ggml-vulkan.cpp 806 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923
  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. typedef std::shared_ptr<struct vk_pipeline_struct> vk_pipeline;
  104. struct vk_pipeline_struct {
  105. std::string name;
  106. vk::ShaderModule shader_module;
  107. vk::PipelineLayout layout;
  108. vk::Pipeline pipeline;
  109. uint32_t push_constant_size;
  110. uint32_t parameter_count;
  111. std::array<uint32_t, 3> wg_denoms;
  112. uint32_t align;
  113. // true if fields have been set by ggml_vk_create_pipeline
  114. bool initialized {};
  115. // set to true to request the pipeline is compiled
  116. std::atomic<bool> needed {};
  117. // set to true when the shader has been compiled
  118. std::atomic<bool> compiled {};
  119. // number of registers used, extracted from pipeline executable properties
  120. uint32_t register_count {};
  121. #if defined(VK_EXT_shader_64bit_indexing)
  122. bool is_64b_indexing {};
  123. #endif
  124. // linked list of pipelines for multiple compilation variants.
  125. // currently only used to compile a 64-bit indexing variant.
  126. vk_pipeline next;
  127. };
  128. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  129. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  130. struct vk_matmul_pipeline_struct {
  131. vk_pipeline l, m, s;
  132. vk_pipeline a_l, a_m, a_s;
  133. // Returns true when all unaligned pipelines are null.
  134. // We only check for unaligned variants since one of the unaligned pipelines must exist
  135. // while aligned pipelines are optional
  136. bool is_empty() const {
  137. return l == nullptr && m == nullptr && s == nullptr;
  138. }
  139. };
  140. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  141. struct vk_matmul_pipeline2 {
  142. vk_matmul_pipeline2() {
  143. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  144. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  145. }
  146. vk_matmul_pipeline f32acc;
  147. vk_matmul_pipeline f16acc;
  148. };
  149. struct vk_device_struct;
  150. typedef std::shared_ptr<vk_device_struct> vk_device;
  151. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  152. struct vk_buffer_struct;
  153. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  154. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  155. struct ggml_backend_vk_buffer_type_context {
  156. std::string name;
  157. vk_device device;
  158. };
  159. struct vk_queue;
  160. // Stores command pool/buffers. There's an instance of this
  161. // for each (context,queue) pair and for each (device,queue) pair.
  162. struct vk_command_pool {
  163. void init(vk_device& device, vk_queue *q_);
  164. void destroy(vk::Device& device);
  165. vk::CommandPool pool;
  166. uint32_t cmd_buffer_idx;
  167. std::vector<vk::CommandBuffer> cmd_buffers;
  168. vk_queue *q;
  169. };
  170. // Prevent simultaneous submissions to the same queue.
  171. // This could be per vk_queue if we stopped having two vk_queue structures
  172. // sharing the same vk::Queue.
  173. static std::mutex queue_mutex;
  174. struct vk_queue {
  175. uint32_t queue_family_index;
  176. vk::Queue queue;
  177. vk_command_pool cmd_pool;
  178. vk::PipelineStageFlags stage_flags;
  179. bool transfer_only;
  180. // copy everything except the cmd_pool
  181. void copyFrom(vk_queue &other) {
  182. queue_family_index = other.queue_family_index;
  183. queue = other.queue;
  184. stage_flags = other.stage_flags;
  185. transfer_only = other.transfer_only;
  186. }
  187. };
  188. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  189. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  190. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  191. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  192. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  193. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  194. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  195. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  196. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  197. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  198. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  199. /* .is_host = */ NULL,
  200. };
  201. class vk_memory_logger;
  202. class vk_perf_logger;
  203. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  204. static void ggml_vk_synchronize(ggml_backend_vk_context * ctx);
  205. static constexpr uint32_t mul_mat_vec_max_cols = 8;
  206. static constexpr uint32_t p021_max_gqa_ratio = 8;
  207. enum vk_device_architecture {
  208. OTHER,
  209. AMD_GCN,
  210. AMD_RDNA1,
  211. AMD_RDNA2,
  212. AMD_RDNA3,
  213. INTEL_XE2,
  214. NVIDIA_PRE_TURING,
  215. };
  216. static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) {
  217. vk::PhysicalDeviceProperties props = device.getProperties();
  218. if (props.vendorID == VK_VENDOR_ID_AMD) {
  219. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  220. bool amd_shader_core_properties = false;
  221. bool integer_dot_product = false;
  222. bool subgroup_size_control = false;
  223. for (const auto& properties : ext_props) {
  224. if (strcmp("VK_AMD_shader_core_properties", properties.extensionName) == 0) {
  225. amd_shader_core_properties = true;
  226. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0) {
  227. integer_dot_product = true;
  228. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  229. subgroup_size_control = true;
  230. }
  231. }
  232. if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) {
  233. return vk_device_architecture::OTHER;
  234. }
  235. vk::PhysicalDeviceProperties2 props2;
  236. vk::PhysicalDeviceShaderCorePropertiesAMD shader_core_props_amd;
  237. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR integer_dot_props;
  238. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  239. props2.pNext = &shader_core_props_amd;
  240. shader_core_props_amd.pNext = &integer_dot_props;
  241. integer_dot_props.pNext = &subgroup_size_control_props;
  242. device.getProperties2(&props2);
  243. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 64) {
  244. return vk_device_architecture::AMD_GCN;
  245. }
  246. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 32) {
  247. // RDNA
  248. if (shader_core_props_amd.wavefrontsPerSimd == 20) {
  249. return vk_device_architecture::AMD_RDNA1;
  250. }
  251. if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
  252. return vk_device_architecture::AMD_RDNA3;
  253. }
  254. return vk_device_architecture::AMD_RDNA2;
  255. }
  256. } else if (props.vendorID == VK_VENDOR_ID_INTEL) {
  257. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  258. bool subgroup_size_control = false;
  259. for (const auto& properties : ext_props) {
  260. if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  261. subgroup_size_control = true;
  262. }
  263. }
  264. if (!subgroup_size_control) {
  265. return vk_device_architecture::OTHER;
  266. }
  267. vk::PhysicalDeviceProperties2 props2;
  268. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  269. props2.pNext = &subgroup_size_control_props;
  270. device.getProperties2(&props2);
  271. if (subgroup_size_control_props.minSubgroupSize == 16) {
  272. // Xe2 architecture uses SIMD16 while previous Xe and Gen architecture uses SIMD8.
  273. // Minimum subgroup size matches the SIMD width so we distinguish architecture by checking this value.
  274. // https://www.intel.com/content/www/us/en/content-details/824434/2024-intel-tech-tour-xe2-and-lunar-lake-s-gpu.html
  275. // https://www.intel.com/content/www/us/en/docs/oneapi/optimization-guide-gpu/2025-0/intel-xe-gpu-architecture.html
  276. return vk_device_architecture::INTEL_XE2;
  277. }
  278. } else if (props.vendorID == VK_VENDOR_ID_NVIDIA) {
  279. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  280. bool cooperative_matrix = false;
  281. // Detect "pre-turing" based on lack of coopmat support.
  282. for (const auto& properties : ext_props) {
  283. if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0) {
  284. cooperative_matrix = true;
  285. break;
  286. }
  287. }
  288. if (!cooperative_matrix) {
  289. return vk_device_architecture::NVIDIA_PRE_TURING;
  290. }
  291. }
  292. return vk_device_architecture::OTHER;
  293. }
  294. enum vk_conv_shapes {
  295. CONV_SHAPE_128x128,
  296. CONV_SHAPE_64x32,
  297. CONV_SHAPE_32x256,
  298. CONV_SHAPE_COUNT,
  299. };
  300. struct vk_conv_block_size {
  301. uint32_t K;
  302. uint32_t NPQ;
  303. uint32_t CRS;
  304. };
  305. vk_conv_block_size vk_conv_block_sizes[CONV_SHAPE_COUNT] = {
  306. // K NPQ CRS
  307. { 128, 128, 16 }, // CONV_SHAPE_128x128
  308. { 64, 32, 32 }, // CONV_SHAPE_64x32
  309. { 32, 256, 16 }, // CONV_SHAPE_32x256
  310. };
  311. enum dmmv_wg_sizes {
  312. DMMV_WG_SIZE_SUBGROUP,
  313. DMMV_WG_SIZE_LARGE,
  314. DMMV_WG_SIZE_COUNT,
  315. };
  316. enum FaCodePath {
  317. FA_SCALAR,
  318. FA_COOPMAT1,
  319. FA_COOPMAT2,
  320. };
  321. struct vk_fa_pipeline_state {
  322. vk_fa_pipeline_state(uint32_t HSK, uint32_t HSV, bool small_rows, bool small_cache, FaCodePath path, bool aligned, bool f32acc)
  323. : HSK(HSK), HSV(HSV), small_rows(small_rows), small_cache(small_cache), path(path), aligned(aligned), f32acc(f32acc) {}
  324. uint32_t HSK, HSV;
  325. bool small_rows, small_cache;
  326. FaCodePath path;
  327. bool aligned;
  328. bool f32acc;
  329. bool operator<(const vk_fa_pipeline_state &b) const {
  330. return std::tie(HSK, HSV, small_rows, small_cache, path, aligned, f32acc) <
  331. std::tie(b.HSK, b.HSV, b.small_rows, b.small_cache, b.path, b.aligned, b.f32acc);
  332. }
  333. };
  334. struct vk_conv2d_pipeline_state {
  335. 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)
  336. : s0(s0), s1(s1), p0(p0), p1(p1), d0(d0), d1(d1), KW(KW), KH(KH) {}
  337. uint32_t s0, s1, p0, p1, d0, d1, KW, KH;
  338. bool operator<(const vk_conv2d_pipeline_state &b) const {
  339. return std::tie(s0, s1, p0, p1, d0, d1, KW, KH) <
  340. std::tie(b.s0, b.s1, b.p0, b.p1, b.d0, b.d1, b.KW, b.KH);
  341. }
  342. };
  343. struct vk_solve_tri_pipeline_state {
  344. vk_solve_tri_pipeline_state(uint32_t N, uint32_t K)
  345. : N(N), K(K) {}
  346. uint32_t N, K;
  347. bool operator<(const vk_solve_tri_pipeline_state &b) const {
  348. return std::tie(N, K) <
  349. std::tie(b.N, b.K);
  350. }
  351. };
  352. enum shader_reduction_mode {
  353. SHADER_REDUCTION_MODE_SHMEM,
  354. SHADER_REDUCTION_MODE_HYBRID,
  355. SHADER_REDUCTION_MODE_SUBGROUP,
  356. SHADER_REDUCTION_MODE_COUNT,
  357. };
  358. // argsort pipelines for up to 1<<10 invocations per workgroup
  359. static constexpr uint32_t num_argsort_pipelines = 11;
  360. static constexpr uint32_t num_topk_moe_pipelines = 10;
  361. static constexpr uint32_t num_topk_pipelines = 11;
  362. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax_norm{ GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  363. GGML_OP_VIEW, GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  364. GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV,
  365. GGML_OP_RESHAPE };
  366. static constexpr std::initializer_list<ggml_op> topk_moe_sigmoid_norm_bias{ GGML_OP_UNARY, GGML_OP_RESHAPE, GGML_OP_ADD,
  367. GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS,
  368. GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, GGML_OP_CLAMP,
  369. GGML_OP_DIV, GGML_OP_RESHAPE };
  370. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax { GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  371. GGML_OP_VIEW, GGML_OP_GET_ROWS };
  372. static constexpr std::initializer_list<ggml_op> topk_moe_late_softmax { GGML_OP_ARGSORT, GGML_OP_VIEW,
  373. GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  374. GGML_OP_SOFT_MAX, GGML_OP_RESHAPE };
  375. //node #978 ( SOFT_MAX): ffn_moe_probs-15 ( 0K) [Vulka ] use=2: ffn_moe_logits-15 ( 0K) [Vulka ]
  376. //node #979 ( RESHAPE): ffn_moe_probs-15 (re ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  377. //node #980 ( ARGSORT): ffn_moe_argsort-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  378. //node #981 ( VIEW): ffn_moe_topk-15 ( 0K) [Vulka ] use=4: ffn_moe_argsort-15 ( 0K) [Vulka ]
  379. //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 ]
  380. //node #983 ( RESHAPE): ffn_moe_weights-15 ( ( 0K) [Vulka ] use=2: ffn_moe_weights-15 ( 0K) [Vulka ]
  381. //node #984 ( SUM_ROWS): ffn_moe_weights_sum- ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ]
  382. //node #985 ( CLAMP): ffn_moe_weights_sum_ ( 0K) [Vulka ] use=1: ffn_moe_weights_sum- ( 0K) [Vulka ]
  383. //node #986 ( DIV): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ] ffn_moe_weights_sum_ ( 0K) [Vulka ]
  384. //node #987 ( RESHAPE): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights_norm ( 0K) [Vulka ]
  385. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_norm_edges {
  386. { 1, 0, 0 }, // reshape->src[0] == softmax
  387. { 2, 0, 0 }, // argsort->src[0] == softmax
  388. { 3, 0, 2 }, // view->src[0] == argsort
  389. { 4, 0, 1 }, // get_rows->src[0] == reshape
  390. { 4, 1, 3 }, // get_rows->src[1] == view
  391. { 5, 0, 4 }, // reshape->src[0] == get_rows
  392. { 6, 0, 5 }, // sum_rows->src[0] == reshape
  393. { 7, 0, 6 }, // clamp->src[0] == sum_rows
  394. { 8, 0, 5 }, // div->src[0] == reshape
  395. { 8, 1, 7 }, // div->src[1] == clamp
  396. { 9, 0, 8 }, // reshape->src[0] == div
  397. };
  398. //node #436 ( UNARY): ffn_moe_probs-10 ( 256K) [Vulka ] use=2: ffn_moe_logits-10 ( 256K) [Vulka ]
  399. //node #437 ( RESHAPE): ffn_moe_probs-10 (re ( 256K) [Vulka ] use=1: ffn_moe_probs-10 ( 256K) [Vulka ]
  400. //node #438 ( ADD): ffn_moe_probs_biased ( 256K) [Vulka ] use=1: ffn_moe_probs-10 ( 256K) [Vulka ] blk.10.exp_probs_b.b ( 0K) [Vulka ]
  401. //node #439 ( ARGSORT): ffn_moe_argsort-10 ( 256K) [Vulka ] use=1: ffn_moe_probs_biased ( 256K) [Vulka ]
  402. //node #440 ( VIEW): ffn_moe_topk-10 ( 255K) [Vulka ] use=3: ffn_moe_argsort-10 ( 256K) [Vulka ]
  403. //node #441 ( GET_ROWS): ffn_moe_weights-10 ( 12K) [Vulka ] use=1: ffn_moe_probs-10 (re ( 256K) [Vulka ] ffn_moe_topk-10 ( 255K) [Vulka ]
  404. //node #442 ( RESHAPE): ffn_moe_weights-10 ( ( 12K) [Vulka ] use=2: ffn_moe_weights-10 ( 12K) [Vulka ]
  405. //node #443 ( SUM_ROWS): ffn_moe_weights_sum- ( 2K) [Vulka ] use=1: ffn_moe_weights-10 ( ( 12K) [Vulka ]
  406. //node #444 ( CLAMP): ffn_moe_weights_sum_ ( 2K) [Vulka ] use=1: ffn_moe_weights_sum- ( 2K) [Vulka ]
  407. //node #445 ( DIV): ffn_moe_weights_norm ( 12K) [Vulka ] use=1: ffn_moe_weights-10 ( ( 12K) [Vulka ] ffn_moe_weights_sum_ ( 2K) [Vulka ]
  408. //node #446 ( RESHAPE): ffn_moe_weights_norm ( 12K) [Vulka ] use=1: ffn_moe_weights_norm ( 12K) [Vulka ]
  409. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_sigmoid_norm_bias_edges {
  410. { 1, 0, 0 }, // reshape->src[0] == sigmoid
  411. { 2, 0, 0 }, // add->src[0] == sigmoid
  412. { 3, 0, 2 }, // argsort->src[0] == add
  413. { 4, 0, 3 }, // view->src[0] == argsort
  414. { 5, 0, 1 }, // get_rows->src[0] == reshape
  415. { 5, 1, 4 }, // get_rows->src[1] == view
  416. { 6, 0, 5 }, // reshape->src[0] == get_rows
  417. { 7, 0, 6 }, // sum_rows->src[0] == reshape
  418. { 8, 0, 7 }, // clamp->src[0] == sum_rows
  419. { 9, 0, 6 }, // div->src[0] == reshape
  420. { 9, 1, 8 }, // div->src[1] == clamp
  421. {10, 0, 9 }, // reshape->src[0] == div
  422. };
  423. // same as early_softmax_norm but ending after the get_rows
  424. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_edges {
  425. { 1, 0, 0 }, // reshape->src[0] == softmax
  426. { 2, 0, 0 }, // argsort->src[0] == softmax
  427. { 3, 0, 2 }, // view->src[0] == argsort
  428. { 4, 0, 1 }, // get_rows->src[0] == reshape
  429. { 4, 1, 3 }, // get_rows->src[1] == view
  430. };
  431. //node #652 ( ARGSORT): ffn_moe_argsort-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 ( 0K) [Vulka ]
  432. //node #653 ( VIEW): ffn_moe_topk-11 ( 0K) [Vulka ] use=7: ffn_moe_argsort-11 ( 0K) [Vulka ]
  433. //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 ]
  434. //node #655 ( RESHAPE): ffn_moe_weights-11 ( ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( 0K) [Vulka ]
  435. //node #656 ( SOFT_MAX): node_656 ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( ( 0K) [Vulka ]
  436. //node #657 ( RESHAPE): ffn_moe_weights_soft ( 0K) [Vulka ] use=1: node_656 ( 0K) [Vulka ]
  437. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_late_softmax_edges {
  438. { 1, 0, 0 }, // view->src[0] == argsort
  439. { 2, 1, 1 }, // get_rows->src[1] == view
  440. { 3, 0, 2 }, // reshape->src[0] == get_rows
  441. { 4, 0, 3 }, // soft_max->src[0] == reshape
  442. { 5, 0, 4 }, // reshape->src[0] == soft_max
  443. };
  444. enum topk_moe_mode {
  445. TOPK_MOE_EARLY_SOFTMAX,
  446. TOPK_MOE_EARLY_SOFTMAX_NORM,
  447. TOPK_MOE_LATE_SOFTMAX,
  448. TOPK_MOE_SIGMOID_NORM_BIAS,
  449. TOPK_MOE_COUNT,
  450. };
  451. static constexpr std::initializer_list<std::array<int, 3>> rope_view_set_rows_edges {
  452. { 1, 0, 0 }, // view->src[0] == rope
  453. { 2, 0, 1 }, // set_rows->src[0] == view
  454. };
  455. static constexpr std::initializer_list<std::array<int, 3>> rms_norm_mul_rope_view_set_rows_edges {
  456. { 1, 0, 0 }, // mul->src[0] == rms
  457. { 2, 0, 1 }, // rope->src[0] == mul
  458. { 3, 0, 2 }, // view->src[0] == rope
  459. { 4, 0, 3 }, // set_rows->src[0] == view
  460. };
  461. struct vk_device_struct {
  462. std::recursive_mutex mutex;
  463. vk::PhysicalDevice physical_device;
  464. vk::PhysicalDeviceProperties properties;
  465. std::string name;
  466. uint64_t max_memory_allocation_size;
  467. uint64_t max_buffer_size;
  468. uint64_t suballocation_block_size;
  469. uint64_t min_imported_host_pointer_alignment;
  470. bool external_memory_host {};
  471. bool fp16;
  472. bool bf16;
  473. bool pipeline_robustness;
  474. bool memory_priority;
  475. vk::Device device;
  476. uint32_t vendor_id;
  477. vk::DriverId driver_id;
  478. vk_device_architecture architecture;
  479. vk_queue compute_queue;
  480. vk_queue transfer_queue;
  481. bool single_queue;
  482. bool support_async;
  483. uint32_t subgroup_size;
  484. uint32_t subgroup_size_log2;
  485. uint32_t shader_core_count;
  486. bool uma;
  487. bool prefer_host_memory;
  488. bool float_controls_rte_fp16;
  489. bool subgroup_basic;
  490. bool subgroup_arithmetic;
  491. bool subgroup_shuffle;
  492. bool subgroup_ballot;
  493. bool subgroup_clustered;
  494. bool subgroup_vote;
  495. bool multi_add;
  496. bool shader_int64;
  497. bool buffer_device_address;
  498. bool vulkan_memory_model;
  499. bool add_rms_fusion;
  500. uint32_t partials_binding_alignment;
  501. bool shader_64b_indexing;
  502. bool integer_dot_product;
  503. // 0: default, 1: force mmvq, -1: disable mmvq
  504. int32_t mmvq_mode;
  505. bool subgroup_size_control;
  506. uint32_t subgroup_min_size;
  507. uint32_t subgroup_max_size;
  508. bool subgroup_require_full_support;
  509. // floor(log2(maxComputeWorkGroupInvocations))
  510. uint32_t max_workgroup_size_log2 {};
  511. bool coopmat_support;
  512. bool coopmat_acc_f32_support {};
  513. bool coopmat_acc_f16_support {};
  514. bool coopmat_bf16_support {};
  515. bool coopmat_support_16x16x16_f16acc {};
  516. bool coopmat_support_16x16x16_f32acc {};
  517. bool coopmat1_fa_support {};
  518. uint32_t coopmat_m;
  519. uint32_t coopmat_n;
  520. uint32_t coopmat_k;
  521. bool coopmat_int_support;
  522. uint32_t coopmat_int_m;
  523. uint32_t coopmat_int_n;
  524. uint32_t coopmat_int_k;
  525. bool coopmat2;
  526. bool pipeline_executable_properties_support {};
  527. size_t idx;
  528. bool mul_mat_l[GGML_TYPE_COUNT];
  529. bool mul_mat_m[GGML_TYPE_COUNT];
  530. bool mul_mat_s[GGML_TYPE_COUNT];
  531. bool mul_mat_id_l[GGML_TYPE_COUNT];
  532. bool mul_mat_id_m[GGML_TYPE_COUNT];
  533. bool mul_mat_id_s[GGML_TYPE_COUNT];
  534. vk::DescriptorSetLayout dsl;
  535. vk_matmul_pipeline pipeline_matmul_f32 {};
  536. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  537. vk_matmul_pipeline pipeline_matmul_bf16 {};
  538. vk_matmul_pipeline2 pipeline_matmul_f16;
  539. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  540. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  541. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  542. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_COUNT];
  543. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  544. vk_matmul_pipeline pipeline_matmul_id_bf16 {};
  545. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  546. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  547. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  548. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_COUNT];
  549. vk_pipeline pipeline_matmul_split_k_reduce;
  550. vk_pipeline pipeline_quantize_q8_1_x4;
  551. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  552. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  553. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  554. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT];
  555. vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  556. vk_pipeline pipeline_dequant_mul_mat_vec_id_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT];
  557. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio];
  558. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  559. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  560. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  561. vk_pipeline pipeline_acc_f32;
  562. // [src0 0=fp32,1=fp16][src1 0=fp32,1=fp16][dst 0=fp32,1=fp16]
  563. vk_pipeline pipeline_add[2][2][2];
  564. vk_pipeline pipeline_add_norepeat[2][2][2];
  565. vk_pipeline pipeline_sub[2][2][2];
  566. vk_pipeline pipeline_sub_norepeat[2][2][2];
  567. vk_pipeline pipeline_mul[2][2][2];
  568. vk_pipeline pipeline_mul_norepeat[2][2][2];
  569. vk_pipeline pipeline_div[2][2][2];
  570. vk_pipeline pipeline_div_norepeat[2][2][2];
  571. vk_pipeline pipeline_add_rms[2][2][2];
  572. vk_pipeline pipeline_add_rms_norepeat[2][2][2];
  573. // indexed by num_additional_fused_ops == num_adds - 1
  574. vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS];
  575. vk_pipeline pipeline_multi_add_rms[MAX_FUSED_ADDS];
  576. vk_pipeline pipeline_add_id_f32;
  577. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  578. vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32, pipeline_upscale_bicubic_f32, pipeline_upscale_bilinear_antialias_f32;
  579. vk_pipeline pipeline_scale_f32;
  580. vk_pipeline pipeline_sqr_f32;
  581. vk_pipeline pipeline_sqrt_f32;
  582. vk_pipeline pipeline_sin_f32;
  583. vk_pipeline pipeline_cos_f32;
  584. vk_pipeline pipeline_log[2];
  585. vk_pipeline pipeline_tri[2];
  586. vk_pipeline pipeline_diag[2];
  587. vk_pipeline pipeline_clamp_f32;
  588. vk_pipeline pipeline_pad_f32;
  589. vk_pipeline pipeline_roll_f32;
  590. vk_pipeline pipeline_repeat_f32, pipeline_repeat_back_f32;
  591. 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;
  592. 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;
  593. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  594. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  595. vk_pipeline pipeline_cpy_transpose_16, pipeline_cpy_transpose_32;
  596. vk_pipeline pipeline_set_rows_i32[GGML_TYPE_COUNT];
  597. vk_pipeline pipeline_set_rows_i64[GGML_TYPE_COUNT];
  598. vk_pipeline pipeline_norm_f32;
  599. vk_pipeline pipeline_group_norm_f32;
  600. vk_pipeline pipeline_rms_norm_f32;
  601. vk_pipeline pipeline_rms_norm_mul_f32;
  602. vk_pipeline pipeline_rms_norm_partials_f32;
  603. vk_pipeline pipeline_rms_norm_mul_partials_f32;
  604. vk_pipeline pipeline_rms_norm_mul_rope_f32_f32;
  605. vk_pipeline pipeline_rms_norm_mul_rope_f32_f16;
  606. vk_pipeline pipeline_rms_norm_back_f32;
  607. vk_pipeline pipeline_l2_norm_f32;
  608. // [src/dst 0=fp32,1=fp16]
  609. vk_pipeline pipeline_exp[2];
  610. vk_pipeline pipeline_gelu[2];
  611. vk_pipeline pipeline_gelu_erf[2];
  612. vk_pipeline pipeline_gelu_quick[2];
  613. vk_pipeline pipeline_silu[2];
  614. vk_pipeline pipeline_relu[2];
  615. vk_pipeline pipeline_xielu[2];
  616. vk_pipeline pipeline_neg[2];
  617. vk_pipeline pipeline_tanh[2];
  618. vk_pipeline pipeline_sigmoid[2];
  619. vk_pipeline pipeline_hardsigmoid[2];
  620. vk_pipeline pipeline_hardswish[2];
  621. vk_pipeline pipeline_abs[2];
  622. vk_pipeline pipeline_softplus[2];
  623. vk_pipeline pipeline_step[2];
  624. vk_pipeline pipeline_round[2];
  625. vk_pipeline pipeline_ceil[2];
  626. vk_pipeline pipeline_floor[2];
  627. vk_pipeline pipeline_trunc[2];
  628. vk_pipeline pipeline_add1_f16_f16;
  629. vk_pipeline pipeline_add1_f16_f32;
  630. vk_pipeline pipeline_add1_f32_f32;
  631. vk_pipeline pipeline_arange_f32;
  632. vk_pipeline pipeline_fill_f32;
  633. vk_pipeline pipeline_geglu[2];
  634. vk_pipeline pipeline_reglu[2];
  635. vk_pipeline pipeline_swiglu[2];
  636. vk_pipeline pipeline_swiglu_oai[2];
  637. vk_pipeline pipeline_geglu_erf[2];
  638. vk_pipeline pipeline_geglu_quick[2];
  639. vk_pipeline pipeline_leaky_relu_f32;
  640. vk_pipeline pipeline_silu_back_f32;
  641. vk_pipeline pipeline_diag_mask_inf_f32;
  642. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  643. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  644. vk_pipeline pipeline_soft_max_back_f32;
  645. vk_pipeline pipeline_soft_max_large1_f32, pipeline_soft_max_large1_f32_f16;
  646. vk_pipeline pipeline_soft_max_large2_f32, pipeline_soft_max_large2_f32_f16;
  647. vk_pipeline pipeline_soft_max_large3_f32, pipeline_soft_max_large3_f32_f16;
  648. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16, pipeline_rope_norm_f32_f16;
  649. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16, pipeline_rope_neox_f32_f16;
  650. vk_pipeline pipeline_rope_multi_f32, pipeline_rope_multi_f16, pipeline_rope_multi_f32_f16;
  651. vk_pipeline pipeline_rope_vision_f32, pipeline_rope_vision_f16;
  652. vk_pipeline pipeline_argsort_f32[num_argsort_pipelines];
  653. vk_pipeline pipeline_argsort_large_f32[num_argsort_pipelines];
  654. vk_pipeline pipeline_topk_f32[num_topk_pipelines];
  655. vk_pipeline pipeline_sum_rows_f32;
  656. vk_pipeline pipeline_cumsum_f32;
  657. vk_pipeline pipeline_cumsum_small_f32;
  658. vk_pipeline pipeline_cumsum_multipass1_f32;
  659. vk_pipeline pipeline_cumsum_multipass2_f32;
  660. vk_pipeline pipeline_argmax_f32;
  661. vk_pipeline pipeline_count_equal_i32;
  662. std::map<vk_solve_tri_pipeline_state, vk_pipeline> pipeline_solve_tri_f32;
  663. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  664. vk_pipeline pipeline_im2col_3d_f32, pipeline_im2col_3d_f32_f16;
  665. vk_pipeline pipeline_timestep_embedding_f32;
  666. vk_pipeline pipeline_conv_transpose_1d_f32;
  667. vk_pipeline pipeline_pool2d_f32;
  668. vk_pipeline pipeline_rwkv_wkv6_f32;
  669. vk_pipeline pipeline_rwkv_wkv7_f32;
  670. vk_pipeline pipeline_ssm_scan_f32_d128;
  671. vk_pipeline pipeline_ssm_scan_f32_d256;
  672. vk_pipeline pipeline_ssm_conv_f32;
  673. vk_pipeline pipeline_opt_step_adamw_f32;
  674. vk_pipeline pipeline_opt_step_sgd_f32;
  675. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f32[CONV_SHAPE_COUNT];
  676. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f16_f32[CONV_SHAPE_COUNT];
  677. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f32[CONV_SHAPE_COUNT];
  678. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f16_f32[CONV_SHAPE_COUNT];
  679. vk_pipeline pipeline_conv2d_dw_whcn_f32, pipeline_conv2d_dw_whcn_f16_f32;
  680. vk_pipeline pipeline_conv2d_dw_cwhn_f32, pipeline_conv2d_dw_cwhn_f16_f32;
  681. std::map<vk_fa_pipeline_state, vk_pipeline> pipeline_flash_attn_f32_f16[GGML_TYPE_COUNT];
  682. vk_pipeline pipeline_flash_attn_split_k_reduce;
  683. vk_pipeline pipeline_count_experts;
  684. // [2] is for whether to take n_experts from spec constant (0) or push constant (1)
  685. vk_pipeline pipeline_topk_moe[num_topk_moe_pipelines][2];
  686. std::vector<vk_pipeline_ref> all_pipelines;
  687. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  688. vk::Fence fence;
  689. vk_buffer sync_staging;
  690. ggml_backend_buffer_type buffer_type;
  691. bool disable_fusion;
  692. bool disable_host_visible_vidmem;
  693. bool allow_sysmem_fallback;
  694. bool disable_graph_optimize;
  695. std::unique_ptr<vk_memory_logger> memory_logger;
  696. ~vk_device_struct() {
  697. VK_LOG_DEBUG("destroy device " << name);
  698. device.destroyFence(fence);
  699. ggml_vk_destroy_buffer(sync_staging);
  700. compute_queue.cmd_pool.destroy(device);
  701. transfer_queue.cmd_pool.destroy(device);
  702. for (auto& pipeline : all_pipelines) {
  703. if (pipeline.expired()) {
  704. continue;
  705. }
  706. vk_pipeline pl = pipeline.lock();
  707. ggml_vk_destroy_pipeline(device, pl);
  708. }
  709. all_pipelines.clear();
  710. device.destroyDescriptorSetLayout(dsl);
  711. device.destroy();
  712. }
  713. };
  714. void vk_command_pool::init(vk_device& device, vk_queue *q_) {
  715. cmd_buffer_idx = 0;
  716. q = q_;
  717. vk::CommandPoolCreateInfo command_pool_create_info(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), q->queue_family_index);
  718. pool = device->device.createCommandPool(command_pool_create_info);
  719. }
  720. void vk_command_pool::destroy(vk::Device& device) {
  721. device.destroyCommandPool(pool);
  722. pool = nullptr;
  723. cmd_buffers.clear();
  724. }
  725. struct vk_buffer_struct {
  726. vk::Buffer buffer = VK_NULL_HANDLE;
  727. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  728. vk::MemoryPropertyFlags memory_property_flags;
  729. void * ptr;
  730. size_t size = 0;
  731. vk::DeviceAddress bda_addr {};
  732. vk_device device;
  733. ~vk_buffer_struct() {
  734. if (size == 0) {
  735. return;
  736. }
  737. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  738. device->device.freeMemory(device_memory);
  739. device->device.destroyBuffer(buffer);
  740. }
  741. };
  742. struct vk_subbuffer {
  743. vk_buffer buffer;
  744. uint64_t offset;
  745. uint64_t size;
  746. operator vk::DescriptorBufferInfo() const {
  747. return { buffer->buffer, offset, size };
  748. }
  749. };
  750. // vk_event is used for the event-related backend interfaces. It uses 'event' for
  751. // event_wait and 'fence' for event_synchronize. Polling on an event for
  752. // event_synchronize wouldn't be sufficient to wait for command buffers to complete,
  753. // and would lead to validation errors.
  754. struct vk_event {
  755. vk::Event event;
  756. vk::Fence fence;
  757. };
  758. struct vk_semaphore {
  759. vk::Semaphore s;
  760. uint64_t value;
  761. };
  762. struct vk_submission {
  763. vk::CommandBuffer buffer;
  764. std::vector<vk_semaphore> wait_semaphores;
  765. std::vector<vk_semaphore> signal_semaphores;
  766. };
  767. typedef std::vector<vk_submission> vk_sequence;
  768. struct vk_mat_mat_push_constants {
  769. uint32_t M; uint32_t N; uint32_t K;
  770. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  771. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  772. uint32_t k_split;
  773. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  774. uint32_t padded_N;
  775. };
  776. #define MAT_VEC_FUSION_FLAGS_BIAS0 0x1
  777. #define MAT_VEC_FUSION_FLAGS_BIAS1 0x2
  778. #define MAT_VEC_FUSION_FLAGS_SCALE0 0x4
  779. #define MAT_VEC_FUSION_FLAGS_SCALE1 0x8
  780. struct vk_mat_vec_push_constants {
  781. uint32_t ncols;
  782. uint32_t stride_a;
  783. uint32_t stride_b;
  784. uint32_t stride_d;
  785. uint32_t batch_stride_a;
  786. uint32_t batch_stride_b;
  787. uint32_t batch_stride_d;
  788. uint32_t fusion_flags;
  789. uint32_t ne02;
  790. uint32_t ne12;
  791. uint32_t broadcast2;
  792. uint32_t broadcast3;
  793. };
  794. struct vk_mat_vec_p021_push_constants {
  795. uint32_t ncols_x;
  796. uint32_t nrows_x;
  797. uint32_t nchannels_x;
  798. uint32_t nchannels_y;
  799. uint32_t b_offset;
  800. uint32_t d_offset;
  801. uint32_t fusion_flags;
  802. };
  803. struct vk_mat_vec_nc_push_constants {
  804. uint32_t ncols_x;
  805. uint32_t nrows_x;
  806. uint32_t row_stride_x;
  807. uint32_t channel_stride_x;
  808. uint32_t channel_stride_y;
  809. uint32_t channel_x_divisor;
  810. uint32_t ne12;
  811. uint32_t b_offset;
  812. uint32_t d_offset;
  813. uint32_t nb03;
  814. uint32_t nb13;
  815. uint32_t nb23;
  816. uint32_t fusion_flags;
  817. };
  818. struct vk_mat_mat_id_push_constants {
  819. uint32_t M; uint32_t N; uint32_t K;
  820. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  821. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  822. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  823. uint32_t padded_N;
  824. };
  825. struct vk_mat_vec_id_push_constants {
  826. uint32_t ncols;
  827. uint32_t stride_a;
  828. uint32_t stride_b;
  829. uint32_t stride_d;
  830. uint32_t batch_stride_a;
  831. uint32_t batch_stride_b;
  832. uint32_t batch_stride_d;
  833. uint32_t fusion_flags;
  834. uint32_t nei0;
  835. uint32_t ne11;
  836. };
  837. struct vk_flash_attn_push_constants {
  838. uint32_t N;
  839. uint32_t KV;
  840. uint32_t ne1;
  841. uint32_t ne2;
  842. uint32_t ne3;
  843. uint32_t neq2;
  844. uint32_t neq3;
  845. uint32_t nek2;
  846. uint32_t nek3;
  847. uint32_t nev2;
  848. uint32_t nev3;
  849. uint32_t nem1;
  850. uint32_t nem2;
  851. uint32_t nem3;
  852. uint32_t nb01;
  853. uint32_t nb02;
  854. uint32_t nb03;
  855. uint32_t nb11;
  856. uint32_t nb12;
  857. uint32_t nb13;
  858. uint32_t nb21;
  859. uint32_t nb22;
  860. uint32_t nb23;
  861. float scale;
  862. float max_bias;
  863. float logit_softcap;
  864. uint32_t mask_n_head_log2;
  865. float m0;
  866. float m1;
  867. uint32_t gqa_ratio;
  868. uint32_t split_kv;
  869. uint32_t k_num;
  870. };
  871. static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128");
  872. struct vk_op_push_constants {
  873. uint32_t KX;
  874. uint32_t KY;
  875. float param1;
  876. float param2;
  877. float param3;
  878. float param4;
  879. };
  880. struct vk_op_count_experts_push_constants {
  881. uint32_t ne00;
  882. uint32_t ne01;
  883. uint32_t nb00;
  884. uint32_t nb01;
  885. uint32_t a_offset;
  886. };
  887. struct vk_op_glu_push_constants {
  888. uint32_t N;
  889. uint32_t ne00;
  890. uint32_t ne20;
  891. uint32_t mode; // 0: default, 1: swapped, 2: split
  892. float alpha; // for swiglu_oai
  893. float limit;
  894. };
  895. struct vk_op_unary_push_constants {
  896. uint32_t ne;
  897. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  898. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  899. uint32_t misalign_offsets;
  900. float param1; float param2;
  901. uint32_t ne0_012mp; uint32_t ne0_012L;
  902. uint32_t ne0_01mp; uint32_t ne0_01L;
  903. uint32_t ne0_0mp; uint32_t ne0_0L;
  904. uint32_t ne1_012mp; uint32_t ne1_012L;
  905. uint32_t ne1_01mp; uint32_t ne1_01L;
  906. uint32_t ne1_0mp; uint32_t ne1_0L;
  907. };
  908. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  909. static vk_op_unary_push_constants vk_op_unary_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst, int64_t ne = 0) {
  910. GGML_ASSERT(ne != 0 || (ggml_nelements(src0) == ggml_nelements(dst)));
  911. ne = ne != 0 ? ne : ggml_nelements(dst);
  912. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  913. vk_op_unary_push_constants p{};
  914. p.ne = (uint32_t)ne;
  915. size_t src0_tsize = ggml_type_size(src0->type);
  916. p.ne00 = (uint32_t)src0->ne[0];
  917. p.ne01 = (uint32_t)src0->ne[1];
  918. p.ne02 = (uint32_t)src0->ne[2];
  919. p.ne03 = (uint32_t)src0->ne[3];
  920. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  921. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  922. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  923. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  924. size_t dst_tsize = ggml_type_size(dst->type);
  925. p.ne10 = (uint32_t)dst->ne[0];
  926. p.ne11 = (uint32_t)dst->ne[1];
  927. p.ne12 = (uint32_t)dst->ne[2];
  928. p.ne13 = (uint32_t)dst->ne[3];
  929. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  930. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  931. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  932. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  933. return p; // offsets are initialized later in ggml_vk_op
  934. }
  935. struct vk_op_pad_push_constants {
  936. uint32_t ne;
  937. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  938. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  939. uint32_t misalign_offsets;
  940. uint32_t circular;
  941. uint32_t lp0; uint32_t rp0;
  942. uint32_t lp1; uint32_t rp1;
  943. uint32_t lp2; uint32_t rp2;
  944. uint32_t lp3; uint32_t rp3;
  945. };
  946. static vk_op_pad_push_constants vk_op_pad_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst) {
  947. int64_t ne = ggml_nelements(dst);
  948. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  949. vk_op_pad_push_constants p{};
  950. p.ne = (uint32_t)ne;
  951. size_t src0_tsize = ggml_type_size(src0->type);
  952. p.ne00 = (uint32_t)src0->ne[0];
  953. p.ne01 = (uint32_t)src0->ne[1];
  954. p.ne02 = (uint32_t)src0->ne[2];
  955. p.ne03 = (uint32_t)src0->ne[3];
  956. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  957. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  958. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  959. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  960. size_t dst_tsize = ggml_type_size(dst->type);
  961. p.ne10 = (uint32_t)dst->ne[0];
  962. p.ne11 = (uint32_t)dst->ne[1];
  963. p.ne12 = (uint32_t)dst->ne[2];
  964. p.ne13 = (uint32_t)dst->ne[3];
  965. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  966. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  967. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  968. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  969. p.lp0 = dst->op_params[0];
  970. p.rp0 = dst->op_params[1];
  971. p.lp1 = dst->op_params[2];
  972. p.rp1 = dst->op_params[3];
  973. p.lp2 = dst->op_params[4];
  974. p.rp2 = dst->op_params[5];
  975. p.lp3 = dst->op_params[6];
  976. p.rp3 = dst->op_params[7];
  977. p.circular = dst->op_params[8];
  978. return p; // fastdiv values and offsets are initialized later in ggml_vk_op
  979. }
  980. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  981. // Precompute mp (m' in the paper) and L such that division
  982. // can be computed using a multiply (high 32b of 64b result)
  983. // and a shift:
  984. //
  985. // n/d = (mulhi(n, mp) + n) >> L;
  986. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  987. {
  988. // compute L = ceil(log2(d));
  989. L = 0;
  990. while (L < 32 && (uint32_t{1} << L) < d) {
  991. L++;
  992. }
  993. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  994. }
  995. template <typename T> void init_pushconst_fastdiv(T &p) {
  996. GGML_UNUSED(p);
  997. static_assert(!std::is_const<T>::value, "unexpected type");
  998. }
  999. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  1000. // Compute magic values to divide by these six numbers.
  1001. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  1002. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  1003. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  1004. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  1005. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  1006. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  1007. }
  1008. struct vk_op_binary_push_constants {
  1009. uint32_t ne;
  1010. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1011. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  1012. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  1013. uint32_t misalign_offsets;
  1014. float param1; float param2; int32_t param3;
  1015. };
  1016. struct vk_op_multi_add_push_constants {
  1017. // shape for dst
  1018. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23;
  1019. // strides for srcs+dst
  1020. uint32_t nb[MAX_PARAMETER_COUNT][4];
  1021. uint32_t rms_partials;
  1022. };
  1023. // update multi_add.comp if this changes
  1024. static_assert(MAX_PARAMETER_COUNT == 12);
  1025. static_assert(sizeof(vk_op_multi_add_push_constants) <= 256);
  1026. struct vk_op_topk_moe_push_constants {
  1027. uint32_t n_rows;
  1028. uint32_t n_experts_push;
  1029. uint32_t n_expert_used;
  1030. float clamp_min;
  1031. float clamp_max;
  1032. uint32_t gating_func;
  1033. uint32_t has_bias;
  1034. uint32_t with_norm;
  1035. float output_scale;
  1036. float output_bias;
  1037. };
  1038. struct vk_op_add_id_push_constants {
  1039. uint32_t ne0;
  1040. uint32_t ne1;
  1041. uint32_t s01;
  1042. uint32_t s02;
  1043. uint32_t s11;
  1044. uint32_t s21;
  1045. };
  1046. struct vk_op_diag_mask_push_constants {
  1047. uint32_t ncols;
  1048. uint32_t rows_per_channel;
  1049. int32_t n_past;
  1050. };
  1051. struct vk_op_rope_push_constants {
  1052. uint32_t rope_mode;
  1053. uint32_t ncols;
  1054. uint32_t nrows;
  1055. uint32_t n_dims;
  1056. float freq_scale;
  1057. uint32_t p_delta_rows;
  1058. float freq_base;
  1059. float ext_factor;
  1060. float attn_factor;
  1061. float corr_dims[2];
  1062. float theta_scale;
  1063. uint32_t has_ff;
  1064. uint32_t ne02;
  1065. uint32_t s1;
  1066. uint32_t s2;
  1067. int32_t sections[4];
  1068. uint32_t is_imrope;
  1069. uint32_t is_back;
  1070. uint32_t set_rows_stride;
  1071. };
  1072. // For fused rms_norm+mul+rope(+view+set_rows)
  1073. struct vk_op_rms_norm_mul_rope_push_constants {
  1074. vk_op_binary_push_constants bin;
  1075. vk_op_rope_push_constants rope;
  1076. };
  1077. struct vk_op_soft_max_push_constants {
  1078. uint32_t KX;
  1079. uint32_t KY;
  1080. uint32_t ne00;
  1081. uint32_t ne01;
  1082. uint32_t ne02;
  1083. uint32_t ne12;
  1084. uint32_t ne13;
  1085. uint32_t nb11;
  1086. uint32_t nb12;
  1087. uint32_t nb13;
  1088. float scale;
  1089. float max_bias;
  1090. float m0;
  1091. float m1;
  1092. uint32_t n_head_log2;
  1093. uint32_t nrows_x;
  1094. uint32_t has_sinks;
  1095. };
  1096. struct vk_op_argsort_push_constants {
  1097. uint32_t ncols;
  1098. uint32_t ncols_padded;
  1099. uint32_t ncols_padded_log2;
  1100. uint32_t nrows;
  1101. uint32_t order;
  1102. uint32_t outer_start;
  1103. uint32_t outer_end;
  1104. uint32_t inner_start;
  1105. uint32_t inner_end;
  1106. };
  1107. struct vk_op_topk_push_constants {
  1108. uint32_t orig_ncols;
  1109. uint32_t ncols_input;
  1110. uint32_t ncols_output;
  1111. uint32_t k;
  1112. uint32_t nrows;
  1113. uint32_t first_pass;
  1114. uint32_t last_pass;
  1115. };
  1116. struct vk_op_im2col_push_constants {
  1117. uint64_t dst_addr;
  1118. uint32_t batch_offset; uint32_t offset_delta;
  1119. uint32_t IC;
  1120. uint32_t IW; uint32_t IH;
  1121. uint32_t OW; uint32_t OH;
  1122. uint32_t KW; uint32_t KH;
  1123. uint32_t pelements;
  1124. uint32_t CHW;
  1125. int32_t s0; int32_t s1;
  1126. int32_t p0; int32_t p1;
  1127. int32_t d0; int32_t d1;
  1128. uint32_t batch_IC;
  1129. };
  1130. struct vk_op_im2col_3d_push_constants {
  1131. uint64_t dst_addr;
  1132. uint32_t nb10;
  1133. uint32_t nb11;
  1134. uint32_t nb12;
  1135. uint32_t nb13;
  1136. uint32_t s0;
  1137. uint32_t s1;
  1138. uint32_t s2;
  1139. uint32_t p0;
  1140. uint32_t p1;
  1141. uint32_t p2;
  1142. uint32_t d0;
  1143. uint32_t d1;
  1144. uint32_t d2;
  1145. uint32_t IW;
  1146. uint32_t IH;
  1147. uint32_t ID;
  1148. uint32_t IC;
  1149. uint32_t KW;
  1150. uint32_t OH;
  1151. uint32_t KD_KH_KW;
  1152. uint32_t KH_KW;
  1153. uint32_t IC_KD_KH_KW;
  1154. uint32_t N_OD_OH;
  1155. uint32_t OD_OH;
  1156. uint32_t OD_OH_OW_IC_KD_KH_KW;
  1157. uint32_t OH_OW_IC_KD_KH_KW;
  1158. uint32_t OW_IC_KD_KH_KW;
  1159. uint32_t misalign_offsets;
  1160. };
  1161. struct vk_op_timestep_embedding_push_constants {
  1162. uint32_t nb1;
  1163. uint32_t dim;
  1164. uint32_t max_period;
  1165. };
  1166. struct vk_op_conv_transpose_1d_push_constants {
  1167. uint32_t Cout;
  1168. uint32_t Cin;
  1169. uint32_t K;
  1170. uint32_t L;
  1171. uint32_t KL;
  1172. uint32_t nb01;
  1173. uint32_t nb02;
  1174. uint32_t nb11;
  1175. uint32_t nb1;
  1176. int32_t s0;
  1177. };
  1178. struct vk_op_pool2d_push_constants {
  1179. uint32_t IW; uint32_t IH;
  1180. uint32_t OW; uint32_t OH;
  1181. uint32_t OC;
  1182. uint32_t pelements;
  1183. uint32_t op;
  1184. int32_t k0; int32_t k1;
  1185. int32_t s0; int32_t s1;
  1186. int32_t p0; int32_t p1;
  1187. };
  1188. struct vk_op_rwkv_wkv6_push_constants {
  1189. uint32_t B;
  1190. uint32_t T;
  1191. uint32_t C;
  1192. uint32_t H;
  1193. };
  1194. struct vk_op_rwkv_wkv7_push_constants {
  1195. uint32_t B;
  1196. uint32_t T;
  1197. uint32_t C;
  1198. uint32_t H;
  1199. };
  1200. struct vk_op_ssm_scan_push_constants {
  1201. uint32_t nb02, nb03, nb12, nb13;
  1202. uint32_t nb21, nb22, nb31;
  1203. uint32_t nb42, nb43, nb52, nb53;
  1204. uint32_t s_off;
  1205. uint32_t n_head, d_head, n_group, n_tok;
  1206. };
  1207. struct vk_op_ssm_conv_push_constants {
  1208. uint32_t nb01, nb02;
  1209. uint32_t nb11;
  1210. uint32_t dst_nb0, dst_nb1, dst_nb2;
  1211. uint32_t nc, ncs, nr, n_t, n_s;
  1212. };
  1213. struct vk_op_conv2d_push_constants {
  1214. uint32_t Cout;
  1215. uint32_t Cin;
  1216. uint32_t N;
  1217. uint32_t W;
  1218. uint32_t H;
  1219. uint32_t OW;
  1220. uint32_t OH;
  1221. uint32_t nb01;
  1222. uint32_t nb02;
  1223. uint32_t nb03;
  1224. uint32_t nb11;
  1225. uint32_t nb12;
  1226. uint32_t nb13;
  1227. uint32_t nb1;
  1228. uint32_t nb2;
  1229. uint32_t nb3;
  1230. // init_fastdiv_values constants for dividing by OW, OW*OH
  1231. uint32_t OWmp; uint32_t OWL;
  1232. uint32_t OWOHmp; uint32_t OWOHL;
  1233. };
  1234. template <> void init_pushconst_fastdiv(vk_op_conv2d_push_constants &p) {
  1235. // Compute magic values to divide by OW, OW*OH
  1236. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1237. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1238. }
  1239. struct vk_op_conv2d_dw_push_constants {
  1240. uint32_t ne;
  1241. uint32_t batches;
  1242. uint32_t channels;
  1243. uint32_t dst_w;
  1244. uint32_t dst_h;
  1245. uint32_t src_w;
  1246. uint32_t src_h;
  1247. uint32_t knl_w;
  1248. uint32_t knl_h;
  1249. int32_t stride_x;
  1250. int32_t stride_y;
  1251. int32_t pad_x;
  1252. int32_t pad_y;
  1253. int32_t dilation_x;
  1254. int32_t dilation_y;
  1255. };
  1256. struct vk_op_upscale_push_constants {
  1257. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  1258. uint32_t ne00; uint32_t ne01;
  1259. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1260. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  1261. float sf0; float sf1; float sf2; float sf3;
  1262. float pixel_offset;
  1263. };
  1264. struct vk_op_sum_rows_push_constants
  1265. {
  1266. uint32_t n_cols;
  1267. uint32_t ne01, ne02;
  1268. uint32_t nb01, nb02, nb03;
  1269. uint32_t nb11, nb12, nb13;
  1270. float weight;
  1271. uint32_t misalign_offsets;
  1272. uint32_t ne0_12mp, ne0_12L;
  1273. uint32_t ne0_1mp, ne0_1L;
  1274. };
  1275. 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) {
  1276. uint32_t type_size = (uint32_t)ggml_type_size(src->type);
  1277. vk_op_sum_rows_push_constants p = {};
  1278. p.n_cols = (uint32_t)n_cols;
  1279. p.ne01 = (uint32_t)src->ne[1];
  1280. p.ne02 = (uint32_t)src->ne[2];
  1281. p.nb01 = (uint32_t)src->nb[1] / type_size;
  1282. p.nb02 = (uint32_t)src->nb[2] / type_size;
  1283. p.nb03 = (uint32_t)src->nb[3] / type_size;
  1284. p.nb11 = (uint32_t)dst->nb[1] / type_size;
  1285. p.nb12 = (uint32_t)dst->nb[2] / type_size;
  1286. p.nb13 = (uint32_t)dst->nb[3] / type_size;
  1287. p.weight = 1.0f;
  1288. return p;
  1289. }
  1290. template <> void init_pushconst_fastdiv(vk_op_sum_rows_push_constants &p) {
  1291. init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L);
  1292. init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L);
  1293. }
  1294. struct vk_quantize_q8_1_push_constants {
  1295. uint32_t ne;
  1296. uint32_t num_blocks;
  1297. };
  1298. // Allow pre-recording command buffers
  1299. struct vk_staging_memcpy {
  1300. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  1301. void * dst;
  1302. const void * src;
  1303. size_t n;
  1304. };
  1305. struct vk_staging_memset {
  1306. vk_staging_memset(void * _dst, uint32_t _val, size_t _n) : dst(_dst), val(_val), n(_n) {}
  1307. void * dst;
  1308. uint32_t val;
  1309. size_t n;
  1310. };
  1311. struct vk_context_struct {
  1312. vk_submission * s;
  1313. std::vector<vk_sequence> seqs;
  1314. int exit_tensor_idx;
  1315. std::vector<vk_staging_memcpy> in_memcpys;
  1316. std::vector<vk_staging_memcpy> out_memcpys;
  1317. std::vector<vk_staging_memset> memsets;
  1318. vk_command_pool * p {};
  1319. };
  1320. typedef std::shared_ptr<vk_context_struct> vk_context;
  1321. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  1322. struct ggml_vk_garbage_collector {
  1323. std::vector<vk_semaphore> tl_semaphores;
  1324. std::vector<vk_semaphore> semaphores;
  1325. std::vector<vk::Event> events;
  1326. std::vector<vk_context> contexts;
  1327. };
  1328. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx);
  1329. static void ggml_vk_load_shaders(vk_device& device);
  1330. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx);
  1331. static bool vk_memory_logger_enabled = false;
  1332. #define VK_LOG_MEMORY(msg) if (vk_memory_logger_enabled) { std::cerr << "ggml_vulkan memory: " << msg << std::endl; }
  1333. static std::string format_size(size_t size) {
  1334. const size_t kib = 1024;
  1335. const size_t mib = kib * 1024;
  1336. const size_t gib = mib * 1024;
  1337. std::ostringstream oss;
  1338. oss << std::fixed << std::setprecision(2);
  1339. if (size >= gib) {
  1340. oss << static_cast<double>(size) / gib << " GiB";
  1341. } else if (size >= mib) {
  1342. oss << static_cast<double>(size) / mib << " MiB";
  1343. } else if (size >= kib) {
  1344. oss << static_cast<double>(size) / kib << " KiB";
  1345. } else {
  1346. oss << size << " B";
  1347. }
  1348. return oss.str();
  1349. }
  1350. class vk_memory_logger {
  1351. public:
  1352. vk_memory_logger(): total_device(0), total_host(0) {}
  1353. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  1354. void log_deallocation(vk_buffer_ref buf_ref);
  1355. private:
  1356. std::map<vk::Buffer, size_t> allocations; // Track allocations
  1357. size_t total_device;
  1358. size_t total_host;
  1359. static std::mutex log_mutex;
  1360. };
  1361. std::mutex vk_memory_logger::log_mutex;
  1362. static bool vk_perf_logger_enabled = false;
  1363. static bool vk_perf_logger_concurrent = false;
  1364. static bool vk_enable_sync_logger = false;
  1365. // number of calls between perf logger prints
  1366. static uint32_t vk_perf_logger_frequency = 1;
  1367. class vk_perf_logger {
  1368. public:
  1369. void print_timings(bool force = false) {
  1370. if (timings.empty()) {
  1371. return;
  1372. }
  1373. print_count++;
  1374. if ((print_count % vk_perf_logger_frequency) != 0 && !force) {
  1375. return;
  1376. }
  1377. print_count = 0;
  1378. uint64_t total_all_op_times = 0;
  1379. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  1380. for (const auto & t : timings) {
  1381. uint64_t total_op_times = 0;
  1382. for (const auto & time : t.second) {
  1383. total_op_times += time;
  1384. }
  1385. std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0)
  1386. << " us = " << (total_op_times / 1000.0) << " us";
  1387. // If we have as many flops entries as timing entries for the op, then compute and log the flops/S.
  1388. auto it = flops.find(t.first);
  1389. if (it != flops.end() && (it->second).size() == t.second.size()) {
  1390. uint64_t total_op_flops = 0;
  1391. for (const auto & elem : it->second) {
  1392. total_op_flops += elem;
  1393. }
  1394. std::cerr << " ("
  1395. << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) /
  1396. (double(total_op_times) / (1000.0 * 1000.0 * 1000.0))
  1397. << " GFLOPS/s)";
  1398. }
  1399. total_all_op_times += total_op_times;
  1400. std::cerr << std::endl;
  1401. }
  1402. if (timings.size() > 0) {
  1403. std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl;
  1404. }
  1405. timings.clear();
  1406. flops.clear();
  1407. }
  1408. std::string get_node_fusion_name(const ggml_tensor * node, const char *fusion_name, uint64_t *n_flops) {
  1409. *n_flops = 0;
  1410. std::string fusion_str;
  1411. if (fusion_name) {
  1412. fusion_str = fusion_name + std::string(" ");
  1413. }
  1414. if (node->op == GGML_OP_UNARY) {
  1415. return fusion_str + ggml_unary_op_name(ggml_get_unary_op(node));
  1416. }
  1417. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  1418. const uint64_t m = node->ne[0];
  1419. const uint64_t n = node->ne[1];
  1420. const uint64_t k = node->src[1]->ne[0];
  1421. const uint64_t batch = node->ne[2] * node->ne[3];
  1422. std::string name = ggml_op_name(node->op);
  1423. if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) ||
  1424. (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) {
  1425. name += "_VEC";
  1426. }
  1427. name += " ";
  1428. name += ggml_type_name(node->src[0]->type);
  1429. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  1430. if (node->op == GGML_OP_MUL_MAT_ID) {
  1431. name += " n_expert=" + std::to_string(node->src[0]->ne[2]);
  1432. }
  1433. if (batch > 1) {
  1434. name += " batch=" + std::to_string(batch);
  1435. }
  1436. name = fusion_str + name;
  1437. *n_flops = m * n * (k + (k - 1)) * batch;
  1438. return name;
  1439. }
  1440. if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) {
  1441. std::string name = ggml_op_name(node->op);
  1442. ggml_tensor * knl = node->src[0];
  1443. uint64_t OW = node->ne[0];
  1444. uint64_t OH = node->ne[1];
  1445. uint64_t N = node->ne[3];
  1446. uint64_t Cout = node->ne[2];
  1447. uint64_t KW = knl->ne[0];
  1448. uint64_t KH = knl->ne[1];
  1449. uint64_t Cin = node->src[1]->ne[2];
  1450. // KxCRS @ CRSxNPQ = KxNPQ -> M=K, K=CRS, N=NPQ
  1451. uint64_t size_M = Cout;
  1452. uint64_t size_K = Cin * KW * KH;
  1453. uint64_t size_N = N * OW * OH;
  1454. *n_flops = size_M * size_N * (size_K + (size_K - 1));
  1455. name += " M=Cout=" + std::to_string(size_M) + ", K=Cin*KW*KH=" + std::to_string(size_K) +
  1456. ", N=N*OW*OH=" + std::to_string(size_N);
  1457. name = fusion_str + name;
  1458. return name;
  1459. }
  1460. if (node->op == GGML_OP_RMS_NORM) {
  1461. std::string name = ggml_op_name(node->op);
  1462. 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]) + ")";
  1463. name = fusion_str + name;
  1464. return name;
  1465. }
  1466. if (node->op == GGML_OP_FLASH_ATTN_EXT) {
  1467. const ggml_tensor * dst = node;
  1468. const ggml_tensor * q = node->src[0];
  1469. const ggml_tensor * k = node->src[1];
  1470. const ggml_tensor * v = node->src[2];
  1471. const ggml_tensor * m = node->src[3];
  1472. std::stringstream name;
  1473. name << fusion_str;
  1474. name << ggml_op_name(node->op) <<
  1475. " dst(" << dst->ne[0] << "," << dst->ne[1] << "," << dst->ne[2] << "," << dst->ne[3] << "), " <<
  1476. " q(" << q->ne[0] << "," << q->ne[1] << "," << q->ne[2] << "," << q->ne[3] << "), " <<
  1477. " k(" << k->ne[0] << "," << k->ne[1] << "," << k->ne[2] << "," << k->ne[3] << "), " <<
  1478. " v(" << v->ne[0] << "," << v->ne[1] << "," << v->ne[2] << "," << v->ne[3] << "), " <<
  1479. " m(" << (m?m->ne[0]:0) << "," << (m?m->ne[1]:0) << "," << (m?m->ne[2]:0) << "," << (m?m->ne[3]:0) << ")";
  1480. return name.str();
  1481. }
  1482. if (node->op == GGML_OP_TOP_K) {
  1483. std::stringstream name;
  1484. name << fusion_str;
  1485. name << ggml_op_name(node->op) <<
  1486. " K=" << node->ne[0] <<
  1487. " (" << node->src[0]->ne[0] << "," << node->src[0]->ne[1] << "," << node->src[0]->ne[2] << "," << node->src[0]->ne[3] << ")";
  1488. return name.str();
  1489. }
  1490. return fusion_str + ggml_op_name(node->op);
  1491. }
  1492. void log_timing(const ggml_tensor * node, const char *fusion_name, uint64_t time) {
  1493. uint64_t n_flops;
  1494. std::string name = get_node_fusion_name(node, fusion_name, &n_flops);
  1495. if (n_flops) {
  1496. flops[name].push_back(n_flops);
  1497. }
  1498. timings[name].push_back(time);
  1499. }
  1500. void log_timing(const std::vector<ggml_tensor *> &nodes, const std::vector<const char *> &names, uint64_t time) {
  1501. uint64_t total_flops = 0;
  1502. std::string name;
  1503. for (size_t n = 0; n < nodes.size(); ++n) {
  1504. uint64_t n_flops = 0;
  1505. name += get_node_fusion_name(nodes[n], names[n], &n_flops);
  1506. total_flops += n_flops;
  1507. if (n != nodes.size() - 1) {
  1508. name += ", ";
  1509. }
  1510. }
  1511. if (total_flops) {
  1512. flops[name].push_back(total_flops);
  1513. }
  1514. timings[name].push_back(time);
  1515. }
  1516. private:
  1517. std::map<std::string, std::vector<uint64_t>> timings;
  1518. std::map<std::string, std::vector<uint64_t>> flops;
  1519. uint32_t print_count {};
  1520. };
  1521. struct ggml_backend_vk_context {
  1522. std::string name;
  1523. vk_device device;
  1524. size_t semaphore_idx, event_idx;
  1525. ggml_vk_garbage_collector gc;
  1526. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset;
  1527. vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials, sync_staging;
  1528. vk::Fence fence, almost_ready_fence;
  1529. bool submit_pending {};
  1530. bool almost_ready_fence_pending {};
  1531. // Set before op_add and unset after op_rms_norm to indicate that the add should
  1532. // write partial sums to accumulate the square of the vector components
  1533. bool do_add_rms_partials_offset_calculation;
  1534. bool do_add_rms_partials;
  1535. uint64_t last_total_mul_mat_bytes {};
  1536. // Cache most recent tensor that was converted into prealloc_y, and what pipeline it used to convert.
  1537. vk_pipeline_struct * prealloc_y_last_pipeline_used {};
  1538. const ggml_tensor * prealloc_y_last_tensor_used {};
  1539. // Track which nodes have been used since the last sync, and whether they were written to
  1540. std::vector<const ggml_tensor *> unsynced_nodes_written;
  1541. std::vector<const ggml_tensor *> unsynced_nodes_read;
  1542. // Track which prealloc buffers have pending reads that need to be synchronized.
  1543. // These are checked before writing to the buffer (and call ggml_vk_sync_buffers if set),
  1544. // and set to true after the buffer contents are consumed.
  1545. bool prealloc_x_need_sync, prealloc_y_need_sync, prealloc_split_k_need_sync;
  1546. vk_context_ref compute_ctx;
  1547. vk_context_ref transfer_ctx;
  1548. std::vector<vk_context_ref> tensor_ctxs;
  1549. std::vector<vk::DescriptorPool> descriptor_pools;
  1550. std::vector<vk::DescriptorSet> descriptor_sets;
  1551. uint32_t descriptor_set_idx {};
  1552. uint32_t pipeline_descriptor_set_requirements {};
  1553. vk_command_pool compute_cmd_pool;
  1554. vk_command_pool transfer_cmd_pool;
  1555. // number of additional consecutive nodes that are being fused with the
  1556. // node currently being processed
  1557. int num_additional_fused_ops {};
  1558. // Bitmask of which fused ops need to write an intermediate value to memory.
  1559. // Bit 'i' means nodes[start_of_fusion + i] writes to memory.
  1560. // If there's no fusion, bit 0 is still set.
  1561. int fused_ops_write_mask {};
  1562. topk_moe_mode fused_topk_moe_mode {};
  1563. bool fused_topk_moe_scale {};
  1564. // for GGML_VK_PERF_LOGGER
  1565. std::unique_ptr<vk_perf_logger> perf_logger;
  1566. vk::QueryPool query_pool;
  1567. std::vector<const char *> query_fusion_names;
  1568. std::vector<int> query_fusion_node_count;
  1569. std::vector<ggml_tensor *> query_nodes;
  1570. std::vector<int> query_node_idx;
  1571. int32_t num_queries {};
  1572. int32_t query_idx {};
  1573. };
  1574. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  1575. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  1576. if (tensor->view_src) {
  1577. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  1578. }
  1579. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  1580. }
  1581. static uint32_t get_misalign_bytes(const ggml_backend_vk_context * ctx, const ggml_tensor * t)
  1582. {
  1583. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  1584. }
  1585. 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) {
  1586. GGML_UNUSED(p);
  1587. GGML_UNUSED(src0);
  1588. GGML_UNUSED(src1);
  1589. GGML_UNUSED(src2);
  1590. GGML_UNUSED(src3);
  1591. GGML_UNUSED(dst);
  1592. static_assert(!std::is_const<T>::value, "unexpected type");
  1593. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  1594. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  1595. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  1596. GGML_ASSERT(!src3 || get_misalign_bytes(ctx, src3) == 0);
  1597. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  1598. }
  1599. 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) {
  1600. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1601. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1602. p.b_offset = b_offset;
  1603. p.d_offset = d_offset;
  1604. GGML_UNUSED(src0);
  1605. GGML_UNUSED(src2);
  1606. GGML_UNUSED(src3);
  1607. }
  1608. 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) {
  1609. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1610. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1611. p.b_offset = b_offset;
  1612. p.d_offset = d_offset;
  1613. GGML_UNUSED(src0);
  1614. GGML_UNUSED(src2);
  1615. GGML_UNUSED(src3);
  1616. }
  1617. struct ggml_backend_vk_buffer_context {
  1618. vk_device_ref device;
  1619. vk_buffer dev_buffer;
  1620. std::string name;
  1621. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  1622. device(device),
  1623. dev_buffer(dev_buffer),
  1624. name(name) {
  1625. }
  1626. ~ggml_backend_vk_buffer_context() {
  1627. ggml_vk_destroy_buffer(dev_buffer);
  1628. }
  1629. };
  1630. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  1631. if (!vk_memory_logger_enabled) {
  1632. return;
  1633. }
  1634. std::lock_guard<std::mutex> guard(log_mutex);
  1635. vk_buffer buf = buf_ref.lock();
  1636. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1637. const std::string type = device ? "device" : "host";
  1638. allocations[buf->buffer] = size;
  1639. total_device += device ? size : 0;
  1640. total_host += device ? 0 : size;
  1641. 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));
  1642. }
  1643. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  1644. if (buf_ref.expired() || buf_ref.lock()->size == 0 || !vk_memory_logger_enabled) {
  1645. return;
  1646. }
  1647. std::lock_guard<std::mutex> guard(log_mutex);
  1648. vk_buffer buf = buf_ref.lock();
  1649. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1650. std::string type = device ? "device" : "host";
  1651. auto it = allocations.find(buf->buffer);
  1652. total_device -= device ? it->second : 0;
  1653. total_host -= device ? 0 : it->second;
  1654. if (it != allocations.end()) {
  1655. 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));
  1656. allocations.erase(it);
  1657. } else {
  1658. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  1659. }
  1660. }
  1661. struct vk_instance_t {
  1662. vk::Instance instance;
  1663. bool debug_utils_support = false; // VK_EXT_debug_utils enabled
  1664. PFN_vkSetDebugUtilsObjectNameEXT pfn_vkSetDebugUtilsObjectNameEXT = {};
  1665. PFN_vkQueueBeginDebugUtilsLabelEXT pfn_vkQueueBeginDebugUtilsLabelEXT = {};
  1666. PFN_vkQueueEndDebugUtilsLabelEXT pfn_vkQueueEndDebugUtilsLabelEXT = {};
  1667. PFN_vkCmdBeginDebugUtilsLabelEXT pfn_vkCmdBeginDebugUtilsLabelEXT = {};
  1668. PFN_vkCmdEndDebugUtilsLabelEXT pfn_vkCmdEndDebugUtilsLabelEXT = {};
  1669. PFN_vkCmdInsertDebugUtilsLabelEXT pfn_vkCmdInsertDebugUtilsLabelEXT = {};
  1670. std::vector<size_t> device_indices;
  1671. std::vector<bool> device_supports_membudget;
  1672. vk_device devices[GGML_VK_MAX_DEVICES];
  1673. };
  1674. static bool vk_instance_initialized = false;
  1675. static vk_instance_t vk_instance;
  1676. #ifdef GGML_VULKAN_CHECK_RESULTS
  1677. static size_t vk_skip_checks;
  1678. static size_t vk_output_tensor;
  1679. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  1680. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1681. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1682. #endif
  1683. 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);
  1684. static void ggml_backend_vk_free(ggml_backend_t backend);
  1685. static VkDeviceSize ggml_vk_get_max_buffer_range(const ggml_backend_vk_context * ctx, const vk_buffer &buf, const VkDeviceSize offset) {
  1686. const VkDeviceSize range = std::min(VkDeviceSize{buf->size - offset},
  1687. VkDeviceSize{ctx->device->properties.limits.maxStorageBufferRange});
  1688. return range;
  1689. }
  1690. // Wait for ctx->fence to be signaled.
  1691. static void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) {
  1692. // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep
  1693. // during this wait.
  1694. if (ctx->almost_ready_fence_pending) {
  1695. VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence");
  1696. ctx->device->device.resetFences({ ctx->almost_ready_fence });
  1697. ctx->almost_ready_fence_pending = false;
  1698. }
  1699. // Spin (w/pause) waiting for the graph to finish executing.
  1700. vk::Result result;
  1701. while ((result = ctx->device->device.getFenceStatus(ctx->fence)) != vk::Result::eSuccess) {
  1702. if (result != vk::Result::eNotReady) {
  1703. fprintf(stderr, "ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__);
  1704. exit(1);
  1705. }
  1706. for (uint32_t i = 0; i < 100; ++i) {
  1707. YIELD();
  1708. YIELD();
  1709. YIELD();
  1710. YIELD();
  1711. YIELD();
  1712. YIELD();
  1713. YIELD();
  1714. YIELD();
  1715. YIELD();
  1716. YIELD();
  1717. }
  1718. }
  1719. ctx->device->device.resetFences({ ctx->fence });
  1720. }
  1721. // variables to track number of compiles in progress
  1722. static uint32_t compile_count = 0;
  1723. static std::mutex compile_count_mutex;
  1724. static std::condition_variable compile_count_cond;
  1725. 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,
  1726. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  1727. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  1728. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  1729. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  1730. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  1731. GGML_ASSERT(parameter_count > 0);
  1732. GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT);
  1733. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  1734. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  1735. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  1736. vk::PushConstantRange pcr(
  1737. vk::ShaderStageFlagBits::eCompute,
  1738. 0,
  1739. pipeline->push_constant_size
  1740. );
  1741. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr);
  1742. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  1743. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  1744. for (size_t i = 0; i < specialization_constants.size(); i++) {
  1745. specialization_entries[i].constantID = i;
  1746. specialization_entries[i].offset = i * sizeof(uint32_t);
  1747. specialization_entries[i].size = sizeof(uint32_t);
  1748. }
  1749. vk::SpecializationInfo specialization_info(
  1750. specialization_entries.size(),
  1751. specialization_entries.data(),
  1752. specialization_constants.size() * sizeof(uint32_t),
  1753. specialization_constants.data()
  1754. );
  1755. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  1756. if (device->subgroup_require_full_support && require_full_subgroups) {
  1757. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  1758. }
  1759. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  1760. pipeline_shader_stage_create_flags,
  1761. vk::ShaderStageFlagBits::eCompute,
  1762. pipeline->shader_module,
  1763. entrypoint.c_str(),
  1764. &specialization_info);
  1765. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  1766. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  1767. if (device->subgroup_size_control && required_subgroup_size > 0) {
  1768. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  1769. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  1770. }
  1771. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  1772. device->pipeline_executable_properties_support ?
  1773. vk::PipelineCreateFlagBits::eCaptureStatisticsKHR :
  1774. vk::PipelineCreateFlags{},
  1775. pipeline_shader_create_info,
  1776. pipeline->layout);
  1777. vk::PipelineRobustnessCreateInfoEXT rci;
  1778. if (device->pipeline_robustness && disable_robustness) {
  1779. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1780. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1781. compute_pipeline_create_info.setPNext(&rci);
  1782. }
  1783. #if defined(VK_EXT_shader_64bit_indexing)
  1784. vk::PipelineCreateFlags2CreateInfo pipelineFlags2CreateInfo;
  1785. if (pipeline->is_64b_indexing)
  1786. {
  1787. pipelineFlags2CreateInfo.flags = vk::PipelineCreateFlagBits2::e64BitIndexingEXT;
  1788. if (device->pipeline_executable_properties_support) {
  1789. pipelineFlags2CreateInfo.flags |= vk::PipelineCreateFlagBits2::eCaptureStatisticsKHR;
  1790. }
  1791. pipelineFlags2CreateInfo.setPNext(compute_pipeline_create_info.pNext);
  1792. compute_pipeline_create_info.setPNext(&pipelineFlags2CreateInfo);
  1793. }
  1794. #endif
  1795. try {
  1796. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  1797. } catch (const vk::SystemError& e) {
  1798. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  1799. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1800. throw e;
  1801. }
  1802. pipeline->compiled = true;
  1803. if (vk_instance.debug_utils_support) {
  1804. vk::DebugUtilsObjectNameInfoEXT duoni;
  1805. duoni.objectType = vk::ObjectType::ePipeline;
  1806. duoni.pObjectName = pipeline->name.c_str();
  1807. duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast<VkPipeline>(pipeline->pipeline));
  1808. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast<VkDebugUtilsObjectNameInfoEXT &>(duoni));
  1809. }
  1810. if (device->pipeline_executable_properties_support) {
  1811. vk::PipelineExecutableInfoKHR executableInfo;
  1812. executableInfo.pipeline = pipeline->pipeline;
  1813. auto statistics = device->device.getPipelineExecutableStatisticsKHR(executableInfo);
  1814. for (auto & s : statistics) {
  1815. // "Register Count" is reported by NVIDIA drivers.
  1816. if (strcmp(s.name, "Register Count") == 0) {
  1817. VK_LOG_DEBUG(pipeline->name << " " << s.name << ": " << s.value.u64 << " registers");
  1818. pipeline->register_count = (uint32_t)s.value.u64;
  1819. }
  1820. }
  1821. }
  1822. device->all_pipelines.push_back(pipeline);
  1823. {
  1824. std::lock_guard<std::mutex> guard(compile_count_mutex);
  1825. assert(compile_count > 0);
  1826. compile_count--;
  1827. }
  1828. compile_count_cond.notify_all();
  1829. }
  1830. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  1831. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  1832. device.destroyPipelineLayout(pipeline->layout);
  1833. device.destroyShaderModule(pipeline->shader_module);
  1834. device.destroyPipeline(pipeline->pipeline);
  1835. }
  1836. static void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) {
  1837. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  1838. ctx->pipeline_descriptor_set_requirements += n;
  1839. if (!pipeline->compiled) {
  1840. pipeline->needed = true;
  1841. ggml_vk_load_shaders(ctx->device);
  1842. }
  1843. ggml_pipeline_allocate_descriptor_sets(ctx);
  1844. }
  1845. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
  1846. if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) {
  1847. // Enough descriptors are available
  1848. return;
  1849. }
  1850. vk_device& device = ctx->device;
  1851. // Grow by 50% to avoid frequent allocations
  1852. uint32_t needed = std::max(3 * ctx->descriptor_sets.size() / 2, size_t{ctx->pipeline_descriptor_set_requirements});
  1853. uint32_t to_alloc = needed - ctx->descriptor_sets.size();
  1854. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1855. uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1856. while (to_alloc > 0) {
  1857. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  1858. to_alloc -= alloc_count;
  1859. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1860. if (pool_idx >= ctx->descriptor_pools.size()) {
  1861. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  1862. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  1863. ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  1864. }
  1865. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  1866. for (uint32_t i = 0; i < alloc_count; i++) {
  1867. layouts[i] = device->dsl;
  1868. }
  1869. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
  1870. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  1871. ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
  1872. pool_idx++;
  1873. }
  1874. }
  1875. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) {
  1876. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  1877. if (p.cmd_buffers.size() > p.cmd_buffer_idx) {
  1878. // Reuse command buffer
  1879. return p.cmd_buffers[p.cmd_buffer_idx++];
  1880. }
  1881. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  1882. p.pool,
  1883. vk::CommandBufferLevel::ePrimary,
  1884. 1);
  1885. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  1886. auto buf = cmd_buffers.front();
  1887. p.cmd_buffers.push_back(buf);
  1888. p.cmd_buffer_idx++;
  1889. return buf;
  1890. }
  1891. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  1892. if (ctx->seqs.empty()) {
  1893. if (fence) {
  1894. std::lock_guard<std::mutex> guard(queue_mutex);
  1895. ctx->p->q->queue.submit({}, fence);
  1896. }
  1897. return;
  1898. }
  1899. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  1900. std::vector<std::vector<uint64_t>> tl_wait_vals;
  1901. std::vector<std::vector<uint64_t>> tl_signal_vals;
  1902. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  1903. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  1904. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  1905. std::vector<vk::SubmitInfo> submit_infos;
  1906. int idx = -1;
  1907. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  1908. size_t reserve = 0;
  1909. for (const auto& sequence : ctx->seqs) {
  1910. reserve += sequence.size();
  1911. }
  1912. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  1913. tl_wait_semaphores.reserve(reserve);
  1914. tl_wait_vals.reserve(reserve);
  1915. tl_signal_semaphores.reserve(reserve);
  1916. tl_signal_vals.reserve(reserve);
  1917. tl_submit_infos.reserve(reserve);
  1918. submit_infos.reserve(reserve);
  1919. stage_flags.reserve(reserve);
  1920. for (const auto& sequence : ctx->seqs) {
  1921. for (const auto& submission : sequence) {
  1922. stage_flags.push_back({});
  1923. idx++;
  1924. tl_wait_vals.push_back({});
  1925. tl_wait_semaphores.push_back({});
  1926. tl_signal_vals.push_back({});
  1927. tl_signal_semaphores.push_back({});
  1928. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  1929. stage_flags[idx].push_back(ctx->p->q->stage_flags);
  1930. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  1931. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  1932. }
  1933. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  1934. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  1935. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  1936. }
  1937. tl_submit_infos.push_back({
  1938. (uint32_t) submission.wait_semaphores.size(),
  1939. tl_wait_vals[idx].data(),
  1940. (uint32_t) submission.signal_semaphores.size(),
  1941. tl_signal_vals[idx].data(),
  1942. });
  1943. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  1944. tl_submit_infos[idx].pNext = nullptr;
  1945. vk::SubmitInfo si{
  1946. (uint32_t) submission.wait_semaphores.size(),
  1947. tl_wait_semaphores[idx].data(),
  1948. stage_flags[idx].data(),
  1949. 1,
  1950. &submission.buffer,
  1951. (uint32_t) submission.signal_semaphores.size(),
  1952. tl_signal_semaphores[idx].data(),
  1953. };
  1954. si.setPNext(&tl_submit_infos[idx]);
  1955. submit_infos.push_back(si);
  1956. }
  1957. }
  1958. std::lock_guard<std::mutex> guard(queue_mutex);
  1959. ctx->p->q->queue.submit(submit_infos, fence);
  1960. ctx->seqs.clear();
  1961. }
  1962. 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) {
  1963. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  1964. const uint32_t qfsize = queue_family_props.size();
  1965. // Try with avoid preferences first
  1966. for (uint32_t i = 0; i < qfsize; i++) {
  1967. 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)) {
  1968. return i;
  1969. }
  1970. }
  1971. // Fall back to only required
  1972. for (size_t i = 0; i < qfsize; i++) {
  1973. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  1974. return i;
  1975. }
  1976. }
  1977. // Fall back to reusing compute queue
  1978. for (size_t i = 0; i < qfsize; i++) {
  1979. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  1980. return i;
  1981. }
  1982. }
  1983. // Fall back to ignoring min_num_queries
  1984. for (size_t i = 0; i < qfsize; i++) {
  1985. if (queue_family_props[i].queueFlags & required) {
  1986. return i;
  1987. }
  1988. }
  1989. // 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.
  1990. // 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.
  1991. if (compute_index >= 0) {
  1992. return compute_index;
  1993. }
  1994. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  1995. for(auto &q_family : queue_family_props) {
  1996. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  1997. }
  1998. abort();
  1999. }
  2000. 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) {
  2001. VK_LOG_DEBUG("ggml_vk_create_queue()");
  2002. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  2003. q.queue_family_index = queue_family_index;
  2004. q.transfer_only = transfer_only;
  2005. q.cmd_pool.init(device, &q);
  2006. q.queue = device->device.getQueue(queue_family_index, queue_index);
  2007. q.stage_flags = stage_flags;
  2008. }
  2009. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) {
  2010. vk_context result = std::make_shared<vk_context_struct>();
  2011. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  2012. ctx->gc.contexts.emplace_back(result);
  2013. result->p = &p;
  2014. return result;
  2015. }
  2016. static vk_context ggml_vk_create_temporary_context(vk_command_pool& p) {
  2017. vk_context result = std::make_shared<vk_context_struct>();
  2018. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  2019. result->p = &p;
  2020. return result;
  2021. }
  2022. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  2023. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  2024. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  2025. vk::SemaphoreCreateInfo ci{};
  2026. ci.setPNext(&tci);
  2027. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  2028. ctx->gc.semaphores.push_back({ semaphore, 0 });
  2029. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  2030. }
  2031. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  2032. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  2033. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  2034. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  2035. vk::SemaphoreCreateInfo ci{};
  2036. ci.setPNext(&tci);
  2037. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  2038. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  2039. }
  2040. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  2041. }
  2042. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  2043. if (ctx->event_idx >= ctx->gc.events.size()) {
  2044. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  2045. }
  2046. return ctx->gc.events[ctx->event_idx++];
  2047. }
  2048. static void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) {
  2049. VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()");
  2050. // Requires command buffers to be done
  2051. device->device.resetCommandPool(p.pool);
  2052. p.cmd_buffer_idx = 0;
  2053. }
  2054. static void ggml_vk_queue_command_pools_cleanup(vk_device& device) {
  2055. VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()");
  2056. // Arbitrary frequency to cleanup/reuse command buffers
  2057. static constexpr uint32_t cleanup_frequency = 10;
  2058. if (device->compute_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  2059. ggml_vk_command_pool_cleanup(device, device->compute_queue.cmd_pool);
  2060. }
  2061. if (device->transfer_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  2062. ggml_vk_command_pool_cleanup(device, device->transfer_queue.cmd_pool);
  2063. }
  2064. }
  2065. static std::vector<uint32_t> ggml_vk_find_memory_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  2066. std::vector<uint32_t> indices;
  2067. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  2068. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  2069. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  2070. (flags & memory_type.propertyFlags) == flags &&
  2071. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  2072. indices.push_back(i);
  2073. }
  2074. }
  2075. return indices;
  2076. }
  2077. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, const std::initializer_list<vk::MemoryPropertyFlags> & req_flags_list,
  2078. void *import_ptr = nullptr) {
  2079. 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]) << ")");
  2080. if (size > device->max_buffer_size) {
  2081. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device buffer size limit");
  2082. }
  2083. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  2084. if (size == 0) {
  2085. buf->size = 0;
  2086. return buf;
  2087. }
  2088. vk::BufferUsageFlags usage_flags = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst;
  2089. vk::MemoryAllocateFlags mem_flags {};
  2090. if (device->buffer_device_address) {
  2091. usage_flags |= vk::BufferUsageFlagBits::eShaderDeviceAddress;
  2092. mem_flags |= vk::MemoryAllocateFlagBits::eDeviceAddress;
  2093. }
  2094. vk::BufferCreateInfo buffer_create_info{
  2095. vk::BufferCreateFlags(),
  2096. size,
  2097. usage_flags,
  2098. vk::SharingMode::eExclusive,
  2099. 0,
  2100. nullptr,
  2101. };
  2102. vk::ExternalMemoryBufferCreateInfo external_memory_bci;
  2103. if (import_ptr) {
  2104. external_memory_bci.handleTypes = vk::ExternalMemoryHandleTypeFlagBits::eHostAllocationEXT;
  2105. buffer_create_info.setPNext(&external_memory_bci);
  2106. }
  2107. buf->buffer = device->device.createBuffer(buffer_create_info);
  2108. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  2109. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  2110. const vk::MemoryPriorityAllocateInfoEXT mem_priority_info { 1.0f };
  2111. vk::MemoryAllocateFlagsInfo mem_flags_info { mem_flags };
  2112. if (device->memory_priority) {
  2113. mem_flags_info.setPNext(&mem_priority_info);
  2114. }
  2115. if (import_ptr) {
  2116. vk::MemoryHostPointerPropertiesEXT host_pointer_props;
  2117. try {
  2118. host_pointer_props = device->device.getMemoryHostPointerPropertiesEXT(vk::ExternalMemoryHandleTypeFlagBits::eHostAllocationEXT, import_ptr);
  2119. } catch (vk::SystemError& e) {
  2120. GGML_LOG_WARN("ggml_vulkan: Failed getMemoryHostPointerPropertiesEXT (%s)\n", e.what());
  2121. device->device.destroyBuffer(buf->buffer);
  2122. return {};
  2123. }
  2124. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  2125. uint32_t memory_type_idx;
  2126. vk::MemoryPropertyFlags property_flags = *req_flags_list.begin();
  2127. for (memory_type_idx = 0; memory_type_idx < 32; ++memory_type_idx) {
  2128. if (!(host_pointer_props.memoryTypeBits & (1u << memory_type_idx))) {
  2129. continue;
  2130. }
  2131. if (!(mem_req.memoryTypeBits & (1u << memory_type_idx))) {
  2132. continue;
  2133. }
  2134. vk::MemoryType memory_type = mem_props.memoryTypes[memory_type_idx];
  2135. // check for visible+coherent+cached. Other flags (e.g. devicelocal) are allowed
  2136. if ((memory_type.propertyFlags & property_flags) == property_flags) {
  2137. property_flags = memory_type.propertyFlags;
  2138. break;
  2139. }
  2140. }
  2141. if (memory_type_idx == 32) {
  2142. GGML_LOG_WARN("ggml_vulkan: Memory type for host allocation not found\n");
  2143. device->device.destroyBuffer(buf->buffer);
  2144. return {};
  2145. }
  2146. buf->memory_property_flags = mem_props.memoryTypes[memory_type_idx].propertyFlags;
  2147. try {
  2148. vk::ImportMemoryHostPointerInfoEXT import_info;
  2149. import_info.handleType = vk::ExternalMemoryHandleTypeFlagBits::eHostAllocationEXT;
  2150. import_info.pHostPointer = import_ptr;
  2151. import_info.setPNext(&mem_flags_info);
  2152. buf->device_memory = device->device.allocateMemory({ size, memory_type_idx, &import_info });
  2153. } catch (const vk::SystemError& e) {
  2154. }
  2155. } else {
  2156. for (auto it = req_flags_list.begin(); it != req_flags_list.end(); it++) {
  2157. const auto & req_flags = *it;
  2158. const std::vector<uint32_t> memory_type_indices = ggml_vk_find_memory_properties(&mem_props, &mem_req, req_flags);
  2159. if (memory_type_indices.empty()) {
  2160. continue;
  2161. }
  2162. buf->memory_property_flags = req_flags;
  2163. bool done = false;
  2164. for (auto mtype_it = memory_type_indices.begin(); mtype_it != memory_type_indices.end(); mtype_it++) {
  2165. try {
  2166. buf->device_memory = device->device.allocateMemory({ mem_req.size, *mtype_it, &mem_flags_info });
  2167. done = true;
  2168. break;
  2169. } catch (const vk::SystemError& e) {
  2170. // loop and retry
  2171. // during last attempt throw the exception
  2172. if (it + 1 == req_flags_list.end() && mtype_it + 1 == memory_type_indices.end()) {
  2173. device->device.destroyBuffer(buf->buffer);
  2174. throw e;
  2175. }
  2176. }
  2177. }
  2178. if (done) {
  2179. break;
  2180. }
  2181. }
  2182. }
  2183. if (!buf->device_memory) {
  2184. device->device.destroyBuffer(buf->buffer);
  2185. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  2186. }
  2187. buf->ptr = nullptr;
  2188. if (import_ptr) {
  2189. buf->ptr = import_ptr;
  2190. } else {
  2191. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2192. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  2193. }
  2194. }
  2195. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  2196. buf->device = device;
  2197. buf->size = size;
  2198. if (device->buffer_device_address) {
  2199. const vk::BufferDeviceAddressInfo addressInfo(buf->buffer);
  2200. buf->bda_addr = device->device.getBufferAddress(addressInfo);
  2201. }
  2202. device->memory_logger->log_allocation(buf, size);
  2203. return buf;
  2204. }
  2205. 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)) {
  2206. try {
  2207. return ggml_vk_create_buffer(device, size, {req_flags, fallback_flags});
  2208. } catch (const vk::SystemError& e) {
  2209. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  2210. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  2211. throw e;
  2212. }
  2213. }
  2214. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  2215. vk_buffer buf;
  2216. try {
  2217. if (device->prefer_host_memory) {
  2218. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2219. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2220. } else if (device->uma) {
  2221. // Fall back to host memory type
  2222. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2223. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2224. } else if (device->disable_host_visible_vidmem) {
  2225. if (device->allow_sysmem_fallback) {
  2226. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2227. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2228. } else {
  2229. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  2230. }
  2231. } else {
  2232. // use rebar if available, otherwise fallback to device only visible memory
  2233. if (device->allow_sysmem_fallback) {
  2234. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2235. vk::MemoryPropertyFlagBits::eDeviceLocal,
  2236. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2237. } else {
  2238. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2239. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2240. }
  2241. }
  2242. } catch (const vk::SystemError& e) {
  2243. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  2244. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  2245. throw e;
  2246. }
  2247. return buf;
  2248. }
  2249. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  2250. if (buf == nullptr) {
  2251. return;
  2252. }
  2253. if (buf->device != nullptr) {
  2254. buf->device->memory_logger->log_deallocation(buf);
  2255. }
  2256. buf.reset();
  2257. }
  2258. static vk_subbuffer ggml_vk_subbuffer(const ggml_backend_vk_context* ctx, const vk_buffer& buf, size_t offset = 0) {
  2259. return { buf, offset, ggml_vk_get_max_buffer_range(ctx, buf, offset) };
  2260. }
  2261. static void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) {
  2262. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  2263. const bool transfer_queue = subctx->p->q->transfer_only;
  2264. if (ctx) {
  2265. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  2266. }
  2267. subctx->s->buffer.pipelineBarrier(
  2268. subctx->p->q->stage_flags,
  2269. subctx->p->q->stage_flags,
  2270. {},
  2271. { {
  2272. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  2273. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  2274. } },
  2275. {},
  2276. {}
  2277. );
  2278. }
  2279. static void ggml_vk_set_event(vk_context& ctx, vk::Event& event) {
  2280. VK_LOG_DEBUG("ggml_vk_set_event()");
  2281. ctx->s->buffer.setEvent(
  2282. event,
  2283. ctx->p->q->stage_flags
  2284. );
  2285. }
  2286. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  2287. VK_LOG_DEBUG("ggml_vk_wait_events()");
  2288. if (events.empty()) {
  2289. return;
  2290. }
  2291. ctx->s->buffer.waitEvents(
  2292. events,
  2293. ctx->p->q->stage_flags,
  2294. ctx->p->q->stage_flags,
  2295. {},
  2296. {},
  2297. {}
  2298. );
  2299. }
  2300. // number of rows/cols for flash attention shader
  2301. static constexpr uint32_t flash_attention_num_small_rows = 32;
  2302. static constexpr uint32_t scalar_flash_attention_num_small_rows = 1;
  2303. static uint32_t get_fa_scalar_num_large_rows(uint32_t hsk, uint32_t hsv, bool small_cache) {
  2304. if (hsv >= 192) {
  2305. return 2;
  2306. } else if ((hsv | hsk) & 8 || small_cache) {
  2307. return 4;
  2308. } else {
  2309. return 8;
  2310. }
  2311. }
  2312. // The FA coopmat1 shader assumes 16x16x16 matrix multiply support.
  2313. // 128 threads split into four subgroups, each subgroup does 1/4
  2314. // of the Bc dimension.
  2315. static constexpr uint32_t coopmat1_flash_attention_num_large_rows = 16;
  2316. static constexpr uint32_t scalar_flash_attention_Bc = 64;
  2317. static constexpr uint32_t scalar_flash_attention_workgroup_size = 128;
  2318. static uint32_t get_fa_num_small_rows(FaCodePath path) {
  2319. if (path == FA_COOPMAT2) {
  2320. return flash_attention_num_small_rows;
  2321. } else {
  2322. return scalar_flash_attention_num_small_rows;
  2323. }
  2324. }
  2325. 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) {
  2326. GGML_UNUSED(clamp);
  2327. if (path == FA_SCALAR) {
  2328. if (small_rows) {
  2329. return {scalar_flash_attention_num_small_rows, 64};
  2330. } else {
  2331. if ((hsv | hsk) & 8) {
  2332. // HSV/HSK not being a multiple of 16 makes D_split smaller, which makes cols_per_iter
  2333. // larger, and Bc needs to be >= cols_per_thread. 64 is large enough, 32 is not.
  2334. return {get_fa_scalar_num_large_rows(hsk, hsv, small_cache), 64};
  2335. } else {
  2336. return {get_fa_scalar_num_large_rows(hsk, hsv, small_cache), 32};
  2337. }
  2338. }
  2339. }
  2340. if (path == FA_COOPMAT1) {
  2341. if (small_rows) {
  2342. return {scalar_flash_attention_num_small_rows, scalar_flash_attention_Bc};
  2343. } else {
  2344. return {coopmat1_flash_attention_num_large_rows, scalar_flash_attention_Bc};
  2345. }
  2346. }
  2347. // small rows, large cols
  2348. if (small_rows) {
  2349. return {get_fa_num_small_rows(FA_COOPMAT2), 32};
  2350. }
  2351. // small cols to reduce register count
  2352. if (ggml_is_quantized(type) || hsk >= 256 || hsv >= 256) {
  2353. if (hsk >= 512 || hsv >= 512) {
  2354. return {32, 32};
  2355. } else {
  2356. return {64, 32};
  2357. }
  2358. }
  2359. return {64, 64};
  2360. }
  2361. static uint32_t fa_align(FaCodePath path, uint32_t hsk, uint32_t hsv, ggml_type type, bool small_rows, bool small_cache) {
  2362. return fa_rows_cols(path, hsk, hsv, 0, type, small_rows, small_cache)[1];
  2363. }
  2364. 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) {
  2365. uint32_t lut_size = 0;
  2366. switch (src0_type) {
  2367. case GGML_TYPE_IQ1_S:
  2368. case GGML_TYPE_IQ1_M:
  2369. lut_size = 2*2048 + 4*2048;
  2370. break;
  2371. case GGML_TYPE_IQ2_XXS:
  2372. lut_size = 8*256;
  2373. break;
  2374. case GGML_TYPE_IQ2_XS:
  2375. lut_size = 8*512;
  2376. break;
  2377. case GGML_TYPE_IQ2_S:
  2378. lut_size = 8*1024;
  2379. break;
  2380. case GGML_TYPE_IQ3_XXS:
  2381. lut_size = 4*256;
  2382. break;
  2383. case GGML_TYPE_IQ3_S:
  2384. lut_size = 4*512;
  2385. break;
  2386. case GGML_TYPE_IQ4_NL:
  2387. case GGML_TYPE_IQ4_XS:
  2388. case GGML_TYPE_MXFP4:
  2389. lut_size = 4*16;
  2390. break;
  2391. default:
  2392. break;
  2393. }
  2394. // Needs to be kept up to date on shader changes
  2395. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  2396. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  2397. const uint32_t warps = warptile[0] / warptile[10];
  2398. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  2399. const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0;
  2400. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  2401. const uint32_t ballots_sh = mul_mat_id ? (warps * 4 * sizeof(uint32_t)) : 0;
  2402. const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size + ballots_sh;
  2403. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  2404. VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), "
  2405. "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported);
  2406. return supported;
  2407. }
  2408. struct GpuPipelineConfig {
  2409. // GPU architecture identifier.
  2410. // Example: vk_device_architecture::AMD_GCN
  2411. vk_device_architecture arch;
  2412. // Mapping of pipeline names to their specific subgroup sizes.
  2413. // Example: {"soft_max_f32", 64}
  2414. std::unordered_map<std::string, uint32_t> pipelines;
  2415. // Default subgroup size for this GPU.
  2416. // Defaults to 0 if not explicitly provided.
  2417. uint32_t default_subgroup_size = 0;
  2418. };
  2419. // Pipeline configuration for RDNA1 GPUs.
  2420. static const std::unordered_map<std::string, uint32_t> rdna1_pipelines = {
  2421. {"soft_max", 64}, {"im2col", 64},
  2422. {"argmax", 64}, {"mul_mat_vec", 64},
  2423. {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32}
  2424. };
  2425. // Pipeline configuration for RDNA2 GPUs.
  2426. static const std::unordered_map<std::string, uint32_t> rdna2_pipelines = {
  2427. {"soft_max", 64}, {"im2col", 64},
  2428. };
  2429. static constexpr uint32_t RDNA_DEFAULT_SUBGROUP_SIZE = 32;
  2430. // Define configurations for different GPUs.
  2431. static std::vector<GpuPipelineConfig> gpu_pipeline_configs = {
  2432. {
  2433. vk_device_architecture::AMD_RDNA1,
  2434. {
  2435. rdna1_pipelines,
  2436. },
  2437. RDNA_DEFAULT_SUBGROUP_SIZE
  2438. },
  2439. {
  2440. vk_device_architecture::AMD_RDNA2,
  2441. {
  2442. rdna2_pipelines,
  2443. },
  2444. RDNA_DEFAULT_SUBGROUP_SIZE
  2445. },
  2446. };
  2447. static uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) {
  2448. for (const auto &config : gpu_pipeline_configs) {
  2449. if (config.arch == arch) {
  2450. auto pipIt = config.pipelines.find(pipeline_name);
  2451. if (pipIt != config.pipelines.end()) {
  2452. return pipIt->second;
  2453. }
  2454. std::vector<std::pair<std::string, uint32_t>> sorted_pipelines(config.pipelines.begin(), config.pipelines.end());
  2455. std::sort(sorted_pipelines.begin(), sorted_pipelines.end(),
  2456. [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
  2457. for (const auto &entry : sorted_pipelines) {
  2458. if (pipeline_name.find(entry.first) != std::string::npos) {
  2459. return entry.second;
  2460. }
  2461. }
  2462. return config.default_subgroup_size;
  2463. }
  2464. }
  2465. return 0; // If no matching configuration is found
  2466. }
  2467. static void ggml_vk_load_shaders(vk_device& device) {
  2468. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  2469. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  2470. // some shaders have a minimum subgroup size
  2471. const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u);
  2472. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  2473. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  2474. 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;
  2475. const uint32_t mul_mat_subgroup_size_8 = std::max(mul_mat_subgroup_size, 8u);
  2476. const uint32_t mul_mat_subgroup_size_16 = std::max(mul_mat_subgroup_size, 16u);
  2477. const uint32_t mul_mat_subgroup_size_32 = std::max(mul_mat_subgroup_size, 32u);
  2478. const bool subgroup_min_size_16 = (!device->subgroup_size_control && device->subgroup_size >= 16) ||
  2479. (device->subgroup_size_control && device->subgroup_max_size >= 16);
  2480. // mulmat
  2481. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  2482. l_warptile_id, m_warptile_id, s_warptile_id,
  2483. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  2484. l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int,
  2485. l_warptile_mmq_int_k, m_warptile_mmq_int_k, s_warptile_mmq_int_k,
  2486. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  2487. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid,
  2488. l_warptile_mmqid_int, m_warptile_mmqid_int, s_warptile_mmqid_int,
  2489. l_warptile_mmqid_int_k, m_warptile_mmqid_int_k, s_warptile_mmqid_int_k;
  2490. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  2491. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  2492. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  2493. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  2494. uint32_t l_align, m_align, s_align;
  2495. if (device->coopmat2) {
  2496. // spec constants and tile sizes for non-quant matmul/matmul_id
  2497. l_warptile = { 256, 128, 256, 64, 1 };
  2498. m_warptile = { 256, 128, 128, 64, 0 };
  2499. s_warptile = { 128, 64, 64, 64, 0 };
  2500. l_wg_denoms = {128, 256, 1 };
  2501. m_wg_denoms = {128, 128, 1 };
  2502. s_wg_denoms = { 64, 64, 1 };
  2503. // spec constants and tile sizes for quant matmul (non-Qi_K)
  2504. l_warptile_mmq = { 256, 128, 256, 64, 1 };
  2505. m_warptile_mmq = { 256, 128, 128, 64, 1 };
  2506. s_warptile_mmq = { 256, 32, 64, 128, 0 };
  2507. l_mmq_wg_denoms = { 128, 256, 1 };
  2508. m_mmq_wg_denoms = { 128, 128, 1 };
  2509. s_mmq_wg_denoms = { 32, 64, 1 };
  2510. // spec constants and tile sizes for quant matmul (Qi_K)
  2511. l_warptile_mmq_k = { 256, 128, 256, 64, 1 };
  2512. m_warptile_mmq_k = { 256, 128, 128, 64, 1 };
  2513. s_warptile_mmq_k = { 256, 32, 64, 128, 0 };
  2514. l_mmq_wg_denoms_k = { 128, 256, 1 };
  2515. m_mmq_wg_denoms_k = { 128, 128, 1 };
  2516. s_mmq_wg_denoms_k = { 32, 64, 1 };
  2517. // spec constants and tile sizes for quant matmul_id
  2518. l_warptile_mmqid = { 256, 128, 128, 32, 1, device->subgroup_size };
  2519. m_warptile_mmqid = { 256, 128, 64, 32, 0, device->subgroup_size };
  2520. s_warptile_mmqid = { 256, 128, 64, 32, 0, device->subgroup_size };
  2521. l_mmqid_wg_denoms = { 128, 128, 1 };
  2522. m_mmqid_wg_denoms = { 128, 64, 1 };
  2523. s_mmqid_wg_denoms = { 128, 64, 1 };
  2524. l_align = 128;
  2525. m_align = 64;
  2526. s_align = 32;
  2527. } else {
  2528. // Matrix cores require different warp group sizes
  2529. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  2530. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  2531. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  2532. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  2533. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  2534. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  2535. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  2536. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  2537. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  2538. const uint32_t s_warptile_wm = device->subgroup_size == 8 ? 8 : 32;
  2539. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2540. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2541. s_warptile = { subgroup_size_32, 32, 32, 16, s_warptile_wm, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2542. l_warptile_mmq = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2543. m_warptile_mmq = { 128, 64, 64, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2544. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2545. // Integer MMQ has a smaller shared memory profile, but heavier register use
  2546. l_warptile_mmq_int = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2547. m_warptile_mmq_int = { 128, 64, 64, 32, subgroup_size_8, 32, 2, 2, 2, 1, subgroup_size_8 };
  2548. s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 2, 2, 1, 1, subgroup_size_8 };
  2549. // K-quants use even more registers, mitigate by setting WMITER to 1
  2550. l_warptile_mmq_int_k = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 1, 4, 4, 1, subgroup_size_8 };
  2551. m_warptile_mmq_int_k = { 128, 64, 64, 32, subgroup_size_8, 32, 1, 2, 2, 1, subgroup_size_8 };
  2552. s_warptile_mmq_int_k = { subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 1, 2, 1, 1, subgroup_size_8 };
  2553. 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 };
  2554. 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 };
  2555. s_warptile_id = { mul_mat_subgroup_size_16, 32, 32, 16, s_warptile_wm, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_16 };
  2556. 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 };
  2557. 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 };
  2558. s_warptile_mmqid = { mul_mat_subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_8 };
  2559. l_warptile_mmqid_int = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, 4, 4, 1, mul_mat_subgroup_size_8 };
  2560. m_warptile_mmqid_int = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, 2, 2, 1, mul_mat_subgroup_size_8 };
  2561. s_warptile_mmqid_int = { mul_mat_subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 2, 2, 1, 1, mul_mat_subgroup_size_8 };
  2562. 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 };
  2563. m_warptile_mmqid_int_k = { 128, 64, 64, 32, mul_mat_subgroup_size_16, 32, 1, 2, 2, 1, mul_mat_subgroup_size_16 };
  2564. s_warptile_mmqid_int_k = { mul_mat_subgroup_size_32, 32, 32, 32, s_warptile_wm, 32, 1, 2, 1, 1, mul_mat_subgroup_size_16 };
  2565. // chip specific tuning
  2566. if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) {
  2567. m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2568. m_warptile_mmqid = m_warptile_mmqid_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2569. } else if (device->vendor_id == VK_VENDOR_ID_AMD && device->coopmat_support && device->driver_id != vk::DriverId::eAmdProprietary) {
  2570. // This is intentionally using tx_m values, slight performance increase
  2571. l_warptile = { 256, 128, 128, 16, subgroup_size_8, 64, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2572. l_warptile_mmq = l_warptile_mmq_int = { 256, 128, 128, 32, subgroup_size_8, 64, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2573. l_warptile_mmq_int_k = { 256, 128, 128, 32, subgroup_size_16, 64, 1, 4, 2, 1, subgroup_size_16 };
  2574. } else if (device->vendor_id == VK_VENDOR_ID_INTEL && device->coopmat_support && device->architecture == INTEL_XE2) {
  2575. // Xe2/Xe3 with coopmat enabled - warptile performance tuning
  2576. l_warptile = { 512, 128, 128, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2577. l_warptile_mmq = { 512, 128, 128, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2578. }
  2579. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  2580. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  2581. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  2582. l_align = 128;
  2583. m_align = 64;
  2584. s_align = 32;
  2585. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  2586. ggml_type t = (ggml_type)i;
  2587. // Disable medium and large matrix multiplication if not enough shared memory is available
  2588. // Check mmq warptiles as the largest configuration
  2589. // Throw an error if not enough for any matrix multiplication is available
  2590. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) {
  2591. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  2592. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  2593. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) {
  2594. device->mul_mat_m[i] = false;
  2595. device->mul_mat_l[i] = false;
  2596. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) {
  2597. device->mul_mat_l[i] = false;
  2598. }
  2599. // Disable mul_mat_id if not enough shared memory is available
  2600. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmqid, true, t)) {
  2601. device->mul_mat_id_s[i] = false;
  2602. device->mul_mat_id_m[i] = false;
  2603. device->mul_mat_id_l[i] = false;
  2604. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmqid, true, t)) {
  2605. device->mul_mat_id_m[i] = false;
  2606. device->mul_mat_id_l[i] = false;
  2607. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmqid, true, t)) {
  2608. device->mul_mat_id_l[i] = false;
  2609. }
  2610. }
  2611. }
  2612. if (!device->pipeline_matmul_f32) {
  2613. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2614. }
  2615. if (!device->pipeline_matmul_f32_f16) {
  2616. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  2617. }
  2618. if (!device->pipeline_matmul_id_f32) {
  2619. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2620. }
  2621. if (!device->pipeline_matmul_bf16) {
  2622. device->pipeline_matmul_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2623. }
  2624. if (!device->pipeline_matmul_id_bf16) {
  2625. device->pipeline_matmul_id_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2626. }
  2627. std::vector<std::future<void>> compiles;
  2628. auto const &ggml_vk_create_pipeline = [&](vk_device& device, vk_pipeline& base_pipeline, const char *name, size_t spv_size, const void* spv_data, const char *entrypoint,
  2629. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2630. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2631. if (!require_full_subgroups && required_subgroup_size == 0) {
  2632. required_subgroup_size = get_subgroup_size(name, device->architecture);
  2633. }
  2634. vk_pipeline *ptr = &base_pipeline;
  2635. int num_pipelines = 1;
  2636. #if defined(VK_EXT_shader_64bit_indexing)
  2637. if (device->shader_64b_indexing) {
  2638. num_pipelines = 2;
  2639. }
  2640. #endif
  2641. for (int i = 0; i < num_pipelines; ++i, ptr = &(*ptr)->next) {
  2642. vk_pipeline &pipeline = *ptr;
  2643. if (!pipeline) {
  2644. pipeline = std::make_shared<vk_pipeline_struct>();
  2645. }
  2646. if (!pipeline->initialized) {
  2647. pipeline->name = name;
  2648. pipeline->parameter_count = parameter_count;
  2649. pipeline->push_constant_size = push_constant_size;
  2650. pipeline->wg_denoms = wg_denoms;
  2651. pipeline->align = align;
  2652. pipeline->initialized = true;
  2653. #if defined(VK_EXT_shader_64bit_indexing)
  2654. pipeline->is_64b_indexing = (i == 1);
  2655. #endif
  2656. }
  2657. if (!pipeline->needed || pipeline->compiled) {
  2658. continue;
  2659. }
  2660. // TODO: We're no longer benefitting from the async compiles (shaders are
  2661. // compiled individually, as needed) and this complexity can be removed.
  2662. {
  2663. // wait until fewer than N compiles are in progress
  2664. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  2665. std::unique_lock<std::mutex> guard(compile_count_mutex);
  2666. while (compile_count >= N) {
  2667. compile_count_cond.wait(guard);
  2668. }
  2669. compile_count++;
  2670. }
  2671. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  2672. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  2673. }
  2674. };
  2675. 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,
  2676. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2677. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2678. return ggml_vk_create_pipeline(device, pipeline, name.c_str(), spv_size, spv_data, entrypoint,
  2679. parameter_count, push_constant_size, wg_denoms, specialization_constants,
  2680. align, disable_robustness, require_full_subgroups, required_subgroup_size);
  2681. };
  2682. 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> {
  2683. return {fa_rows_cols(path, hsk, hsv, clamp, type, small_rows, small_cache)[0], 1, 1};
  2684. };
  2685. 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> {
  2686. // For large number of rows, 128 invocations seems to work best.
  2687. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  2688. // can't use 256 for D==80.
  2689. // For scalar, use 128 (arbitrary)
  2690. // The same D_split value is used for both HSK and HSV, so just base it on the union of the LSBs.
  2691. const uint32_t D = (hsk|hsv);
  2692. uint32_t wg_size = (path == FA_SCALAR || path == FA_COOPMAT1)
  2693. ? scalar_flash_attention_workgroup_size
  2694. : ((small_rows && (D % 32) == 0) ? 256 : 128);
  2695. auto rows_cols = fa_rows_cols(path, hsk, hsv, clamp, type, small_rows, small_cache);
  2696. // D_split can't be larger than a subgroup because we use subgroupShuffle to reduce it.
  2697. // D_split can't be larger than the LSB of D divided by 4 due to vectorization in the shader.
  2698. const uint32_t D_lsb = D ^ (D & (D-1));
  2699. uint32_t D_split = std::min(std::min(device->subgroup_size, 8u), D_lsb / 4);
  2700. return {wg_size, rows_cols[0], rows_cols[1], hsk, hsv, clamp, D_split};
  2701. };
  2702. #define CREATE_FA(TYPE, NAMELC, FAPATH, SUFFIX) \
  2703. for (auto &fa : device->pipeline_flash_attn_f32_f16[TYPE]) { \
  2704. uint32_t HSK = fa.first.HSK; \
  2705. uint32_t HSV = fa.first.HSV; \
  2706. bool small_rows = fa.first.small_rows; \
  2707. bool small_cache = fa.first.small_cache; \
  2708. FaCodePath path = fa.first.path; \
  2709. bool aligned = fa.first.aligned; \
  2710. bool f32acc = fa.first.f32acc; \
  2711. if (path == FAPATH) { \
  2712. if (aligned) { \
  2713. if (f32acc) { \
  2714. 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)); \
  2715. } else { \
  2716. 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)); \
  2717. } \
  2718. } else { \
  2719. if (f32acc) { \
  2720. 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)); \
  2721. } else { \
  2722. 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)); \
  2723. } \
  2724. } \
  2725. } \
  2726. }
  2727. CREATE_FA(GGML_TYPE_F32, f32, FA_SCALAR, )
  2728. CREATE_FA(GGML_TYPE_F16, f16, FA_SCALAR, )
  2729. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_SCALAR, )
  2730. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_SCALAR, )
  2731. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2732. if (device->coopmat1_fa_support) {
  2733. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT1, _cm1)
  2734. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT1, _cm1)
  2735. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT1, _cm1)
  2736. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT1, _cm1)
  2737. }
  2738. #endif
  2739. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2740. if (device->coopmat2) {
  2741. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT2, _cm2)
  2742. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT2, _cm2)
  2743. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT2, _cm2)
  2744. CREATE_FA(GGML_TYPE_Q4_1, q4_1, FA_COOPMAT2, _cm2)
  2745. CREATE_FA(GGML_TYPE_Q5_0, q5_0, FA_COOPMAT2, _cm2)
  2746. CREATE_FA(GGML_TYPE_Q5_1, q5_1, FA_COOPMAT2, _cm2)
  2747. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT2, _cm2)
  2748. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl, FA_COOPMAT2, _cm2)
  2749. }
  2750. #endif
  2751. #undef CREATE_FA
  2752. const int mul_mat_id_param_count = 5;
  2753. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2754. if (device->coopmat2) {
  2755. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2756. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2757. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _cm2_len, NAMELC ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, true); \
  2758. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _cm2_len, NAMELC ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, true); \
  2759. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _cm2_len, NAMELC ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, true); \
  2760. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _cm2_len, NAMELC ## _aligned ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, true); \
  2761. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _cm2_len, NAMELC ## _aligned ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, true); \
  2762. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _cm2_len, NAMELC ## _aligned ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, true); \
  2763. // Create 2 variants, {f16,f32} accumulator
  2764. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2765. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2766. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2767. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2768. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2769. if (device->coopmat_bf16_support) {
  2770. CREATE_MM(pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2771. }
  2772. #endif
  2773. 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)
  2774. 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)
  2775. 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)
  2776. 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)
  2777. 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)
  2778. 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)
  2779. 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)
  2780. 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)
  2781. 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)
  2782. 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)
  2783. 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)
  2784. 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)
  2785. 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)
  2786. 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)
  2787. 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)
  2788. 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)
  2789. 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)
  2790. 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)
  2791. 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)
  2792. 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)
  2793. GGML_ASSERT(device->subgroup_ballot);
  2794. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 5)
  2795. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2796. if (device->coopmat_bf16_support) {
  2797. CREATE_MM(pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 5)
  2798. }
  2799. #endif
  2800. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2801. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2802. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2803. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2804. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2805. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2806. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2807. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2808. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2809. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2810. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2811. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2812. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2813. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2814. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2815. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2816. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2817. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2818. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2819. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 5)
  2820. #undef CREATE_MM
  2821. #undef CREATE_MM2
  2822. } else
  2823. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2824. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2825. if (device->coopmat_support) {
  2826. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2827. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2828. if (device->mul_mat ## ID ## _l[TYPE]) \
  2829. 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); \
  2830. if (device->mul_mat ## ID ## _m[TYPE]) \
  2831. 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); \
  2832. if (device->mul_mat ## ID ## _s[TYPE]) \
  2833. 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); \
  2834. if (device->mul_mat ## ID ## _l[TYPE]) \
  2835. 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); \
  2836. if (device->mul_mat ## ID ## _m[TYPE]) \
  2837. 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); \
  2838. if (device->mul_mat ## ID ## _s[TYPE]) \
  2839. 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); \
  2840. // Create 2 variants, {f16,f32} accumulator
  2841. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2842. if (device->coopmat_acc_f16_support) { \
  2843. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2844. } \
  2845. if (device->coopmat_acc_f32_support) { \
  2846. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2847. } \
  2848. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2849. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2850. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2851. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2852. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2853. if (device->coopmat_bf16_support) {
  2854. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, )
  2855. }
  2856. #endif
  2857. if (device->coopmat_acc_f16_support) {
  2858. 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, );
  2859. 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, );
  2860. 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, );
  2861. 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, );
  2862. 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, );
  2863. 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, );
  2864. 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, );
  2865. 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, );
  2866. 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, );
  2867. 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, );
  2868. 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, );
  2869. 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, );
  2870. 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, );
  2871. 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, );
  2872. 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, );
  2873. 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, );
  2874. 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, );
  2875. 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, );
  2876. 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, );
  2877. 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, );
  2878. } else {
  2879. 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, );
  2880. 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, );
  2881. 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, );
  2882. 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, );
  2883. 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, );
  2884. 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, );
  2885. 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, );
  2886. 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, );
  2887. 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, );
  2888. 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, );
  2889. 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, );
  2890. 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, );
  2891. 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, );
  2892. 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, );
  2893. 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, );
  2894. 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, );
  2895. 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, );
  2896. 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, );
  2897. 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, );
  2898. 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, );
  2899. }
  2900. GGML_ASSERT(device->subgroup_ballot);
  2901. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2902. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2903. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2904. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2905. if (device->coopmat_bf16_support) {
  2906. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2907. }
  2908. #endif
  2909. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2910. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2911. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2912. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2913. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2914. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2915. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2916. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2917. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2918. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2919. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2920. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2921. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2922. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2923. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2924. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2925. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2926. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2927. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2928. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id);
  2929. #undef CREATE_MM2
  2930. #undef CREATE_MM
  2931. } else
  2932. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2933. if (device->fp16) {
  2934. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2935. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2936. if (device->mul_mat ## ID ## _l[TYPE]) \
  2937. 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); \
  2938. if (device->mul_mat ## ID ## _m[TYPE]) \
  2939. 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); \
  2940. if (device->mul_mat ## ID ## _s[TYPE]) \
  2941. 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); \
  2942. if (device->mul_mat ## ID ## _l[TYPE]) \
  2943. 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); \
  2944. if (device->mul_mat ## ID ## _m[TYPE]) \
  2945. 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); \
  2946. if (device->mul_mat ## ID ## _s[TYPE]) \
  2947. 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); \
  2948. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2949. if (device->mul_mat ## ID ## _l[TYPE]) { \
  2950. 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); \
  2951. } \
  2952. if (device->mul_mat ## ID ## _m[TYPE]) { \
  2953. 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); \
  2954. } \
  2955. if (device->mul_mat ## ID ## _s[TYPE]) { \
  2956. 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); \
  2957. } \
  2958. // Create 2 variants, {f16,f32} accumulator
  2959. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2960. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2961. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2962. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2963. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2964. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2965. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2966. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2967. 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);
  2968. 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);
  2969. 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);
  2970. 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);
  2971. 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);
  2972. 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);
  2973. 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);
  2974. 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);
  2975. 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);
  2976. 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);
  2977. 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);
  2978. 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);
  2979. 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);
  2980. 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);
  2981. 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);
  2982. 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);
  2983. 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);
  2984. 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);
  2985. 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);
  2986. 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);
  2987. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2988. if (device->integer_dot_product) {
  2989. 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);
  2990. 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);
  2991. 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);
  2992. 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);
  2993. 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);
  2994. 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);
  2995. 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);
  2996. 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);
  2997. 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);
  2998. 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);
  2999. 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);
  3000. }
  3001. #endif
  3002. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  3003. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3004. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3005. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3006. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3007. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3008. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3009. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3010. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3011. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3012. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3013. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3014. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3015. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3016. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3017. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3018. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3019. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3020. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3021. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3022. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3023. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3024. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3025. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3026. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3027. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3028. if (device->integer_dot_product) {
  3029. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3030. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3031. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3032. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3033. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3034. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3035. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3036. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3037. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3038. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3039. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3040. }
  3041. #endif
  3042. } else {
  3043. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3044. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3045. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3046. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3047. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3048. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3049. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3050. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3051. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3052. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3053. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3054. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3055. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3056. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3057. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3058. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3059. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3060. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3061. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3062. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3063. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3064. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3065. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3066. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3067. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3068. if (device->integer_dot_product) {
  3069. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_0], matmul_id_q4_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3070. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_1], matmul_id_q4_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3071. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_0], matmul_id_q5_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3072. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_1], matmul_id_q5_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3073. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q8_0], matmul_id_q8_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3074. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_MXFP4], matmul_id_mxfp4_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3075. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q2_K], matmul_id_q2_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3076. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q3_K], matmul_id_q3_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3077. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_K], matmul_id_q4_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3078. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_K], matmul_id_q5_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3079. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q6_K], matmul_id_q6_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3080. }
  3081. #endif
  3082. }
  3083. #undef CREATE_MM2
  3084. #undef CREATE_MMQ
  3085. #undef CREATE_MM
  3086. } else {
  3087. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  3088. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  3089. if (device->mul_mat ## ID ## _l[TYPE]) \
  3090. 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); \
  3091. if (device->mul_mat ## ID ## _m[TYPE]) \
  3092. 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); \
  3093. if (device->mul_mat ## ID ## _s[TYPE]) \
  3094. 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); \
  3095. if (device->mul_mat ## ID ## _l[TYPE]) \
  3096. 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); \
  3097. if (device->mul_mat ## ID ## _m[TYPE]) \
  3098. 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); \
  3099. if (device->mul_mat ## ID ## _s[TYPE]) \
  3100. 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); \
  3101. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  3102. if (device->mul_mat ## ID ## _l[TYPE]) \
  3103. 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); \
  3104. if (device->mul_mat ## ID ## _m[TYPE]) \
  3105. 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); \
  3106. if (device->mul_mat ## ID ## _s[TYPE]) \
  3107. 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); \
  3108. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3109. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3110. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3111. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3112. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3113. 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);
  3114. 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);
  3115. 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);
  3116. 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);
  3117. 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);
  3118. 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);
  3119. 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);
  3120. 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);
  3121. 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);
  3122. 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);
  3123. 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);
  3124. 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);
  3125. 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);
  3126. 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);
  3127. 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);
  3128. 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);
  3129. 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);
  3130. 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);
  3131. 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);
  3132. 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);
  3133. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3134. if (device->integer_dot_product) {
  3135. 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, );
  3136. 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, );
  3137. 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, );
  3138. 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, );
  3139. 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, );
  3140. 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, );
  3141. 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, );
  3142. 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, );
  3143. 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, );
  3144. 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, );
  3145. }
  3146. #endif
  3147. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  3148. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3149. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_subgroup_f16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3150. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_subgroup_f16_f32, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3151. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size_16);
  3152. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_subgroup_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3153. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_subgroup_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3154. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_subgroup_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3155. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_subgroup_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3156. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_subgroup_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3157. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_subgroup_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3158. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_subgroup_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3159. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_subgroup_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3160. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_subgroup_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3161. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_subgroup_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3162. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_subgroup_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3163. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_subgroup_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3164. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_subgroup_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3165. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_subgroup_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3166. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_subgroup_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3167. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_subgroup_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3168. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_subgroup_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3169. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_subgroup_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3170. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_subgroup_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3171. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_subgroup_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, mul_mat_subgroup_size);
  3172. } else {
  3173. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3174. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3175. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_f16_f32, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3176. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3177. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3178. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3179. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3180. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3181. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3182. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3183. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3184. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3185. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3186. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3187. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3188. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3189. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3190. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3191. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3192. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3193. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3194. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3195. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3196. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3197. }
  3198. }
  3199. // reusing CREATE_MM from the fp32 path
  3200. if ((device->coopmat2 || device->coopmat_support)
  3201. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3202. && !device->coopmat_bf16_support
  3203. #endif
  3204. ) {
  3205. // use scalar tile sizes
  3206. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  3207. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, 4, 2, 1, subgroup_size_8 };
  3208. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, 2, 2, 1, subgroup_size_8 };
  3209. l_wg_denoms = {128, 128, 1 };
  3210. m_wg_denoms = { 64, 64, 1 };
  3211. s_wg_denoms = { 32, 32, 1 };
  3212. if (device->vendor_id == VK_VENDOR_ID_INTEL && device->architecture == INTEL_XE2) {
  3213. // Xe2/Xe3 - bf16 warptile performance tuning
  3214. l_warptile = { 512, 128, 128, 16, subgroup_size_8, 32, 2, 4, 4, 1, subgroup_size_8 };
  3215. }
  3216. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3217. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, mul_mat_id_param_count, _id, 0);
  3218. }
  3219. #undef CREATE_MM
  3220. // mul mat vec
  3221. // the number of rows computed per shader depends on GPU model and quant
  3222. uint32_t rm_stdq = 1;
  3223. uint32_t rm_kq = 2;
  3224. uint32_t rm_stdq_int = 1;
  3225. uint32_t rm_kq_int = 1;
  3226. auto const &rm_iq_int = [](uint32_t i) { return i == 0 ? 8u : 4u; };
  3227. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3228. if (device->architecture == AMD_GCN) {
  3229. rm_stdq = 2;
  3230. rm_kq = 4;
  3231. rm_stdq_int = 4;
  3232. }
  3233. } else if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3234. rm_stdq = 2;
  3235. rm_stdq_int = 2;
  3236. }
  3237. uint32_t rm_iq = 2 * rm_kq;
  3238. const bool use_subgroups = device->subgroup_arithmetic && device->architecture != vk_device_architecture::AMD_GCN;
  3239. // Ensure a subgroup size >= 16 is available
  3240. const bool use_subgroups16 = use_subgroups && subgroup_min_size_16;
  3241. 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;
  3242. const uint32_t subgroup_size16 = std::max(subgroup_size, 16u);
  3243. const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0;
  3244. const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0;
  3245. static constexpr uint32_t mul_mat_vec_num_bindings = 5;
  3246. static constexpr uint32_t mul_mat_vec_id_num_bindings = 6;
  3247. for (uint32_t w = 0; w < DMMV_WG_SIZE_COUNT; ++w) {
  3248. const uint32_t wg_size_subgroup = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size : (subgroup_size * 4);
  3249. const uint32_t wg_size_subgroup16 = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size16 : (subgroup_size16 * 4);
  3250. const shader_reduction_mode reduc = (use_subgroups && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  3251. (use_subgroups && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  3252. SHADER_REDUCTION_MODE_SHMEM;
  3253. const shader_reduction_mode reduc16 = (use_subgroups16 && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  3254. (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  3255. SHADER_REDUCTION_MODE_SHMEM;
  3256. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  3257. 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);
  3258. 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);
  3259. 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);
  3260. 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);
  3261. 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);
  3262. 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);
  3263. 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);
  3264. 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);
  3265. 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);
  3266. 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);
  3267. 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);
  3268. 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);
  3269. 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);
  3270. 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);
  3271. 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);
  3272. 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);
  3273. 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);
  3274. 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);
  3275. 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);
  3276. 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);
  3277. 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);
  3278. 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);
  3279. 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);
  3280. 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);
  3281. 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);
  3282. 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);
  3283. 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);
  3284. 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);
  3285. 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);
  3286. 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);
  3287. 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);
  3288. 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);
  3289. 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);
  3290. 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);
  3291. 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);
  3292. 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);
  3293. 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);
  3294. 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);
  3295. 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);
  3296. 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);
  3297. 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);
  3298. 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);
  3299. 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);
  3300. 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);
  3301. 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);
  3302. 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);
  3303. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3304. if (device->integer_dot_product) {
  3305. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  3306. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  3307. 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);
  3308. 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);
  3309. 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);
  3310. 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);
  3311. 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);
  3312. 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);
  3313. 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);
  3314. 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);
  3315. 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);
  3316. 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);
  3317. 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);
  3318. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_q8_1_f32", arr_dmmv_iq1_s_q8_1_f32_len[reduc], arr_dmmv_iq1_s_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(i), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(i), i+1}, 1, true, use_subgroups, subgroup_size_int);
  3319. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_q8_1_f32", arr_dmmv_iq1_m_q8_1_f32_len[reduc], arr_dmmv_iq1_m_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(i), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(i), i+1}, 1, true, use_subgroups, subgroup_size_int);
  3320. }
  3321. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  3322. }
  3323. 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);
  3324. 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);
  3325. 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);
  3326. 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);
  3327. 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);
  3328. 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);
  3329. 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);
  3330. 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);
  3331. 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);
  3332. 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);
  3333. 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);
  3334. 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);
  3335. 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);
  3336. 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);
  3337. 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);
  3338. 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);
  3339. 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);
  3340. 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);
  3341. 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);
  3342. 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);
  3343. 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);
  3344. 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);
  3345. 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);
  3346. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3347. if (device->integer_dot_product) {
  3348. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  3349. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  3350. 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_id_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3351. 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_id_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3352. 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_id_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3353. 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_id_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3354. 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_id_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3355. 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_id_push_constants), {2*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3356. 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_id_push_constants), {2*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 2*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3357. 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_id_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3358. 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_id_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3359. 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_id_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3360. 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_id_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3361. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_IQ1_S], "mul_mat_vec_id_iq1_s_q8_1_f32", arr_dmmv_id_iq1_s_q8_1_f32_len[reduc], arr_dmmv_id_iq1_s_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_iq_int(0), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(0)}, 1, true, use_subgroups, subgroup_size_int);
  3362. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_IQ1_M], "mul_mat_vec_id_iq1_m_q8_1_f32", arr_dmmv_id_iq1_m_q8_1_f32_len[reduc], arr_dmmv_id_iq1_m_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_iq_int(0), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(0)}, 1, true, use_subgroups, subgroup_size_int);
  3363. }
  3364. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  3365. }
  3366. #if !defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3367. GGML_UNUSED(rm_stdq_int);
  3368. GGML_UNUSED(rm_kq_int);
  3369. GGML_UNUSED(rm_iq_int);
  3370. #endif
  3371. // dequant shaders
  3372. 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);
  3373. 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);
  3374. 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);
  3375. 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);
  3376. 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);
  3377. 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);
  3378. 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);
  3379. 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);
  3380. 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);
  3381. 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);
  3382. 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);
  3383. 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);
  3384. 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);
  3385. 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);
  3386. 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);
  3387. 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);
  3388. 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);
  3389. 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);
  3390. 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);
  3391. 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);
  3392. 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);
  3393. // get_rows
  3394. 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);
  3395. 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);
  3396. 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);
  3397. 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);
  3398. 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);
  3399. 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);
  3400. 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);
  3401. 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);
  3402. 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);
  3403. 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);
  3404. 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);
  3405. 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);
  3406. 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);
  3407. 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);
  3408. 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);
  3409. 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);
  3410. 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);
  3411. 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);
  3412. 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);
  3413. 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);
  3414. 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);
  3415. 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);
  3416. 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);
  3417. 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);
  3418. 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);
  3419. 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);
  3420. 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);
  3421. 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);
  3422. 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);
  3423. 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);
  3424. 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);
  3425. 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);
  3426. 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);
  3427. 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);
  3428. 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);
  3429. 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);
  3430. 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);
  3431. 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);
  3432. 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);
  3433. 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);
  3434. 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);
  3435. 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);
  3436. 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);
  3437. 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);
  3438. 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);
  3439. 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);
  3440. 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);
  3441. 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);
  3442. 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);
  3443. if (device->subgroup_clustered && device->subgroup_require_full_support) {
  3444. 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, sizeof(vk_quantize_q8_1_push_constants), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1, true, true);
  3445. } else {
  3446. 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, sizeof(vk_quantize_q8_1_push_constants), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1);
  3447. }
  3448. for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) {
  3449. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3450. 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);
  3451. } else {
  3452. 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);
  3453. }
  3454. }
  3455. 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);
  3456. 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);
  3457. 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);
  3458. 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);
  3459. 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);
  3460. 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);
  3461. 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);
  3462. if (device->float_controls_rte_fp16 &&
  3463. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= device->properties.limits.maxPushConstantsSize) {
  3464. 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);
  3465. 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);
  3466. }
  3467. 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);
  3468. 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);
  3469. 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);
  3470. 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);
  3471. 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);
  3472. 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);
  3473. 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);
  3474. 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);
  3475. 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);
  3476. 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);
  3477. 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);
  3478. 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);
  3479. 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);
  3480. 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);
  3481. 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);
  3482. 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);
  3483. 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);
  3484. 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);
  3485. if (device->float_controls_rte_fp16) {
  3486. 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);
  3487. 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);
  3488. 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);
  3489. 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);
  3490. 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);
  3491. 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);
  3492. } else {
  3493. 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);
  3494. 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);
  3495. 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);
  3496. 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);
  3497. 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);
  3498. 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);
  3499. }
  3500. #define SET_ROWS(itype, rte) \
  3501. 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); \
  3502. 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); \
  3503. 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); \
  3504. 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); \
  3505. 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); \
  3506. 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); \
  3507. 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); \
  3508. 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); \
  3509. 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);
  3510. if (device->float_controls_rte_fp16) {
  3511. SET_ROWS(_i32, _rte)
  3512. SET_ROWS(_i64, _rte)
  3513. } else {
  3514. SET_ROWS(_i32, )
  3515. SET_ROWS(_i64, )
  3516. }
  3517. #undef SET_ROWS
  3518. 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);
  3519. 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);
  3520. 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);
  3521. 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);
  3522. 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);
  3523. 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);
  3524. auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) {
  3525. std::string s;
  3526. s += std::string(src0_f16 ? "_f16" : "_f32");
  3527. s += std::string(src1_f16 ? "_f16" : "_f32");
  3528. s += std::string(dst_f16 ? "_f16" : "_f32");
  3529. return s;
  3530. };
  3531. bool rte = device->float_controls_rte_fp16;
  3532. #define CREATE_BINARY(name, namemod, spec, bindings) \
  3533. for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \
  3534. ggml_vk_create_pipeline2(device, device->pipeline_ ## name ## namemod[s0][s1][d], \
  3535. #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d][rte], name ## _data[s0][s1][d][rte], \
  3536. "main", (bindings), sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1);
  3537. CREATE_BINARY(add, , {0}, 4)
  3538. CREATE_BINARY(add, _norepeat, {1}, 4)
  3539. CREATE_BINARY(sub, , {0}, 3)
  3540. CREATE_BINARY(sub, _norepeat, {1}, 3)
  3541. CREATE_BINARY(mul, , {0}, 3)
  3542. CREATE_BINARY(mul, _norepeat, {1}, 3)
  3543. CREATE_BINARY(div, , {0}, 3)
  3544. CREATE_BINARY(div, _norepeat, {1}, 3)
  3545. CREATE_BINARY(add_rms, , {0}, 4)
  3546. CREATE_BINARY(add_rms, _norepeat, {1}, 4)
  3547. #undef CREATE_BINARY
  3548. if (device->multi_add) {
  3549. for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) {
  3550. 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);
  3551. 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);
  3552. }
  3553. }
  3554. 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);
  3555. 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);
  3556. 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);
  3557. 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);
  3558. 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);
  3559. 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);
  3560. 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);
  3561. 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);
  3562. 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);
  3563. 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);
  3564. 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);
  3565. 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);
  3566. 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);
  3567. 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);
  3568. if (device->float_controls_rte_fp16) {
  3569. 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);
  3570. 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);
  3571. } else {
  3572. 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);
  3573. 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);
  3574. }
  3575. 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);
  3576. 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);
  3577. 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);
  3578. 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);
  3579. 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);
  3580. 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);
  3581. 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);
  3582. 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);
  3583. 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);
  3584. #define CREATE_UNARY(name) \
  3585. 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); \
  3586. 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);
  3587. CREATE_UNARY(gelu)
  3588. CREATE_UNARY(gelu_erf)
  3589. CREATE_UNARY(gelu_quick)
  3590. CREATE_UNARY(silu)
  3591. CREATE_UNARY(relu)
  3592. CREATE_UNARY(xielu)
  3593. CREATE_UNARY(neg)
  3594. CREATE_UNARY(tanh)
  3595. CREATE_UNARY(sigmoid)
  3596. CREATE_UNARY(hardsigmoid)
  3597. CREATE_UNARY(hardswish)
  3598. CREATE_UNARY(abs)
  3599. CREATE_UNARY(softplus)
  3600. CREATE_UNARY(step)
  3601. CREATE_UNARY(round)
  3602. CREATE_UNARY(ceil)
  3603. CREATE_UNARY(floor)
  3604. CREATE_UNARY(trunc)
  3605. #undef CREATE_UNARY
  3606. #define CREATE_UNARY_RTE(name) \
  3607. if (device->float_controls_rte_fp16) { \
  3608. 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); \
  3609. 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); \
  3610. } else { \
  3611. 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); \
  3612. 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); \
  3613. }
  3614. CREATE_UNARY_RTE(exp)
  3615. #undef CREATE_UNARY_RTE
  3616. 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);
  3617. 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);
  3618. 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);
  3619. ggml_vk_create_pipeline(device, device->pipeline_arange_f32, "arange_f32", arange_f32_len, arange_f32_data, "main", 1, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3620. ggml_vk_create_pipeline(device, device->pipeline_fill_f32, "fill_f32", fill_f32_len, fill_f32_data, "main", 1, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3621. #define CREATE_GLU(name) \
  3622. if (device->float_controls_rte_fp16) { \
  3623. 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); \
  3624. 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); \
  3625. } else { \
  3626. 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); \
  3627. 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); \
  3628. }
  3629. CREATE_GLU(geglu)
  3630. CREATE_GLU(reglu)
  3631. CREATE_GLU(swiglu)
  3632. CREATE_GLU(swiglu_oai)
  3633. CREATE_GLU(geglu_erf)
  3634. CREATE_GLU(geglu_quick)
  3635. #undef CREATE_GLU
  3636. 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);
  3637. 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);
  3638. 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);
  3639. 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);
  3640. 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);
  3641. 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);
  3642. 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);
  3643. 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);
  3644. 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);
  3645. 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);
  3646. 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);
  3647. 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);
  3648. 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);
  3649. 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);
  3650. 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);
  3651. 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);
  3652. 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);
  3653. 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);
  3654. if (device->float_controls_rte_fp16) {
  3655. 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);
  3656. 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);
  3657. 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);
  3658. 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);
  3659. 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);
  3660. 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);
  3661. 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);
  3662. } else {
  3663. 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);
  3664. 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);
  3665. 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);
  3666. 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);
  3667. 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);
  3668. 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);
  3669. 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);
  3670. }
  3671. for (uint32_t i = 0; i < num_argsort_pipelines; ++i) {
  3672. uint32_t BLOCK_SIZE = 1u << std::min(i, device->max_workgroup_size_log2);
  3673. if (i <= device->max_workgroup_size_log2 &&
  3674. 2 * sizeof(int) * BLOCK_SIZE <= device->properties.limits.maxComputeSharedMemorySize) {
  3675. const uint32_t NCOLS_PADDED_LOG2 = i;
  3676. 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);
  3677. }
  3678. const uint32_t WG_UNROLL_FACTOR = BLOCK_SIZE > 1 ? 2 : 1;
  3679. BLOCK_SIZE /= WG_UNROLL_FACTOR;
  3680. 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);
  3681. }
  3682. for (uint32_t i = 0; i < num_topk_pipelines; ++i) {
  3683. const uint32_t BLOCK_SIZE = 1u << i;
  3684. const uint32_t NCOLS_PADDED_LOG2 = i;
  3685. if (i <= device->max_workgroup_size_log2) {
  3686. uint32_t nary_shmem = 2 * sizeof(int) * BLOCK_SIZE +
  3687. sizeof(int) * device->subgroup_size +
  3688. 2 * sizeof(int) +
  3689. 2 * (BLOCK_SIZE / device->subgroup_size) * sizeof(int);
  3690. if (device->subgroup_arithmetic && device->subgroup_require_full_support && device->subgroup_shuffle && device->subgroup_ballot &&
  3691. nary_shmem <= device->properties.limits.maxComputeSharedMemorySize) {
  3692. 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);
  3693. } else if (2 * sizeof(int) * BLOCK_SIZE <= device->properties.limits.maxComputeSharedMemorySize) {
  3694. 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);
  3695. }
  3696. }
  3697. }
  3698. 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);
  3699. 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);
  3700. const uint32_t cumsum_elem_per_thread = (device->vendor_id == VK_VENDOR_ID_AMD || device->vendor_id == VK_VENDOR_ID_INTEL) ? 2 : 4;
  3701. ggml_vk_create_pipeline(device, device->pipeline_cumsum_f32, "cumsum_f32", cumsum_f32_len, cumsum_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { 256, device->subgroup_size, cumsum_elem_per_thread }, 1, true, true, device->subgroup_size);
  3702. ggml_vk_create_pipeline(device, device->pipeline_cumsum_small_f32, "cumsum_f32", cumsum_f32_len, cumsum_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { 128, device->subgroup_size, 1 }, 1, true, true, device->subgroup_size);
  3703. ggml_vk_create_pipeline(device, device->pipeline_cumsum_multipass1_f32, "cumsum_multipass1_f32", cumsum_multipass1_f32_len, cumsum_multipass1_f32_data, "main", 3, sizeof(vk_op_sum_rows_push_constants), {256, 1, 1}, { 256, device->subgroup_size }, 1, true, true, device->subgroup_size);
  3704. ggml_vk_create_pipeline(device, device->pipeline_cumsum_multipass2_f32, "cumsum_multipass2_f32", cumsum_multipass2_f32_len, cumsum_multipass2_f32_data, "main", 3, sizeof(vk_op_sum_rows_push_constants), {256, 1, 1}, { 256, device->subgroup_size }, 1, true, true, device->subgroup_size);
  3705. 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);
  3706. ggml_vk_create_pipeline(device, device->pipeline_count_experts, "count_experts", count_experts_len, count_experts_data, "main", 2, sizeof(vk_op_count_experts_push_constants), {1, 1, 1}, {}, 1, true);
  3707. for (auto &s : device->pipeline_solve_tri_f32) {
  3708. const vk_solve_tri_pipeline_state &state = s.first;
  3709. // Max number of rows to load at a time, limited by shared memory
  3710. const uint32_t batch_N = device->properties.limits.maxComputeSharedMemorySize / ((state.N + state.K) * sizeof(float));
  3711. // Need at least K invocations, and prefer a minimum of 128 to spread out loading shared memory
  3712. const uint32_t block_size = std::max(128u, 1u << (uint32_t)ceilf(log2f(float(state.K))));
  3713. ggml_vk_create_pipeline(
  3714. device, s.second, "solve_tri_f32",
  3715. solve_tri_f32_len, solve_tri_f32_data, "main", 3,
  3716. sizeof(vk_op_binary_push_constants), {1, 1, 1}, { 0, state.N, state.K, batch_N, block_size }, 1, true);
  3717. }
  3718. #define IM2COL(bda) \
  3719. 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); \
  3720. 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); \
  3721. if (device->float_controls_rte_fp16) { \
  3722. 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); \
  3723. 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); \
  3724. } else { \
  3725. 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); \
  3726. 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); \
  3727. }
  3728. if (device->shader_int64 && device->buffer_device_address) {
  3729. IM2COL(_bda)
  3730. } else {
  3731. IM2COL()
  3732. }
  3733. 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);
  3734. 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);
  3735. 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);
  3736. 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);
  3737. 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);
  3738. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3739. 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}, 1, true, true);
  3740. 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}, 1, true, true);
  3741. } else {
  3742. 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);
  3743. 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);
  3744. }
  3745. 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);
  3746. 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);
  3747. 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);
  3748. // conv2d, conv_transpose_2d
  3749. for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) {
  3750. uint32_t conv2d_WG_SIZE = 256;
  3751. uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices.
  3752. uint32_t conv2d_TS_K = (s == CONV_SHAPE_64x32) ? 4 : 8;
  3753. uint32_t conv2d_SHMEM_PAD = 4;
  3754. vk_conv_block_size conv2d_BS = vk_conv_block_sizes[s];
  3755. bool conv2d_UNROLL = true;
  3756. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3757. if (device->coopmat2) {
  3758. conv2d_SHMEM_PAD = 8; // 8 float16_t
  3759. }
  3760. #endif
  3761. if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3762. conv2d_SHMEM_PAD = 0;
  3763. conv2d_UNROLL = false;
  3764. } else if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3765. conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4;
  3766. if (s == CONV_SHAPE_128x128 && device->architecture != vk_device_architecture::AMD_GCN) {
  3767. conv2d_UNROLL = false;
  3768. }
  3769. }
  3770. // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math.
  3771. bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA ||
  3772. device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  3773. bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD ||
  3774. device->architecture == vk_device_architecture::AMD_GCN;
  3775. if (device->subgroup_shuffle &&
  3776. device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316.
  3777. allow_collectives_nv &&
  3778. allow_collectives_amd) {
  3779. use_collectives = 1;
  3780. conv2d_BS.CRS = std::min(
  3781. device->subgroup_size,
  3782. conv2d_BS.CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used.
  3783. }
  3784. uint32_t conv2d_shmem_req =
  3785. (conv2d_BS.K * (conv2d_BS.CRS + conv2d_SHMEM_PAD) + conv2d_BS.CRS * (conv2d_BS.NPQ + conv2d_SHMEM_PAD)) * sizeof(float);
  3786. if (device->properties.limits.maxComputeSharedMemorySize < conv2d_shmem_req) {
  3787. conv2d_BS.CRS = 8;
  3788. if (use_collectives) {
  3789. conv2d_BS.CRS = std::min(device->subgroup_size, conv2d_BS.CRS);
  3790. }
  3791. }
  3792. std::array<uint32_t, 3> wg_denoms = { conv2d_BS.K, 1, 1 };
  3793. 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 };
  3794. #define CREATE_CONV(name, type_suffix, spv_suffix) \
  3795. for (auto &c : device->pipeline_##name##type_suffix[s]) { \
  3796. const vk_conv2d_pipeline_state &state = c.first; \
  3797. std::vector<uint32_t> spec_constants_cpy = spec_constants; \
  3798. spec_constants_cpy.push_back(state.s0); \
  3799. spec_constants_cpy.push_back(state.s1); \
  3800. spec_constants_cpy.push_back(state.p0); \
  3801. spec_constants_cpy.push_back(state.p1); \
  3802. spec_constants_cpy.push_back(state.d0); \
  3803. spec_constants_cpy.push_back(state.d1); \
  3804. spec_constants_cpy.push_back(state.KW); \
  3805. spec_constants_cpy.push_back(state.KH); \
  3806. ggml_vk_create_pipeline( \
  3807. device, c.second, #name #type_suffix, \
  3808. name##type_suffix##spv_suffix##_len, name##type_suffix##spv_suffix##_data, "main", 3, \
  3809. sizeof(vk_op_conv2d_push_constants), wg_denoms, spec_constants_cpy, 1, true, use_collectives); \
  3810. }
  3811. #define CREATE_CONVS(spv_suffix) \
  3812. CREATE_CONV(conv2d, _f32, spv_suffix) \
  3813. CREATE_CONV(conv2d, _f16_f32, spv_suffix) \
  3814. CREATE_CONV(conv_transpose_2d, _f32, spv_suffix) \
  3815. CREATE_CONV(conv_transpose_2d, _f16_f32, spv_suffix)
  3816. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3817. if (device->coopmat2) {
  3818. CREATE_CONVS(_cm2)
  3819. } else
  3820. #endif
  3821. if (conv2d_UNROLL) {
  3822. CREATE_CONVS(_unroll)
  3823. } else {
  3824. CREATE_CONVS( )
  3825. }
  3826. #undef CREATE_CONV
  3827. #undef CREATE_CONVS
  3828. }
  3829. 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);
  3830. 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);
  3831. 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);
  3832. 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);
  3833. for (uint32_t use_push = 0; use_push < 2; ++use_push) {
  3834. for (uint32_t i = 0; i < num_topk_moe_pipelines; ++i) {
  3835. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][use_push], "topk_moe_f32_"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 4, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, use_push}, 1, true, true, device->subgroup_size);
  3836. }
  3837. }
  3838. for (auto &c : compiles) {
  3839. c.wait();
  3840. }
  3841. }
  3842. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch);
  3843. static vk_device ggml_vk_get_device(size_t idx) {
  3844. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  3845. if (vk_instance.devices[idx] == nullptr) {
  3846. VK_LOG_DEBUG("Initializing new vk_device");
  3847. vk_device device = std::make_shared<vk_device_struct>();
  3848. vk_instance.devices[idx] = device;
  3849. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  3850. size_t dev_num = vk_instance.device_indices[idx];
  3851. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  3852. if (dev_num >= physical_devices.size()) {
  3853. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3854. throw std::runtime_error("Device not found");
  3855. }
  3856. device->physical_device = physical_devices[dev_num];
  3857. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  3858. device->architecture = get_device_architecture(device->physical_device);
  3859. const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY");
  3860. device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr;
  3861. const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM");
  3862. device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr;
  3863. const char* GGML_VK_ALLOW_SYSMEM_FALLBACK = getenv("GGML_VK_ALLOW_SYSMEM_FALLBACK");
  3864. device->allow_sysmem_fallback = GGML_VK_ALLOW_SYSMEM_FALLBACK != nullptr;
  3865. const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE");
  3866. device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr;
  3867. bool fp16_storage = false;
  3868. bool fp16_compute = false;
  3869. bool maintenance4_support = false;
  3870. bool sm_builtins = false;
  3871. bool amd_shader_core_properties2 = false;
  3872. bool pipeline_robustness = false;
  3873. bool coopmat2_support = false;
  3874. bool pipeline_executable_properties_support = false;
  3875. device->coopmat_support = false;
  3876. device->integer_dot_product = false;
  3877. device->shader_64b_indexing = false;
  3878. bool bfloat16_support = false;
  3879. for (const auto& properties : ext_props) {
  3880. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  3881. maintenance4_support = true;
  3882. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3883. fp16_storage = true;
  3884. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3885. fp16_compute = true;
  3886. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  3887. sm_builtins = true;
  3888. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  3889. amd_shader_core_properties2 = true;
  3890. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  3891. pipeline_robustness = true;
  3892. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  3893. device->subgroup_size_control = true;
  3894. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3895. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3896. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3897. device->coopmat_support = true;
  3898. device->coopmat_m = 0;
  3899. device->coopmat_n = 0;
  3900. device->coopmat_k = 0;
  3901. #endif
  3902. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3903. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3904. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3905. coopmat2_support = true;
  3906. #endif
  3907. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3908. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3909. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3910. device->integer_dot_product = true;
  3911. #endif
  3912. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3913. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3914. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3915. bfloat16_support = true;
  3916. #endif
  3917. } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) {
  3918. pipeline_executable_properties_support = true;
  3919. } else if (strcmp("VK_EXT_memory_priority", properties.extensionName) == 0 &&
  3920. getenv("GGML_VK_ENABLE_MEMORY_PRIORITY")) {
  3921. device->memory_priority = true;
  3922. } else if (strcmp("VK_EXT_external_memory_host", properties.extensionName) == 0) {
  3923. device->external_memory_host = true;
  3924. #if defined(VK_EXT_shader_64bit_indexing)
  3925. } else if (strcmp("VK_EXT_shader_64bit_indexing", properties.extensionName) == 0) {
  3926. device->shader_64b_indexing = true;
  3927. #endif
  3928. }
  3929. }
  3930. vk::PhysicalDeviceProperties2 props2;
  3931. vk::PhysicalDeviceMaintenance3Properties props3;
  3932. vk::PhysicalDeviceMaintenance4Properties props4;
  3933. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3934. vk::PhysicalDeviceDriverProperties driver_props;
  3935. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  3936. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  3937. vk::PhysicalDeviceVulkan11Properties vk11_props;
  3938. vk::PhysicalDeviceVulkan12Properties vk12_props;
  3939. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  3940. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3941. vk::PhysicalDeviceExternalMemoryHostPropertiesEXT external_memory_host_props;
  3942. props2.pNext = &props3;
  3943. props3.pNext = &subgroup_props;
  3944. subgroup_props.pNext = &driver_props;
  3945. driver_props.pNext = &vk11_props;
  3946. vk11_props.pNext = &vk12_props;
  3947. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  3948. if (maintenance4_support) {
  3949. last_struct->pNext = (VkBaseOutStructure *)&props4;
  3950. last_struct = (VkBaseOutStructure *)&props4;
  3951. }
  3952. if (sm_builtins) {
  3953. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  3954. last_struct = (VkBaseOutStructure *)&sm_props;
  3955. }
  3956. if (amd_shader_core_properties2) {
  3957. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3958. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3959. }
  3960. if (device->subgroup_size_control) {
  3961. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  3962. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  3963. }
  3964. #if defined(VK_NV_cooperative_matrix2)
  3965. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  3966. if (coopmat2_support) {
  3967. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  3968. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  3969. }
  3970. #endif
  3971. if (device->integer_dot_product) {
  3972. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3973. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3974. }
  3975. if (device->external_memory_host) {
  3976. last_struct->pNext = (VkBaseOutStructure *)&external_memory_host_props;
  3977. last_struct = (VkBaseOutStructure *)&external_memory_host_props;
  3978. }
  3979. device->physical_device.getProperties2(&props2);
  3980. device->properties = props2.properties;
  3981. device->vendor_id = device->properties.vendorID;
  3982. device->driver_id = driver_props.driverID;
  3983. if (device->driver_id == vk::DriverId::eMoltenvk) {
  3984. // Disable external_memory_host until https://github.com/KhronosGroup/MoltenVK/pull/2622
  3985. // is available in the Vulkan SDK.
  3986. device->external_memory_host = false;
  3987. }
  3988. // Implementing the async backend interfaces seems broken on older Intel HW,
  3989. // see https://github.com/ggml-org/llama.cpp/issues/17302.
  3990. device->support_async = (device->vendor_id != VK_VENDOR_ID_INTEL ||
  3991. std::string(device->properties.deviceName.data()).find("(DG1)") == std::string::npos) &&
  3992. getenv("GGML_VK_DISABLE_ASYNC") == nullptr;
  3993. if (!device->support_async) {
  3994. GGML_LOG_DEBUG("ggml_vulkan: WARNING: Async execution disabled on certain Intel devices.\n");
  3995. }
  3996. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  3997. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  3998. device->max_memory_allocation_size = std::stoull(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  3999. } else if (maintenance4_support) {
  4000. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  4001. } else {
  4002. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  4003. }
  4004. const char* GGML_VK_FORCE_MAX_BUFFER_SIZE = getenv("GGML_VK_FORCE_MAX_BUFFER_SIZE");
  4005. if (GGML_VK_FORCE_MAX_BUFFER_SIZE != nullptr) {
  4006. device->max_buffer_size = std::stoull(GGML_VK_FORCE_MAX_BUFFER_SIZE);
  4007. } else if (maintenance4_support) {
  4008. device->max_buffer_size = props4.maxBufferSize;
  4009. } else {
  4010. device->max_buffer_size = device->max_memory_allocation_size;
  4011. }
  4012. const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE");
  4013. if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) {
  4014. device->suballocation_block_size = std::stoull(GGML_VK_SUBALLOCATION_BLOCK_SIZE);
  4015. } else {
  4016. // Limit batching of allocations to 1GB by default to avoid fragmentation issues
  4017. device->suballocation_block_size = 1024*1024*1024;
  4018. }
  4019. device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size);
  4020. device->subgroup_size = subgroup_props.subgroupSize;
  4021. device->subgroup_size_log2 = uint32_t(log2f(float(device->subgroup_size)));
  4022. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  4023. if (sm_builtins) {
  4024. device->shader_core_count = sm_props.shaderSMCount;
  4025. } else if (amd_shader_core_properties2) {
  4026. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  4027. } else {
  4028. device->shader_core_count = 0;
  4029. }
  4030. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  4031. device->subgroup_basic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4032. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBasic);
  4033. device->subgroup_arithmetic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4034. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic);
  4035. #ifdef __APPLE__
  4036. // Workaround for subgroup arithmetic failing on MoltenVK with AMD GPUs (issue 15846)
  4037. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  4038. device->subgroup_arithmetic = false;
  4039. }
  4040. #endif
  4041. device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4042. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle);
  4043. device->subgroup_clustered = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4044. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eClustered);
  4045. device->subgroup_ballot = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4046. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBallot);
  4047. device->subgroup_vote = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  4048. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eVote);
  4049. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  4050. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  4051. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) {
  4052. device->coopmat_support = false;
  4053. }
  4054. device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated;
  4055. device->min_imported_host_pointer_alignment = external_memory_host_props.minImportedHostPointerAlignment;
  4056. device->max_workgroup_size_log2 = uint32_t(log2f(float(device->properties.limits.maxComputeWorkGroupInvocations)));
  4057. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  4058. // Try to find a non-graphics compute queue and transfer-focused queues
  4059. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  4060. 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);
  4061. const float priorities[] = { 1.0f, 1.0f };
  4062. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  4063. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  4064. if (compute_queue_family_index != transfer_queue_family_index) {
  4065. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  4066. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  4067. } else if(!device->single_queue) {
  4068. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  4069. } else {
  4070. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  4071. }
  4072. vk::DeviceCreateInfo device_create_info;
  4073. std::vector<const char *> device_extensions;
  4074. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  4075. VkPhysicalDeviceFeatures2 device_features2;
  4076. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  4077. device_features2.pNext = nullptr;
  4078. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  4079. VkPhysicalDeviceVulkan11Features vk11_features;
  4080. vk11_features.pNext = nullptr;
  4081. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  4082. device_features2.pNext = &vk11_features;
  4083. VkPhysicalDeviceVulkan12Features vk12_features;
  4084. vk12_features.pNext = nullptr;
  4085. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  4086. vk11_features.pNext = &vk12_features;
  4087. last_struct = (VkBaseOutStructure *)&vk12_features;
  4088. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  4089. pl_robustness_features.pNext = nullptr;
  4090. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  4091. pl_robustness_features.pipelineRobustness = VK_FALSE;
  4092. if (pipeline_robustness) {
  4093. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  4094. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  4095. device_extensions.push_back("VK_EXT_pipeline_robustness");
  4096. }
  4097. VkPhysicalDeviceMemoryPriorityFeaturesEXT memory_priority_features;
  4098. memory_priority_features.pNext = nullptr;
  4099. memory_priority_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PRIORITY_FEATURES_EXT;
  4100. memory_priority_features.memoryPriority = VK_FALSE;
  4101. if (device->memory_priority) {
  4102. last_struct->pNext = (VkBaseOutStructure *)&memory_priority_features;
  4103. last_struct = (VkBaseOutStructure *)&memory_priority_features;
  4104. device_extensions.push_back("VK_EXT_memory_priority");
  4105. }
  4106. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  4107. subgroup_size_control_features.pNext = nullptr;
  4108. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  4109. subgroup_size_control_features.computeFullSubgroups = false;
  4110. subgroup_size_control_features.subgroupSizeControl = false;
  4111. if (device->subgroup_size_control) {
  4112. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  4113. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  4114. }
  4115. #if defined(VK_KHR_cooperative_matrix)
  4116. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  4117. coopmat_features.pNext = nullptr;
  4118. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  4119. coopmat_features.cooperativeMatrix = VK_FALSE;
  4120. if (device->coopmat_support) {
  4121. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  4122. last_struct = (VkBaseOutStructure *)&coopmat_features;
  4123. }
  4124. #endif
  4125. #if defined(VK_NV_cooperative_matrix2)
  4126. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  4127. coopmat2_features.pNext = nullptr;
  4128. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  4129. if (coopmat2_support) {
  4130. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  4131. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  4132. device_extensions.push_back("VK_NV_cooperative_matrix2");
  4133. }
  4134. #endif
  4135. #if defined(VK_KHR_shader_bfloat16)
  4136. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  4137. bfloat16_features.pNext = nullptr;
  4138. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  4139. if (bfloat16_support) {
  4140. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  4141. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  4142. device_extensions.push_back("VK_KHR_shader_bfloat16");
  4143. }
  4144. #endif
  4145. VkPhysicalDeviceMaintenance4Features maint4_features {};
  4146. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  4147. if (maintenance4_support) {
  4148. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  4149. last_struct = (VkBaseOutStructure *)&maint4_features;
  4150. device_extensions.push_back("VK_KHR_maintenance4");
  4151. }
  4152. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  4153. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  4154. if (device->integer_dot_product) {
  4155. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4156. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4157. device_extensions.push_back("VK_KHR_shader_integer_dot_product");
  4158. }
  4159. VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pep_features {};
  4160. pep_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR;
  4161. if (pipeline_executable_properties_support) {
  4162. last_struct->pNext = (VkBaseOutStructure *)&pep_features;
  4163. last_struct = (VkBaseOutStructure *)&pep_features;
  4164. device_extensions.push_back("VK_KHR_pipeline_executable_properties");
  4165. }
  4166. if (device->external_memory_host) {
  4167. device_extensions.push_back("VK_EXT_external_memory_host");
  4168. }
  4169. #if defined(VK_EXT_shader_64bit_indexing)
  4170. VkPhysicalDeviceShader64BitIndexingFeaturesEXT shader_64bit_indexing_features {};
  4171. shader_64bit_indexing_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_64_BIT_INDEXING_FEATURES_EXT;
  4172. if (device->shader_64b_indexing) {
  4173. last_struct->pNext = (VkBaseOutStructure *)&shader_64bit_indexing_features;
  4174. last_struct = (VkBaseOutStructure *)&shader_64bit_indexing_features;
  4175. device_extensions.push_back("VK_EXT_shader_64bit_indexing");
  4176. }
  4177. #endif
  4178. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  4179. device->pipeline_executable_properties_support = pipeline_executable_properties_support;
  4180. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  4181. #if defined(VK_KHR_shader_bfloat16)
  4182. device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4183. #else
  4184. device->bf16 = false;
  4185. #endif
  4186. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  4187. device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 &&
  4188. device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) &&
  4189. getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr;
  4190. device->shader_int64 = device_features2.features.shaderInt64;
  4191. device->buffer_device_address = vk12_features.bufferDeviceAddress;
  4192. device->vulkan_memory_model = vk12_features.vulkanMemoryModel;
  4193. if (device->subgroup_size_control) {
  4194. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  4195. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  4196. device_extensions.push_back("VK_EXT_subgroup_size_control");
  4197. }
  4198. device->subgroup_size_control = device->subgroup_size_control &&
  4199. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  4200. subgroup_size_control_features.subgroupSizeControl;
  4201. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  4202. #if defined(VK_KHR_cooperative_matrix)
  4203. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  4204. // coopmat1 fa shader currently assumes 32 invocations per subgroup
  4205. device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support &&
  4206. device->subgroup_size_control && device->subgroup_min_size <= 32 &&
  4207. device->subgroup_max_size >= 32;
  4208. #endif
  4209. if (coopmat2_support) {
  4210. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  4211. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  4212. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  4213. coopmat2_features.cooperativeMatrixReductions &&
  4214. coopmat2_features.cooperativeMatrixConversions &&
  4215. coopmat2_features.cooperativeMatrixPerElementOperations &&
  4216. coopmat2_features.cooperativeMatrixTensorAddressing &&
  4217. coopmat2_features.cooperativeMatrixBlockLoads &&
  4218. vk12_features.bufferDeviceAddress) {
  4219. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  4220. uint32_t count = 0;
  4221. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  4222. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  4223. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  4224. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  4225. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  4226. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  4227. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  4228. flexible_dimensions.resize(count, empty_prop);
  4229. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  4230. bool found_fp16_128 = false,
  4231. found_fp16_256 = false,
  4232. found_fp32_128 = false,
  4233. found_fp32_256 = false;
  4234. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  4235. // with 32x16x16 and 256 with 32x32x16.
  4236. for (auto &prop : flexible_dimensions) {
  4237. if (prop.saturatingAccumulation == VK_FALSE &&
  4238. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  4239. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4240. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4241. if (prop.workgroupInvocations == 128 &&
  4242. prop.MGranularity <= 32 &&
  4243. prop.NGranularity <= 16 &&
  4244. prop.KGranularity <= 16) {
  4245. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4246. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4247. found_fp16_128 = true;
  4248. }
  4249. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4250. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  4251. found_fp32_128 = true;
  4252. }
  4253. }
  4254. if (prop.workgroupInvocations == 256 &&
  4255. prop.MGranularity <= 32 &&
  4256. prop.NGranularity <= 32 &&
  4257. prop.KGranularity <= 16) {
  4258. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4259. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4260. found_fp16_256 = true;
  4261. }
  4262. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4263. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  4264. found_fp32_256 = true;
  4265. }
  4266. }
  4267. }
  4268. }
  4269. if (found_fp16_128 && found_fp16_256 &&
  4270. found_fp32_128 && found_fp32_256 &&
  4271. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  4272. device->coopmat2 = true;
  4273. }
  4274. }
  4275. #endif
  4276. }
  4277. if (!vk11_features.storageBuffer16BitAccess) {
  4278. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  4279. throw std::runtime_error("Unsupported device");
  4280. }
  4281. device_extensions.push_back("VK_KHR_16bit_storage");
  4282. #ifdef GGML_VULKAN_VALIDATE
  4283. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  4284. #endif
  4285. if (device->fp16) {
  4286. device_extensions.push_back("VK_KHR_shader_float16_int8");
  4287. }
  4288. #if defined(VK_KHR_cooperative_matrix)
  4289. if (device->coopmat_support) {
  4290. // Query supported shapes
  4291. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  4292. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  4293. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  4294. uint32_t cm_props_num;
  4295. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  4296. cm_props.resize(cm_props_num);
  4297. for (auto& prop : cm_props) {
  4298. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  4299. }
  4300. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  4301. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  4302. for (auto& prop : cm_props) {
  4303. 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));
  4304. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  4305. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  4306. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  4307. ) {
  4308. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  4309. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  4310. // coopmat sizes not set yet
  4311. if (device->coopmat_m == 0) {
  4312. device->coopmat_acc_f32_support = true;
  4313. device->coopmat_m = prop.MSize;
  4314. device->coopmat_n = prop.NSize;
  4315. device->coopmat_k = prop.KSize;
  4316. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4317. // Only enable if shape is identical
  4318. device->coopmat_acc_f32_support = true;
  4319. }
  4320. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  4321. device->coopmat_support_16x16x16_f32acc = true;
  4322. }
  4323. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  4324. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  4325. // coopmat sizes not set yet
  4326. if (device->coopmat_m == 0) {
  4327. device->coopmat_acc_f16_support = true;
  4328. device->coopmat_m = prop.MSize;
  4329. device->coopmat_n = prop.NSize;
  4330. device->coopmat_k = prop.KSize;
  4331. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4332. // Only enable if shape is identical
  4333. device->coopmat_acc_f16_support = true;
  4334. }
  4335. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  4336. device->coopmat_support_16x16x16_f16acc = true;
  4337. }
  4338. }
  4339. } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 &&
  4340. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 &&
  4341. (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 &&
  4342. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 &&
  4343. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup &&
  4344. device->coopmat_int_m == 0
  4345. ) {
  4346. device->coopmat_int_support = true;
  4347. device->coopmat_int_m = prop.MSize;
  4348. device->coopmat_int_n = prop.NSize;
  4349. device->coopmat_int_k = prop.KSize;
  4350. }
  4351. #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4352. if (prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  4353. prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  4354. prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4355. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4356. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  4357. ) {
  4358. // coopmat sizes not set yet
  4359. if (device->coopmat_m == 0) {
  4360. device->coopmat_bf16_support = true;
  4361. device->coopmat_m = prop.MSize;
  4362. device->coopmat_n = prop.NSize;
  4363. device->coopmat_k = prop.KSize;
  4364. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4365. // Only enable if shape is identical
  4366. device->coopmat_bf16_support = true;
  4367. }
  4368. }
  4369. #endif
  4370. }
  4371. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  4372. // No suitable matmul mode found
  4373. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  4374. device->coopmat_support = false;
  4375. }
  4376. if (getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4377. device->coopmat_bf16_support = false;
  4378. }
  4379. }
  4380. if (device->coopmat_support) {
  4381. device_extensions.push_back("VK_KHR_cooperative_matrix");
  4382. }
  4383. #if defined(VK_KHR_shader_bfloat16)
  4384. if (device->coopmat_bf16_support) {
  4385. device_extensions.push_back("VK_KHR_shader_bfloat16");
  4386. }
  4387. #endif
  4388. #endif
  4389. device->name = GGML_VK_NAME + std::to_string(idx);
  4390. device_create_info = {
  4391. vk::DeviceCreateFlags(),
  4392. device_queue_create_infos,
  4393. {},
  4394. device_extensions
  4395. };
  4396. device_create_info.setPNext(&device_features2);
  4397. device->device = device->physical_device.createDevice(device_create_info);
  4398. // Queues
  4399. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  4400. // Shaders
  4401. // Disable matmul tile sizes early if performance low or not supported
  4402. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  4403. switch (device->vendor_id) {
  4404. #ifndef GGML_VULKAN_RUN_TESTS
  4405. case VK_VENDOR_ID_AMD:
  4406. device->mul_mat_l[i] = device->coopmat_support && device->driver_id != vk::DriverId::eAmdProprietary;
  4407. device->mul_mat_m[i] = true;
  4408. device->mul_mat_s[i] = true;
  4409. device->mul_mat_id_l[i] = false;
  4410. device->mul_mat_id_m[i] = true;
  4411. device->mul_mat_id_s[i] = true;
  4412. break;
  4413. case VK_VENDOR_ID_INTEL:
  4414. if (!device->coopmat_support || device->architecture != INTEL_XE2) {
  4415. device->mul_mat_l[i] = false;
  4416. device->mul_mat_id_l[i] = false;
  4417. } else {
  4418. device->mul_mat_l[i] = true; // if coopmat & XE2+, allow large matmul warptile config for Intel
  4419. device->mul_mat_id_l[i] = true;
  4420. }
  4421. device->mul_mat_m[i] = true;
  4422. device->mul_mat_s[i] = true;
  4423. device->mul_mat_id_m[i] = true;
  4424. device->mul_mat_id_s[i] = true;
  4425. break;
  4426. case VK_VENDOR_ID_APPLE:
  4427. device->mul_mat_l[i] = false;
  4428. device->mul_mat_m[i] = true;
  4429. device->mul_mat_s[i] = false;
  4430. device->mul_mat_id_l[i] = false;
  4431. device->mul_mat_id_m[i] = true;
  4432. device->mul_mat_id_s[i] = false;
  4433. break;
  4434. #endif
  4435. default:
  4436. device->mul_mat_l[i] = true;
  4437. device->mul_mat_m[i] = true;
  4438. device->mul_mat_s[i] = true;
  4439. device->mul_mat_id_l[i] = true;
  4440. device->mul_mat_id_m[i] = true;
  4441. device->mul_mat_id_s[i] = true;
  4442. break;
  4443. }
  4444. }
  4445. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  4446. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  4447. for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
  4448. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  4449. dsl_binding_flags.push_back({});
  4450. }
  4451. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  4452. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  4453. {},
  4454. dsl_binding);
  4455. descriptor_set_layout_create_info.setPNext(&dslbfci);
  4456. device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  4457. ggml_vk_load_shaders(device);
  4458. if (!device->single_queue) {
  4459. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  4460. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  4461. } else {
  4462. // TODO: Use pointer or reference to avoid copy
  4463. device->transfer_queue.copyFrom(device->compute_queue);
  4464. device->transfer_queue.cmd_pool.init(device, &device->transfer_queue);
  4465. }
  4466. device->buffer_type = {
  4467. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  4468. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  4469. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  4470. };
  4471. device->fence = device->device.createFence({});
  4472. device->idx = idx;
  4473. device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr;
  4474. device->add_rms_fusion = !device->disable_fusion &&
  4475. device->subgroup_arithmetic &&
  4476. device->vendor_id != VK_VENDOR_ID_INTEL;
  4477. device->partials_binding_alignment =
  4478. std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment);
  4479. device->mmvq_mode = 0;
  4480. if (getenv("GGML_VK_DISABLE_MMVQ")) {
  4481. device->mmvq_mode = -1;
  4482. } else if (getenv("GGML_VK_FORCE_MMVQ")) {
  4483. device->mmvq_mode = 1;
  4484. }
  4485. return device;
  4486. }
  4487. return vk_instance.devices[idx];
  4488. }
  4489. static void ggml_vk_print_gpu_info(size_t idx) {
  4490. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4491. size_t dev_num = vk_instance.device_indices[idx];
  4492. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  4493. GGML_ASSERT(vk_instance_initialized);
  4494. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4495. if (dev_num >= devices.size()) {
  4496. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  4497. throw std::runtime_error("Device not found");
  4498. }
  4499. vk::PhysicalDevice physical_device = devices[dev_num];
  4500. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  4501. bool fp16_storage = false;
  4502. bool fp16_compute = false;
  4503. bool coopmat_support = false;
  4504. bool coopmat2_support = false;
  4505. bool integer_dot_product = false;
  4506. bool bfloat16_support = false;
  4507. for (auto properties : ext_props) {
  4508. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  4509. fp16_storage = true;
  4510. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  4511. fp16_compute = true;
  4512. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4513. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  4514. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  4515. coopmat_support = true;
  4516. #endif
  4517. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  4518. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  4519. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  4520. coopmat2_support = true;
  4521. #endif
  4522. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  4523. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  4524. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  4525. integer_dot_product = true;
  4526. #endif
  4527. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4528. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  4529. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4530. bfloat16_support = true;
  4531. #endif
  4532. }
  4533. }
  4534. const vk_device_architecture device_architecture = get_device_architecture(physical_device);
  4535. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  4536. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  4537. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  4538. vk::PhysicalDeviceProperties2 props2;
  4539. vk::PhysicalDeviceMaintenance3Properties props3;
  4540. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  4541. vk::PhysicalDeviceDriverProperties driver_props;
  4542. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  4543. props2.pNext = &props3;
  4544. props3.pNext = &subgroup_props;
  4545. subgroup_props.pNext = &driver_props;
  4546. // Pointer to the last chain element
  4547. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  4548. if (integer_dot_product) {
  4549. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4550. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4551. }
  4552. physical_device.getProperties2(&props2);
  4553. VkPhysicalDeviceFeatures2 device_features2;
  4554. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  4555. device_features2.pNext = nullptr;
  4556. VkPhysicalDeviceVulkan11Features vk11_features;
  4557. vk11_features.pNext = nullptr;
  4558. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  4559. device_features2.pNext = &vk11_features;
  4560. VkPhysicalDeviceVulkan12Features vk12_features;
  4561. vk12_features.pNext = nullptr;
  4562. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  4563. vk11_features.pNext = &vk12_features;
  4564. // Pointer to the last chain element
  4565. last_struct = (VkBaseOutStructure *)&vk12_features;
  4566. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4567. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  4568. coopmat_features.pNext = nullptr;
  4569. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  4570. coopmat_features.cooperativeMatrix = VK_FALSE;
  4571. if (coopmat_support) {
  4572. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  4573. last_struct = (VkBaseOutStructure *)&coopmat_features;
  4574. }
  4575. #endif
  4576. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  4577. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  4578. if (integer_dot_product) {
  4579. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4580. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4581. }
  4582. #if defined(VK_KHR_shader_bfloat16)
  4583. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  4584. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  4585. if (bfloat16_support) {
  4586. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  4587. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  4588. }
  4589. #endif
  4590. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  4591. fp16 = fp16 && vk12_features.shaderFloat16;
  4592. #if defined(VK_KHR_shader_bfloat16)
  4593. bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4594. #else
  4595. bool bf16 = false;
  4596. #endif
  4597. uint32_t default_subgroup_size = get_subgroup_size("", device_architecture);
  4598. const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize;
  4599. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  4600. integer_dot_product = integer_dot_product
  4601. && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated
  4602. && shader_integer_dot_product_features.shaderIntegerDotProduct;
  4603. coopmat_support = coopmat_support
  4604. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4605. && coopmat_features.cooperativeMatrix
  4606. #endif
  4607. && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture);
  4608. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  4609. std::string device_name = props2.properties.deviceName.data();
  4610. 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",
  4611. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, bf16, subgroup_size,
  4612. props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str());
  4613. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  4614. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  4615. }
  4616. }
  4617. static bool ggml_vk_instance_layer_settings_available();
  4618. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  4619. static bool ggml_vk_instance_debug_utils_ext_available(const std::vector<vk::ExtensionProperties> & instance_extensions);
  4620. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev);
  4621. static DispatchLoaderDynamic ggml_vk_default_dispatcher_instance;
  4622. DispatchLoaderDynamic & ggml_vk_default_dispatcher() {
  4623. return ggml_vk_default_dispatcher_instance;
  4624. }
  4625. static void ggml_vk_instance_init() {
  4626. if (vk_instance_initialized) {
  4627. return;
  4628. }
  4629. VK_LOG_DEBUG("ggml_vk_instance_init()");
  4630. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4631. ggml_vk_default_dispatcher_instance.init(vkGetInstanceProcAddr);
  4632. uint32_t api_version = vk::enumerateInstanceVersion();
  4633. if (api_version < VK_API_VERSION_1_2) {
  4634. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  4635. throw vk::SystemError(vk::Result::eErrorFeatureNotPresent, "Vulkan 1.2 required");
  4636. }
  4637. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  4638. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  4639. const bool layer_settings = ggml_vk_instance_layer_settings_available();
  4640. #ifdef __APPLE__
  4641. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  4642. #endif
  4643. const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr;
  4644. std::vector<const char*> layers;
  4645. if (layer_settings) {
  4646. layers.push_back("VK_LAYER_KHRONOS_validation");
  4647. }
  4648. std::vector<const char*> extensions;
  4649. if (layer_settings) {
  4650. extensions.push_back("VK_EXT_layer_settings");
  4651. }
  4652. #ifdef __APPLE__
  4653. if (portability_enumeration_ext) {
  4654. extensions.push_back("VK_KHR_portability_enumeration");
  4655. }
  4656. #endif
  4657. if (debug_utils_ext) {
  4658. extensions.push_back("VK_EXT_debug_utils");
  4659. }
  4660. VkBool32 enable_best_practice = layer_settings;
  4661. std::vector<vk::LayerSettingEXT> settings = {
  4662. {
  4663. "VK_LAYER_KHRONOS_validation",
  4664. "validate_best_practices",
  4665. vk::LayerSettingTypeEXT::eBool32,
  4666. 1,
  4667. &enable_best_practice
  4668. },
  4669. };
  4670. vk::LayerSettingsCreateInfoEXT layer_setting_info(settings);
  4671. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions, &layer_setting_info);
  4672. #ifdef __APPLE__
  4673. if (portability_enumeration_ext) {
  4674. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  4675. }
  4676. #endif
  4677. vk_instance.instance = vk::createInstance(instance_create_info);
  4678. vk_instance_initialized = true;
  4679. if (debug_utils_ext) {
  4680. vk_instance.debug_utils_support = true;
  4681. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT");
  4682. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT");
  4683. vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT");
  4684. vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT");
  4685. vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT");
  4686. vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT");
  4687. }
  4688. vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr;
  4689. vk_perf_logger_concurrent = getenv("GGML_VK_PERF_LOGGER_CONCURRENT") != nullptr;
  4690. vk_enable_sync_logger = getenv("GGML_VK_SYNC_LOGGER") != nullptr;
  4691. vk_memory_logger_enabled = getenv("GGML_VK_MEMORY_LOGGER") != nullptr;
  4692. const char* GGML_VK_PERF_LOGGER_FREQUENCY = getenv("GGML_VK_PERF_LOGGER_FREQUENCY");
  4693. if (GGML_VK_PERF_LOGGER_FREQUENCY != nullptr) {
  4694. vk_perf_logger_frequency = std::stoul(GGML_VK_PERF_LOGGER_FREQUENCY);
  4695. }
  4696. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4697. VULKAN_HPP_DEFAULT_DISPATCHER.init(vk_instance.instance);
  4698. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4699. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  4700. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  4701. if (devices_env != nullptr) {
  4702. size_t num_available_devices = devices.size();
  4703. std::string devices(devices_env);
  4704. std::replace(devices.begin(), devices.end(), ',', ' ');
  4705. std::stringstream ss(devices);
  4706. size_t tmp;
  4707. while (ss >> tmp) {
  4708. if(tmp >= num_available_devices) {
  4709. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  4710. throw std::runtime_error("Invalid Vulkan device index");
  4711. }
  4712. vk_instance.device_indices.push_back(tmp);
  4713. }
  4714. } else {
  4715. // If no vulkan devices are found, return early
  4716. if (devices.empty()) {
  4717. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4718. return;
  4719. }
  4720. // Default to using all dedicated GPUs
  4721. for (size_t i = 0; i < devices.size(); i++) {
  4722. vk::PhysicalDeviceProperties2 new_props;
  4723. vk::PhysicalDeviceDriverProperties new_driver;
  4724. vk::PhysicalDeviceIDProperties new_id;
  4725. new_props.pNext = &new_driver;
  4726. new_driver.pNext = &new_id;
  4727. devices[i].getProperties2(&new_props);
  4728. if ((new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu || new_props.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) && ggml_vk_device_is_supported(devices[i])) {
  4729. // Check if there are two physical devices corresponding to the same GPU
  4730. auto old_device = std::find_if(
  4731. vk_instance.device_indices.begin(),
  4732. vk_instance.device_indices.end(),
  4733. [&devices, &new_id](const size_t k){
  4734. vk::PhysicalDeviceProperties2 old_props;
  4735. vk::PhysicalDeviceIDProperties old_id;
  4736. old_props.pNext = &old_id;
  4737. devices[k].getProperties2(&old_props);
  4738. bool equals = std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  4739. equals = equals || (
  4740. old_id.deviceLUIDValid && new_id.deviceLUIDValid &&
  4741. std::equal(std::begin(old_id.deviceLUID), std::end(old_id.deviceLUID), std::begin(new_id.deviceLUID))
  4742. );
  4743. return equals;
  4744. }
  4745. );
  4746. if (old_device == vk_instance.device_indices.end()) {
  4747. vk_instance.device_indices.push_back(i);
  4748. } else {
  4749. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  4750. // This can cause error when splitting layers aross the devices, need to keep only 1
  4751. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  4752. vk::PhysicalDeviceProperties2 old_props;
  4753. vk::PhysicalDeviceDriverProperties old_driver;
  4754. old_props.pNext = &old_driver;
  4755. devices[*old_device].getProperties2(&old_props);
  4756. std::map<vk::DriverId, int> driver_priorities {};
  4757. int old_priority = std::numeric_limits<int>::max();
  4758. int new_priority = std::numeric_limits<int>::max();
  4759. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  4760. // Smaller number -> higher priority
  4761. switch (old_props.properties.vendorID) {
  4762. case VK_VENDOR_ID_AMD:
  4763. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  4764. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  4765. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  4766. break;
  4767. case VK_VENDOR_ID_INTEL:
  4768. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  4769. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  4770. break;
  4771. case VK_VENDOR_ID_NVIDIA:
  4772. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  4773. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  4774. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  4775. #endif
  4776. break;
  4777. }
  4778. driver_priorities[vk::DriverId::eMesaDozen] = 100;
  4779. if (driver_priorities.count(old_driver.driverID)) {
  4780. old_priority = driver_priorities[old_driver.driverID];
  4781. }
  4782. if (driver_priorities.count(new_driver.driverID)) {
  4783. new_priority = driver_priorities[new_driver.driverID];
  4784. }
  4785. if (new_priority < old_priority) {
  4786. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  4787. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  4788. vk_instance.device_indices.push_back(i);
  4789. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  4790. }
  4791. else {
  4792. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  4793. }
  4794. }
  4795. }
  4796. }
  4797. // If no GPUs found, fall back to the first non-CPU device.
  4798. // If only CPU devices are available, return without devices.
  4799. if (vk_instance.device_indices.empty()) {
  4800. for (size_t i = 0; i < devices.size(); i++) {
  4801. if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) {
  4802. vk_instance.device_indices.push_back(i);
  4803. break;
  4804. }
  4805. }
  4806. }
  4807. if (vk_instance.device_indices.empty()) {
  4808. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4809. return;
  4810. }
  4811. }
  4812. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  4813. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  4814. vk::PhysicalDevice vkdev = devices[vk_instance.device_indices[i]];
  4815. std::vector<vk::ExtensionProperties> extensionprops = vkdev.enumerateDeviceExtensionProperties();
  4816. bool membudget_supported = false;
  4817. for (const auto & ext : extensionprops) {
  4818. if (strcmp(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, ext.extensionName) == 0) {
  4819. membudget_supported = true;
  4820. break;
  4821. }
  4822. }
  4823. vk_instance.device_supports_membudget.push_back(membudget_supported);
  4824. ggml_vk_print_gpu_info(i);
  4825. }
  4826. }
  4827. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  4828. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  4829. ggml_vk_instance_init();
  4830. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4831. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4832. ctx->device = ggml_vk_get_device(idx);
  4833. ctx->semaphore_idx = 0;
  4834. ctx->event_idx = 0;
  4835. ctx->prealloc_size_x = 0;
  4836. ctx->prealloc_size_y = 0;
  4837. ctx->prealloc_size_split_k = 0;
  4838. // Fixed size of 1KB, for deterministic behavior
  4839. ctx->prealloc_size_add_rms_partials = 1024;
  4840. ctx->fence = ctx->device->device.createFence({});
  4841. ctx->almost_ready_fence = ctx->device->device.createFence({});
  4842. ctx->compute_cmd_pool.init(ctx->device, &ctx->device->compute_queue);
  4843. ctx->transfer_cmd_pool.init(ctx->device, &ctx->device->transfer_queue);
  4844. if (vk_perf_logger_enabled) {
  4845. ctx->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  4846. }
  4847. #ifdef GGML_VULKAN_CHECK_RESULTS
  4848. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  4849. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  4850. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  4851. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  4852. #endif
  4853. }
  4854. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  4855. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  4856. switch (type) {
  4857. case GGML_TYPE_F32:
  4858. case GGML_TYPE_Q4_0:
  4859. case GGML_TYPE_Q4_1:
  4860. case GGML_TYPE_Q5_0:
  4861. case GGML_TYPE_Q5_1:
  4862. case GGML_TYPE_Q8_0:
  4863. case GGML_TYPE_Q2_K:
  4864. case GGML_TYPE_Q3_K:
  4865. case GGML_TYPE_Q4_K:
  4866. case GGML_TYPE_Q5_K:
  4867. case GGML_TYPE_Q6_K:
  4868. case GGML_TYPE_IQ1_S:
  4869. case GGML_TYPE_IQ1_M:
  4870. case GGML_TYPE_IQ2_XXS:
  4871. case GGML_TYPE_IQ2_XS:
  4872. case GGML_TYPE_IQ2_S:
  4873. case GGML_TYPE_IQ3_XXS:
  4874. case GGML_TYPE_IQ3_S:
  4875. case GGML_TYPE_IQ4_XS:
  4876. case GGML_TYPE_IQ4_NL:
  4877. case GGML_TYPE_MXFP4:
  4878. break;
  4879. default:
  4880. return nullptr;
  4881. }
  4882. return ctx->device->pipeline_dequant[type];
  4883. }
  4884. 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) {
  4885. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ", " << prec << ")");
  4886. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4887. return ctx->device->pipeline_matmul_f32;
  4888. }
  4889. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4890. return ctx->device->pipeline_matmul_f32_f16;
  4891. }
  4892. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4893. return ctx->device->pipeline_matmul_bf16;
  4894. }
  4895. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4896. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4897. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  4898. }
  4899. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4900. return ctx->device->pipeline_matmul_f16.f16acc;
  4901. }
  4902. } else {
  4903. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4904. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  4905. }
  4906. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4907. return ctx->device->pipeline_matmul_f16.f32acc;
  4908. }
  4909. }
  4910. // MMQ
  4911. if (src1_type == GGML_TYPE_Q8_1) {
  4912. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1[src0_type].f32acc;
  4913. if (pipelines->is_empty()) {
  4914. return nullptr;
  4915. }
  4916. return pipelines;
  4917. }
  4918. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  4919. return nullptr;
  4920. }
  4921. switch (src0_type) {
  4922. case GGML_TYPE_Q4_0:
  4923. case GGML_TYPE_Q4_1:
  4924. case GGML_TYPE_Q5_0:
  4925. case GGML_TYPE_Q5_1:
  4926. case GGML_TYPE_Q8_0:
  4927. case GGML_TYPE_Q2_K:
  4928. case GGML_TYPE_Q3_K:
  4929. case GGML_TYPE_Q4_K:
  4930. case GGML_TYPE_Q5_K:
  4931. case GGML_TYPE_Q6_K:
  4932. case GGML_TYPE_IQ1_S:
  4933. case GGML_TYPE_IQ1_M:
  4934. case GGML_TYPE_IQ2_XXS:
  4935. case GGML_TYPE_IQ2_XS:
  4936. case GGML_TYPE_IQ2_S:
  4937. case GGML_TYPE_IQ3_XXS:
  4938. case GGML_TYPE_IQ3_S:
  4939. case GGML_TYPE_IQ4_XS:
  4940. case GGML_TYPE_IQ4_NL:
  4941. case GGML_TYPE_MXFP4:
  4942. break;
  4943. default:
  4944. return nullptr;
  4945. }
  4946. if (ctx->device->coopmat2) {
  4947. assert(src1_type == GGML_TYPE_F16);
  4948. 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;
  4949. }
  4950. if (ctx->device->coopmat_support) {
  4951. 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;
  4952. }
  4953. 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;
  4954. }
  4955. 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) {
  4956. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  4957. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1);
  4958. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  4959. if (b_type == GGML_TYPE_Q8_1) {
  4960. switch (a_type) {
  4961. case GGML_TYPE_Q4_0:
  4962. case GGML_TYPE_Q4_1:
  4963. case GGML_TYPE_Q5_0:
  4964. case GGML_TYPE_Q5_1:
  4965. case GGML_TYPE_Q8_0:
  4966. case GGML_TYPE_MXFP4:
  4967. case GGML_TYPE_Q2_K:
  4968. case GGML_TYPE_Q3_K:
  4969. case GGML_TYPE_Q4_K:
  4970. case GGML_TYPE_Q5_K:
  4971. case GGML_TYPE_Q6_K:
  4972. case GGML_TYPE_IQ1_S:
  4973. case GGML_TYPE_IQ1_M:
  4974. break;
  4975. default:
  4976. return nullptr;
  4977. }
  4978. }
  4979. switch (a_type) {
  4980. case GGML_TYPE_F32:
  4981. case GGML_TYPE_F16:
  4982. case GGML_TYPE_BF16:
  4983. case GGML_TYPE_Q4_0:
  4984. case GGML_TYPE_Q4_1:
  4985. case GGML_TYPE_Q5_0:
  4986. case GGML_TYPE_Q5_1:
  4987. case GGML_TYPE_Q8_0:
  4988. case GGML_TYPE_Q2_K:
  4989. case GGML_TYPE_Q3_K:
  4990. case GGML_TYPE_Q4_K:
  4991. case GGML_TYPE_Q5_K:
  4992. case GGML_TYPE_Q6_K:
  4993. case GGML_TYPE_IQ1_S:
  4994. case GGML_TYPE_IQ1_M:
  4995. case GGML_TYPE_IQ2_XXS:
  4996. case GGML_TYPE_IQ2_XS:
  4997. case GGML_TYPE_IQ2_S:
  4998. case GGML_TYPE_IQ3_XXS:
  4999. case GGML_TYPE_IQ3_S:
  5000. case GGML_TYPE_IQ4_XS:
  5001. case GGML_TYPE_IQ4_NL:
  5002. case GGML_TYPE_MXFP4:
  5003. break;
  5004. default:
  5005. return nullptr;
  5006. }
  5007. // heuristic to choose workgroup size
  5008. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  5009. 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) {
  5010. // Prefer larger workgroups when M is small, to spread the work out more
  5011. // and keep more SMs busy.
  5012. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  5013. if (a_type == GGML_TYPE_Q6_K) {
  5014. if (m < 4096 && k >= 1024) {
  5015. dmmv_wg = DMMV_WG_SIZE_LARGE;
  5016. }
  5017. } else {
  5018. if (m <= 8192 && k >= 1024) {
  5019. dmmv_wg = DMMV_WG_SIZE_LARGE;
  5020. }
  5021. }
  5022. }
  5023. if (b_type == GGML_TYPE_Q8_1) {
  5024. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  5025. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  5026. }
  5027. return ctx->device->pipeline_dequant_mul_mat_vec_q8_1_f32[dmmv_wg][a_type][num_cols-1];
  5028. }
  5029. 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];
  5030. }
  5031. 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) {
  5032. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  5033. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  5034. return ctx->device->pipeline_matmul_id_f32;
  5035. }
  5036. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  5037. return ctx->device->pipeline_matmul_id_bf16;
  5038. }
  5039. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  5040. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  5041. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  5042. }
  5043. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  5044. return ctx->device->pipeline_matmul_id_f16.f16acc;
  5045. }
  5046. } else {
  5047. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  5048. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  5049. }
  5050. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  5051. return ctx->device->pipeline_matmul_id_f16.f32acc;
  5052. }
  5053. }
  5054. // MMQ
  5055. if (src1_type == GGML_TYPE_Q8_1) {
  5056. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_id_q8_1[src0_type].f32acc;
  5057. if (pipelines->is_empty()) {
  5058. return nullptr;
  5059. }
  5060. return pipelines;
  5061. }
  5062. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  5063. switch (src0_type) {
  5064. case GGML_TYPE_Q4_0:
  5065. case GGML_TYPE_Q4_1:
  5066. case GGML_TYPE_Q5_0:
  5067. case GGML_TYPE_Q5_1:
  5068. case GGML_TYPE_Q8_0:
  5069. case GGML_TYPE_Q2_K:
  5070. case GGML_TYPE_Q3_K:
  5071. case GGML_TYPE_Q4_K:
  5072. case GGML_TYPE_Q5_K:
  5073. case GGML_TYPE_Q6_K:
  5074. case GGML_TYPE_IQ1_S:
  5075. case GGML_TYPE_IQ1_M:
  5076. case GGML_TYPE_IQ2_XXS:
  5077. case GGML_TYPE_IQ2_XS:
  5078. case GGML_TYPE_IQ2_S:
  5079. case GGML_TYPE_IQ3_XXS:
  5080. case GGML_TYPE_IQ3_S:
  5081. case GGML_TYPE_IQ4_XS:
  5082. case GGML_TYPE_IQ4_NL:
  5083. case GGML_TYPE_MXFP4:
  5084. break;
  5085. default:
  5086. return nullptr;
  5087. }
  5088. vk_matmul_pipeline2& mmp = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type];
  5089. // XXX TODO 'prec' is not actually allowed in mul_mat_id.
  5090. bool prefer_fp16acc = ctx->device->fp16 /*&& prec == GGML_PREC_DEFAULT*/;
  5091. bool support_fp16acc = !mmp.f16acc->is_empty();
  5092. bool support_fp32acc = !mmp.f32acc->is_empty();
  5093. if (support_fp16acc && (prefer_fp16acc || !support_fp32acc)) {
  5094. return mmp.f16acc;
  5095. } else {
  5096. GGML_ASSERT(support_fp32acc);
  5097. return mmp.f32acc;
  5098. }
  5099. }
  5100. 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) {
  5101. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()");
  5102. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_Q8_1);
  5103. if (b_type == GGML_TYPE_Q8_1) {
  5104. switch (a_type) {
  5105. case GGML_TYPE_Q4_0:
  5106. case GGML_TYPE_Q4_1:
  5107. case GGML_TYPE_Q5_0:
  5108. case GGML_TYPE_Q5_1:
  5109. case GGML_TYPE_Q8_0:
  5110. case GGML_TYPE_MXFP4:
  5111. case GGML_TYPE_Q2_K:
  5112. case GGML_TYPE_Q3_K:
  5113. case GGML_TYPE_Q4_K:
  5114. case GGML_TYPE_Q5_K:
  5115. case GGML_TYPE_Q6_K:
  5116. case GGML_TYPE_IQ1_S:
  5117. case GGML_TYPE_IQ1_M:
  5118. break;
  5119. default:
  5120. return nullptr;
  5121. }
  5122. }
  5123. switch (a_type) {
  5124. case GGML_TYPE_F32:
  5125. case GGML_TYPE_F16:
  5126. case GGML_TYPE_BF16:
  5127. case GGML_TYPE_Q4_0:
  5128. case GGML_TYPE_Q4_1:
  5129. case GGML_TYPE_Q5_0:
  5130. case GGML_TYPE_Q5_1:
  5131. case GGML_TYPE_Q8_0:
  5132. case GGML_TYPE_Q2_K:
  5133. case GGML_TYPE_Q3_K:
  5134. case GGML_TYPE_Q4_K:
  5135. case GGML_TYPE_Q5_K:
  5136. case GGML_TYPE_Q6_K:
  5137. case GGML_TYPE_IQ1_S:
  5138. case GGML_TYPE_IQ1_M:
  5139. case GGML_TYPE_IQ2_XXS:
  5140. case GGML_TYPE_IQ2_XS:
  5141. case GGML_TYPE_IQ2_S:
  5142. case GGML_TYPE_IQ3_XXS:
  5143. case GGML_TYPE_IQ3_S:
  5144. case GGML_TYPE_IQ4_XS:
  5145. case GGML_TYPE_IQ4_NL:
  5146. case GGML_TYPE_MXFP4:
  5147. break;
  5148. default:
  5149. return nullptr;
  5150. }
  5151. // heuristic to choose workgroup size
  5152. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  5153. 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) {
  5154. // Prefer larger workgroups when M is small, to spread the work out more
  5155. // and keep more SMs busy.
  5156. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  5157. if (a_type == GGML_TYPE_Q6_K) {
  5158. if (m < 4096 && k >= 1024) {
  5159. dmmv_wg = DMMV_WG_SIZE_LARGE;
  5160. }
  5161. } else {
  5162. if (m <= 8192 && k >= 1024) {
  5163. dmmv_wg = DMMV_WG_SIZE_LARGE;
  5164. }
  5165. }
  5166. }
  5167. if (b_type == GGML_TYPE_Q8_1) {
  5168. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  5169. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  5170. }
  5171. return ctx->device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[dmmv_wg][a_type];
  5172. }
  5173. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[dmmv_wg][a_type];
  5174. }
  5175. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  5176. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  5177. vk_buffer buf = ggml_vk_create_buffer(device, size,
  5178. {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  5179. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  5180. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  5181. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  5182. size/1024.0/1024.0);
  5183. device->device.freeMemory(buf->device_memory);
  5184. device->device.destroyBuffer(buf->buffer);
  5185. return nullptr;
  5186. }
  5187. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  5188. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  5189. return buf->ptr;
  5190. }
  5191. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  5192. if (ptr == nullptr) {
  5193. return;
  5194. }
  5195. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  5196. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  5197. vk_buffer buf;
  5198. size_t index;
  5199. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  5200. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  5201. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  5202. if (ptr >= addr && ptr < endr) {
  5203. buf = std::get<2>(device->pinned_memory[i]);
  5204. index = i;
  5205. break;
  5206. }
  5207. }
  5208. if (buf == nullptr) {
  5209. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  5210. return;
  5211. }
  5212. ggml_vk_destroy_buffer(buf);
  5213. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  5214. }
  5215. static void ggml_vk_host_get(const vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  5216. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  5217. buf = nullptr;
  5218. buf_offset = 0;
  5219. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  5220. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  5221. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  5222. if (ptr >= addr && ptr < endr) {
  5223. buf = std::get<2>(device->pinned_memory[i]);
  5224. buf_offset = ((const uint8_t *)ptr) - addr;
  5225. break;
  5226. }
  5227. }
  5228. }
  5229. static vk_subbuffer ggml_vk_tensor_subbuffer(
  5230. const ggml_backend_vk_context * ctx, const ggml_tensor * tensor, bool allow_misalign = false) {
  5231. vk_buffer buffer = nullptr;
  5232. size_t offset = 0;
  5233. if (ctx->device->uma) {
  5234. ggml_vk_host_get(ctx->device, tensor->data, buffer, offset);
  5235. }
  5236. if (!buffer) {
  5237. auto buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  5238. buffer = buf_ctx->dev_buffer;
  5239. offset = vk_tensor_offset(tensor) + tensor->view_offs;
  5240. }
  5241. GGML_ASSERT(buffer != nullptr);
  5242. size_t size = ggml_nbytes(tensor);
  5243. size_t misalign_bytes = offset & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  5244. // The shader must support misaligned offsets when indexing into the buffer
  5245. GGML_ASSERT(allow_misalign || misalign_bytes == 0);
  5246. offset &= ~misalign_bytes;
  5247. size += misalign_bytes;
  5248. return vk_subbuffer{buffer, offset, size};
  5249. }
  5250. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) {
  5251. vk_submission s;
  5252. s.buffer = ggml_vk_create_cmd_buffer(device, p);
  5253. if (one_time) {
  5254. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  5255. } else {
  5256. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  5257. }
  5258. return s;
  5259. }
  5260. template <typename T> size_t push_constant_size(const T &t) {
  5261. static_assert(std::is_class<T>::value, "T must be a struct/class");
  5262. GGML_UNUSED(t);
  5263. return sizeof(T);
  5264. }
  5265. template <typename T> size_t push_constant_size(const std::vector<T> &t) {
  5266. GGML_UNUSED(t);
  5267. return sizeof(T) * t.size();
  5268. }
  5269. template <typename T, uint32_t N> size_t push_constant_size(const std::array<T, N> &t) {
  5270. GGML_UNUSED(t);
  5271. return sizeof(T) * N;
  5272. }
  5273. template <typename T> const T *push_constant_data(const T &t) {
  5274. static_assert(std::is_class<T>::value, "T must be a struct/class");
  5275. return &t;
  5276. }
  5277. template <typename T> const T *push_constant_data(const std::vector<T> &t) {
  5278. return t.data();
  5279. }
  5280. template <typename T, uint32_t N> const T *push_constant_data(const std::array<T, N> &t) {
  5281. return t.data();
  5282. }
  5283. template <typename T>
  5284. 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) {
  5285. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  5286. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  5287. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  5288. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  5289. for (auto& buffer : descriptor_buffer_infos) {
  5290. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  5291. }
  5292. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  5293. GGML_ASSERT(wg0 <= ctx->device->properties.limits.maxComputeWorkGroupCount[0] &&
  5294. wg1 <= ctx->device->properties.limits.maxComputeWorkGroupCount[1] &&
  5295. wg2 <= ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  5296. GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size());
  5297. GGML_ASSERT(descriptor_buffer_infos.size() <= MAX_PARAMETER_COUNT);
  5298. GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size());
  5299. GGML_ASSERT(pipeline->push_constant_size == push_constant_size(push_constants));
  5300. vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[ctx->descriptor_set_idx++];
  5301. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  5302. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  5303. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size(push_constants), push_constant_data(push_constants));
  5304. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  5305. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  5306. pipeline->layout,
  5307. 0,
  5308. { descriptor_set },
  5309. {});
  5310. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  5311. }
  5312. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  5313. s.buffer.end();
  5314. s.wait_semaphores = std::move(wait_semaphores);
  5315. s.signal_semaphores = std::move(signal_semaphores);
  5316. }
  5317. static void ggml_vk_ctx_end(vk_context& ctx) {
  5318. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  5319. if (ctx->s == nullptr) {
  5320. return;
  5321. }
  5322. ctx->s->buffer.end();
  5323. ctx->s = nullptr;
  5324. }
  5325. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  5326. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  5327. if (subctx->s != nullptr) {
  5328. ggml_vk_ctx_end(subctx);
  5329. }
  5330. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) });
  5331. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  5332. }
  5333. static size_t ggml_vk_align_size(size_t width, size_t align) {
  5334. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  5335. return CEIL_DIV(width, align) * align;
  5336. }
  5337. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  5338. if (memcpys == nullptr) {
  5339. memcpy(dst, src, size);
  5340. } else {
  5341. memcpys->emplace_back(dst, src, size);
  5342. }
  5343. }
  5344. static void deferred_memset(void * dst, uint32_t val, size_t size, std::vector<vk_staging_memset>* memsets = nullptr) {
  5345. if (memsets == nullptr) {
  5346. memset(dst, val, size);
  5347. } else {
  5348. memsets->emplace_back(dst, val, size);
  5349. }
  5350. }
  5351. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  5352. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  5353. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  5354. ggml_vk_destroy_buffer(device->sync_staging);
  5355. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  5356. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  5357. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  5358. }
  5359. }
  5360. static void ggml_vk_ensure_sync_staging_buffer(ggml_backend_vk_context * ctx, size_t size) {
  5361. if (ctx->sync_staging == nullptr || ctx->sync_staging->size < size) {
  5362. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  5363. ggml_vk_destroy_buffer(ctx->sync_staging);
  5364. ctx->sync_staging = ggml_vk_create_buffer_check(ctx->device, size,
  5365. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  5366. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  5367. }
  5368. }
  5369. 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) {
  5370. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  5371. GGML_ASSERT(!ggml_is_contiguous(tensor));
  5372. // Buffer is already mapped
  5373. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5374. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  5375. GGML_ABORT("fatal error");
  5376. }
  5377. // Check if src is pinned memory
  5378. vk_buffer buf = nullptr;
  5379. size_t buf_offset = 0;
  5380. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  5381. const uint64_t ne0 = tensor->ne[0];
  5382. const uint64_t ne1 = tensor->ne[1];
  5383. const uint64_t ne2 = tensor->ne[2];
  5384. const uint64_t ne3 = tensor->ne[3];
  5385. const uint64_t nb0 = tensor->nb[0];
  5386. const uint64_t nb1 = tensor->nb[1];
  5387. const uint64_t nb2 = tensor->nb[2];
  5388. const uint64_t nb3 = tensor->nb[3];
  5389. const ggml_type type = tensor->type;
  5390. const uint64_t ts = ggml_type_size(type);
  5391. const uint64_t bs = ggml_blck_size(type);
  5392. const uint64_t dstnb0 = ts;
  5393. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  5394. const uint64_t dstnb2 = dstnb1*ne1;
  5395. const uint64_t dstnb3 = dstnb2*ne2;
  5396. const uint64_t ne = ggml_nelements(tensor);
  5397. if (buf != nullptr) {
  5398. // Memory is pinned, use as staging buffer
  5399. std::vector<vk::BufferCopy> slices;
  5400. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  5401. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  5402. // Find longest contiguous slice
  5403. if (ne1*nb1 == dstnb2) {
  5404. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  5405. } else {
  5406. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  5407. if (ne0*nb0/bs == dstnb1) {
  5408. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  5409. } else {
  5410. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  5411. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  5412. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  5413. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  5414. }
  5415. }
  5416. }
  5417. }
  5418. }
  5419. }
  5420. ggml_vk_sync_buffers(ctx, subctx);
  5421. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  5422. return;
  5423. }
  5424. if (!sync_staging) {
  5425. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  5426. }
  5427. // Staging buffer required
  5428. vk_buffer& staging = ctx->device->sync_staging;
  5429. const uint64_t copy_size = ts*ne/bs;
  5430. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  5431. VkBufferCopy buf_copy{ 0, offset, copy_size };
  5432. ggml_vk_sync_buffers(ctx, subctx);
  5433. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  5434. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  5435. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  5436. // Find longest contiguous slice
  5437. if (ne1*nb1 == dstnb2) {
  5438. 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);
  5439. } else {
  5440. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  5441. if (ne0*nb0/bs == dstnb1) {
  5442. 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);
  5443. } else {
  5444. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  5445. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  5446. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  5447. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  5448. }
  5449. }
  5450. }
  5451. }
  5452. }
  5453. }
  5454. }
  5455. 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) {
  5456. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  5457. // Check if src is pinned memory
  5458. vk_buffer buf = nullptr;
  5459. size_t buf_offset = 0;
  5460. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  5461. if (buf != nullptr) {
  5462. // Memory is pinned, use as staging buffer
  5463. std::vector<vk::BufferCopy> slices(1);
  5464. if (width == spitch) {
  5465. // Only do single write if stride is equal
  5466. slices[0].srcOffset = buf_offset;
  5467. slices[0].dstOffset = offset;
  5468. slices[0].size = width * height;
  5469. } else {
  5470. slices.resize(height);
  5471. for (size_t i = 0; i < height; i++) {
  5472. slices[i].srcOffset = buf_offset + i * spitch;
  5473. slices[i].dstOffset = offset + i * width;
  5474. slices[i].size = width;
  5475. }
  5476. }
  5477. ggml_vk_sync_buffers(nullptr, subctx);
  5478. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  5479. return true;
  5480. }
  5481. VK_LOG_DEBUG("STAGING");
  5482. if (!sync_staging) {
  5483. // copy was not handled caller needs to fall back
  5484. return false;
  5485. }
  5486. // Staging buffer required
  5487. const size_t copy_size = width*height;
  5488. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  5489. vk_buffer& staging_buffer = dst->device->sync_staging;
  5490. VkBufferCopy buf_copy = {
  5491. 0,
  5492. offset,
  5493. copy_size};
  5494. ggml_vk_sync_buffers(nullptr, subctx);
  5495. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  5496. if (width == spitch) {
  5497. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  5498. } else {
  5499. for (size_t i = 0; i < height; i++) {
  5500. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  5501. }
  5502. }
  5503. return true;
  5504. }
  5505. 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) {
  5506. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  5507. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  5508. }
  5509. 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) {
  5510. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  5511. // Buffer is already mapped
  5512. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5513. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5514. for (size_t i = 0; i < height; i++) {
  5515. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  5516. }
  5517. } else {
  5518. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5519. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5520. ggml_vk_ctx_begin(dst->device, subctx);
  5521. bool ret = ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  5522. GGML_ASSERT(ret);
  5523. ggml_vk_ctx_end(subctx);
  5524. for (auto& cpy : subctx->in_memcpys) {
  5525. memcpy(cpy.dst, cpy.src, cpy.n);
  5526. }
  5527. for (auto& mset : subctx->memsets) {
  5528. memset(mset.dst, mset.val, mset.n);
  5529. }
  5530. ggml_vk_submit(subctx, dst->device->fence);
  5531. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  5532. dst->device->device.resetFences({ dst->device->fence });
  5533. ggml_vk_queue_command_pools_cleanup(dst->device);
  5534. }
  5535. }
  5536. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  5537. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  5538. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  5539. }
  5540. 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) {
  5541. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  5542. GGML_ASSERT(width > 0);
  5543. GGML_ASSERT(height > 0);
  5544. GGML_ASSERT(src != nullptr);
  5545. // TODO: staging_offset is not used
  5546. // Check if dst is pinned memory
  5547. vk_buffer buf = nullptr;
  5548. size_t buf_offset = 0;
  5549. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  5550. std::vector<vk::BufferCopy> slices(1);
  5551. if (width == spitch && width == dpitch) {
  5552. // Only do single write if stride is equal
  5553. slices[0].srcOffset = offset;
  5554. slices[0].dstOffset = buf_offset;
  5555. slices[0].size = width * height;
  5556. } else {
  5557. slices.resize(height);
  5558. for (size_t i = 0; i < height; i++) {
  5559. slices[i].srcOffset = offset + i * spitch;
  5560. slices[i].dstOffset = buf_offset + i * dpitch;
  5561. slices[i].size = width;
  5562. }
  5563. }
  5564. if (buf != nullptr) {
  5565. // Memory is pinned, use as staging buffer
  5566. ggml_vk_sync_buffers(nullptr, subctx);
  5567. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  5568. return true;
  5569. }
  5570. VK_LOG_DEBUG("STAGING");
  5571. if (!sync_staging) {
  5572. // copy was not handled caller needs to fall back
  5573. return false;
  5574. }
  5575. // Fall back to staging buffer
  5576. const size_t copy_size = dpitch * height;
  5577. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  5578. vk_buffer& staging_buffer = src->device->sync_staging;
  5579. ggml_vk_sync_buffers(nullptr, subctx);
  5580. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  5581. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  5582. return true;
  5583. }
  5584. 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) {
  5585. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  5586. }
  5587. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  5588. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  5589. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  5590. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  5591. // the HW device to host copy path.
  5592. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  5593. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5594. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  5595. } else {
  5596. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5597. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5598. ggml_vk_ctx_begin(src->device, subctx);
  5599. bool ret = ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  5600. GGML_ASSERT(ret);
  5601. ggml_vk_ctx_end(subctx);
  5602. ggml_vk_submit(subctx, src->device->fence);
  5603. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  5604. src->device->device.resetFences({ src->device->fence });
  5605. ggml_vk_queue_command_pools_cleanup(src->device);
  5606. for (auto& cpy : subctx->out_memcpys) {
  5607. memcpy(cpy.dst, cpy.src, cpy.n);
  5608. }
  5609. }
  5610. }
  5611. 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) {
  5612. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  5613. // Make sure both buffers are on same device
  5614. GGML_ASSERT(src->device == dst->device);
  5615. VkBufferCopy bc{ src_offset, dst_offset, size };
  5616. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  5617. }
  5618. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  5619. if (src->device == dst->device) {
  5620. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5621. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  5622. // Copy within the device
  5623. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5624. ggml_vk_ctx_begin(src->device, subctx);
  5625. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  5626. ggml_vk_ctx_end(subctx);
  5627. ggml_vk_submit(subctx, src->device->fence);
  5628. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  5629. src->device->device.resetFences({ src->device->fence });
  5630. ggml_vk_queue_command_pools_cleanup(src->device);
  5631. } else {
  5632. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  5633. // Copy device to device
  5634. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  5635. // Copy to src staging buffer
  5636. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  5637. // Copy to dst buffer
  5638. ggml_vk_buffer_write_2d(dst, dst_offset, src->device->sync_staging->ptr, 0, size, 1);
  5639. }
  5640. }
  5641. static void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5642. VK_LOG_DEBUG("ggml_vk_buffer_memset_async(" << offset << ", " << c << ", " << size << ")");
  5643. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5644. dst->device->uma) {
  5645. deferred_memset((uint8_t*)dst->ptr + offset, c, size, &ctx->memsets);
  5646. return;
  5647. }
  5648. // Fall back to GPU fillBuffer for non-UMA or non-host-visible buffers
  5649. ctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5650. }
  5651. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5652. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  5653. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5654. dst->device->uma) {
  5655. memset((uint8_t*)dst->ptr + offset, c, size);
  5656. return;
  5657. }
  5658. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5659. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5660. ggml_vk_ctx_begin(dst->device, subctx);
  5661. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5662. ggml_vk_ctx_end(subctx);
  5663. ggml_vk_submit(subctx, dst->device->fence);
  5664. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  5665. dst->device->device.resetFences({ dst->device->fence });
  5666. ggml_vk_queue_command_pools_cleanup(dst->device);
  5667. }
  5668. 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) {
  5669. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ", " << disable_split_k << ")");
  5670. if (disable_split_k) {
  5671. return 1;
  5672. }
  5673. uint32_t split_k = 1;
  5674. if (ctx->device->shader_core_count != 0 && m >= pipeline->wg_denoms[0] && n >= pipeline->wg_denoms[1]) {
  5675. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  5676. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  5677. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  5678. if (k >= 2048) {
  5679. if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) {
  5680. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  5681. } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) {
  5682. split_k = 3;
  5683. }
  5684. // Cap the split at 8x. Unless k is huge this is a lot of overhead.
  5685. split_k = std::min(split_k, 8u);
  5686. // ggml_vk_matmul will align the splits to be a multiple of 256.
  5687. // If this rounded up size would cause the last split to be empty,
  5688. // then reduce the split count.
  5689. while (true) {
  5690. if (split_k == 1) {
  5691. break;
  5692. }
  5693. uint32_t k_split = CEIL_DIV(k, split_k);
  5694. k_split = ROUNDUP_POW2(k_split, 256);
  5695. if (k_split * (split_k - 1) < k) {
  5696. break;
  5697. }
  5698. split_k--;
  5699. }
  5700. }
  5701. }
  5702. return split_k;
  5703. }
  5704. 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) {
  5705. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5706. if (ctx->device->coopmat2) {
  5707. const uint32_t shader_core_count = ctx->device->shader_core_count;
  5708. const uint32_t tiles_l = CEIL_DIV(m, mmp->a_l->wg_denoms[0]) * CEIL_DIV(n, mmp->a_l->wg_denoms[1]);
  5709. const uint32_t tiles_m = CEIL_DIV(m, mmp->a_m->wg_denoms[0]) * CEIL_DIV(n, mmp->a_m->wg_denoms[1]);
  5710. // Use large shader when the N dimension is greater than the medium shader's tile size
  5711. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5712. // Prefer large over medium if either:
  5713. // - medium or large tiles would overfill the GPU
  5714. // - large tiles with a split_k==3 fits in the GPU and medium tiles with split_k==2 does not
  5715. // (medium with split_k==2 is probably better if it fits - more workgroups running and less split_k overhead)
  5716. bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count ||
  5717. // split_k==3 with large tiles likely better than medium tiles with no split_k.
  5718. (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2);
  5719. 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])) {
  5720. return aligned ? mmp->a_l : mmp->l;
  5721. }
  5722. // Use medium shader when the N dimension is greater than the small shader's tile size
  5723. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5724. if ((ctx->device->mul_mat_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_s[src0_type]) {
  5725. return aligned ? mmp->a_m : mmp->m;
  5726. }
  5727. return aligned ? mmp->a_s : mmp->s;
  5728. }
  5729. 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])) {
  5730. return aligned ? mmp->a_s : mmp->s;
  5731. }
  5732. if ((ctx->device->mul_mat_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l[src0_type]) {
  5733. return aligned ? mmp->a_m : mmp->m;
  5734. }
  5735. return aligned ? mmp->a_l : mmp->l;
  5736. GGML_UNUSED(src1_type);
  5737. }
  5738. 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) {
  5739. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5740. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, src0_type, src1_type)->align;
  5741. }
  5742. static void ggml_vk_matmul(
  5743. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5744. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  5745. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5746. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5747. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3,
  5748. uint32_t padded_n) {
  5749. 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 << ")");
  5750. if (split_k == 1) {
  5751. 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 };
  5752. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc, { m, n, batch });
  5753. return;
  5754. }
  5755. if (ctx->prealloc_split_k_need_sync) {
  5756. ggml_vk_sync_buffers(ctx, subctx);
  5757. }
  5758. GGML_ASSERT(batch_stride_d == m * n);
  5759. // Round the split size up to a multiple of 256 (k-quant alignment)
  5760. uint32_t k_split = CEIL_DIV(k, split_k);
  5761. k_split = ROUNDUP_POW2(k_split, 256);
  5762. 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 };
  5763. // Make sure enough workgroups get assigned for split k to work
  5764. 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 });
  5765. ggml_vk_sync_buffers(ctx, subctx);
  5766. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  5767. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 });
  5768. ctx->prealloc_split_k_need_sync = true;
  5769. }
  5770. 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) {
  5771. VK_LOG_DEBUG("ggml_vk_guess_matmul_id_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ")");
  5772. if (ctx->device->coopmat2) {
  5773. // Use large shader when the N dimension is greater than the medium shader's tile size
  5774. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5775. 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])) {
  5776. return aligned ? mmp->a_l : mmp->l;
  5777. }
  5778. // Use medium shader when the N dimension is greater than the small shader's tile size
  5779. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5780. if ((ctx->device->mul_mat_id_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_id_s[src0_type]) {
  5781. return aligned ? mmp->a_m : mmp->m;
  5782. }
  5783. return aligned ? mmp->a_s : mmp->s;
  5784. }
  5785. 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])) {
  5786. return aligned ? mmp->a_s : mmp->s;
  5787. }
  5788. if ((ctx->device->mul_mat_id_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l[src0_type]) {
  5789. return aligned ? mmp->a_m : mmp->m;
  5790. }
  5791. return aligned ? mmp->a_l : mmp->l;
  5792. }
  5793. 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) {
  5794. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ")");
  5795. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true, src0_type)->align;
  5796. }
  5797. static void ggml_vk_matmul_id(
  5798. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5799. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids, const vk_subbuffer & expert_count_buf,
  5800. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5801. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5802. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11,
  5803. uint32_t padded_n) {
  5804. VK_LOG_DEBUG("ggml_vk_matmul_id(a: (" << a.buffer->buffer << ", " << a.offset << ", " << a.size << "), b: (" << b.buffer->buffer << ", " << b.offset << ", " << b.size << "), d: (" << d.buffer->buffer << ", " << d.offset << ", " << d.size << "), ids: (" << ids.buffer->buffer << ", " << ids.offset << ", " << ids.size << "), expert_count: (" << expert_count_buf.buffer->buffer << ", " << expert_count_buf.offset << ", " << expert_count_buf.size << "), " <<
  5805. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  5806. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  5807. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  5808. 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,
  5809. nei0, nei1, nbi1, ne11, padded_n };
  5810. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids, expert_count_buf }, pc, { m, nei1, n_as });
  5811. }
  5812. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  5813. return
  5814. tensor->nb[0] == ggml_type_size(tensor->type) &&
  5815. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  5816. (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]);
  5817. }
  5818. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  5819. // Choose "contiguous copy" shader if src/dst are contiguous
  5820. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  5821. // Use optimized "transpose" shader if src dim1 is the innermost dimension.
  5822. bool transpose = dst && src->nb[1] == ggml_type_size(to) && ggml_are_same_shape(dst, src);
  5823. if (transpose && src->type == to) {
  5824. if (ggml_type_size(to) == 4) {
  5825. return ctx->device->pipeline_cpy_transpose_32;
  5826. } else if (ggml_type_size(to) == 2) {
  5827. return ctx->device->pipeline_cpy_transpose_16;
  5828. }
  5829. }
  5830. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  5831. if (contig) {
  5832. return ctx->device->pipeline_contig_cpy_f32_f32;
  5833. } else {
  5834. return ctx->device->pipeline_cpy_f32_f32;
  5835. }
  5836. }
  5837. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  5838. if (contig) {
  5839. return ctx->device->pipeline_contig_cpy_f32_f16;
  5840. } else {
  5841. return ctx->device->pipeline_cpy_f32_f16;
  5842. }
  5843. }
  5844. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  5845. if (contig) {
  5846. return ctx->device->pipeline_contig_cpy_f16_f16;
  5847. } else {
  5848. return ctx->device->pipeline_cpy_f16_f16;
  5849. }
  5850. }
  5851. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) {
  5852. if (contig) {
  5853. return ctx->device->pipeline_contig_cpy_f16_f32;
  5854. } else {
  5855. return ctx->device->pipeline_cpy_f16_f32;
  5856. }
  5857. }
  5858. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) {
  5859. if (contig) {
  5860. return ctx->device->pipeline_contig_cpy_f32_bf16;
  5861. } else {
  5862. return ctx->device->pipeline_cpy_f32_bf16;
  5863. }
  5864. }
  5865. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
  5866. if (contig) {
  5867. return ctx->device->pipeline_contig_cpy_f32_i32;
  5868. } else {
  5869. return ctx->device->pipeline_cpy_f32_i32;
  5870. }
  5871. }
  5872. if (src->type == GGML_TYPE_I32 && to == GGML_TYPE_F32) {
  5873. if (contig) {
  5874. return ctx->device->pipeline_contig_cpy_i32_f32;
  5875. } else {
  5876. return ctx->device->pipeline_cpy_i32_f32;
  5877. }
  5878. }
  5879. if (src->type == GGML_TYPE_F32) {
  5880. switch (to) {
  5881. case GGML_TYPE_Q4_0:
  5882. case GGML_TYPE_Q4_1:
  5883. case GGML_TYPE_Q5_0:
  5884. case GGML_TYPE_Q5_1:
  5885. case GGML_TYPE_Q8_0:
  5886. case GGML_TYPE_IQ4_NL:
  5887. return ctx->device->pipeline_cpy_f32_quant[to];
  5888. default:
  5889. break;
  5890. }
  5891. }
  5892. if (to == GGML_TYPE_F32) {
  5893. switch (src->type) {
  5894. case GGML_TYPE_Q4_0:
  5895. case GGML_TYPE_Q4_1:
  5896. case GGML_TYPE_Q5_0:
  5897. case GGML_TYPE_Q5_1:
  5898. case GGML_TYPE_Q8_0:
  5899. case GGML_TYPE_IQ4_NL:
  5900. return ctx->device->pipeline_cpy_quant_f32[src->type];
  5901. default:
  5902. break;
  5903. }
  5904. }
  5905. if (src->type == to) {
  5906. // Copy two or four bytes at a time, depending on block size.
  5907. // For quantized types, we scale by block size/type size. But
  5908. // this path is also used for bf16->bf16 for example, where the
  5909. // type size must be exactly 2 or 4.
  5910. GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4);
  5911. if ((ggml_type_size(src->type) % 4) == 0) {
  5912. if (contig) {
  5913. return ctx->device->pipeline_contig_cpy_f32_f32;
  5914. } else {
  5915. return ctx->device->pipeline_cpy_f32_f32;
  5916. }
  5917. } else {
  5918. if (contig) {
  5919. return ctx->device->pipeline_contig_cpy_f16_f16;
  5920. } else {
  5921. return ctx->device->pipeline_cpy_f16_f16;
  5922. }
  5923. }
  5924. }
  5925. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  5926. GGML_ABORT("fatal error");
  5927. }
  5928. 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) {
  5929. 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] << "), ";
  5930. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  5931. const int tensor_type_size = ggml_type_size(tensor->type);
  5932. const uint32_t ne = ggml_nelements(tensor);
  5933. std::array<uint32_t, 3> elements;
  5934. if (ne > 262144) {
  5935. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  5936. } else if (ne > 512) {
  5937. elements = { 512, CEIL_DIV(ne, 512), 1 };
  5938. } else {
  5939. elements = { ne, 1, 1 };
  5940. }
  5941. vk_op_unary_push_constants pc = {
  5942. (uint32_t)ne,
  5943. (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,
  5944. (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]),
  5945. 0,
  5946. 0.0f, 0.0f,
  5947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5948. };
  5949. init_pushconst_fastdiv(pc);
  5950. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements);
  5951. ggml_vk_sync_buffers(ctx, subctx);
  5952. }
  5953. static vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type) {
  5954. switch(type) {
  5955. case GGML_TYPE_Q8_1:
  5956. return ctx->device->pipeline_quantize_q8_1_x4;
  5957. default:
  5958. std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl;
  5959. GGML_ABORT("fatal error");
  5960. }
  5961. }
  5962. 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) {
  5963. VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")");
  5964. vk_pipeline pipeline = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5965. const uint32_t num_blocks = CEIL_DIV(ne, pipeline->wg_denoms[0]);
  5966. // clamp the number of elements to the max workgroup count. The shader will iterate over the total number of blocks.
  5967. const uint64_t max_elements = std::min<uint64_t>(uint64_t{ctx->device->properties.limits.maxComputeWorkGroupCount[0]} * pipeline->wg_denoms[0], std::numeric_limits<uint32_t>::max());
  5968. const uint32_t elements = std::min(ne, static_cast<uint32_t>(max_elements));
  5969. const vk_quantize_q8_1_push_constants pc = {
  5970. ne,
  5971. num_blocks,
  5972. };
  5973. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, { elements, 1, 1 });
  5974. ggml_vk_sync_buffers(ctx, subctx);
  5975. }
  5976. static vk_pipeline ggml_vk_get_64b_indexing_pipeline(ggml_backend_vk_context * ctx, vk_pipeline &pipeline) {
  5977. GGML_UNUSED(ctx);
  5978. #if defined(VK_EXT_shader_64bit_indexing)
  5979. vk_pipeline *ptr = &pipeline;
  5980. while (*ptr) {
  5981. if ((*ptr)->is_64b_indexing) {
  5982. return *ptr;
  5983. }
  5984. ptr = &(*ptr)->next;
  5985. }
  5986. #endif
  5987. return pipeline;
  5988. }
  5989. 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) {
  5990. 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];
  5991. 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];
  5992. 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];
  5993. std::cerr << "))");
  5994. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5995. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5996. const uint64_t ne00 = src0->ne[0];
  5997. const uint64_t ne01 = src0->ne[1];
  5998. const uint64_t ne02 = src0->ne[2];
  5999. const uint64_t ne03 = src0->ne[3];
  6000. const uint64_t ne10 = src1->ne[0];
  6001. const uint64_t ne11 = src1->ne[1];
  6002. const uint64_t ne12 = src1->ne[2];
  6003. const uint64_t ne13 = src1->ne[3];
  6004. const uint64_t ne21 = dst->ne[1];
  6005. const uint32_t stride_d = dst->nb[1] / ggml_type_size(dst->type);
  6006. const uint32_t stride_batch_d = stride_d*ne21;
  6007. const uint64_t r2 = ne12 / ne02;
  6008. const uint64_t r3 = ne13 / ne03;
  6009. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6010. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6011. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6012. vk_buffer d_Qx = nullptr;
  6013. size_t qx_buf_offset = 0;
  6014. vk_buffer d_Qy = nullptr;
  6015. size_t qy_buf_offset = 0;
  6016. bool src0_uma = false;
  6017. bool src1_uma = false;
  6018. if (ctx->device->uma) {
  6019. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6020. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6021. src0_uma = d_Qx != nullptr;
  6022. src1_uma = d_Qy != nullptr;
  6023. }
  6024. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  6025. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  6026. !ggml_vk_dim01_contiguous(src0);
  6027. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  6028. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  6029. !ggml_vk_dim01_contiguous(src1);
  6030. // If src0 is BF16, try to use a BF16 x BF16 multiply
  6031. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  6032. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  6033. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  6034. // Check for mmq first
  6035. 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;
  6036. if (mmp == nullptr) {
  6037. // Fall back to f16 dequant mul mat
  6038. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  6039. quantize_y = false;
  6040. }
  6041. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  6042. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  6043. if (qx_needs_dequant) {
  6044. // Fall back to dequant + f16 mulmat
  6045. 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]);
  6046. }
  6047. // Not implemented
  6048. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6049. 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)));
  6050. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8;
  6051. 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));
  6052. if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) {
  6053. pipeline = ggml_vk_get_64b_indexing_pipeline(ctx, pipeline);
  6054. }
  6055. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  6056. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11;
  6057. const uint64_t x_ne = ggml_nelements(src0);
  6058. // 128 elements per Q8_1 x4 block
  6059. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  6060. const uint64_t d_ne = ggml_nelements(dst);
  6061. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline);
  6062. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  6063. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6064. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  6065. 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);
  6066. const uint64_t d_sz = sizeof(float) * d_ne;
  6067. vk_pipeline to_fp16_vk_0 = nullptr;
  6068. vk_pipeline to_fp16_vk_1 = nullptr;
  6069. vk_pipeline to_q8_1 = nullptr;
  6070. if (x_non_contig) {
  6071. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  6072. } else {
  6073. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  6074. }
  6075. if (y_non_contig) {
  6076. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  6077. } else {
  6078. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6079. }
  6080. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6081. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6082. if (quantize_y) {
  6083. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6084. }
  6085. {
  6086. const uint64_t split_k_size = split_k > 1 ? d_sz * split_k : 0;
  6087. if (
  6088. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6089. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6090. (split_k > 1 && split_k_size > ctx->device->properties.limits.maxStorageBufferRange)) {
  6091. GGML_ABORT("Requested preallocation size is too large");
  6092. }
  6093. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6094. ctx->prealloc_size_x = x_sz;
  6095. ggml_vk_preallocate_buffers(ctx, subctx);
  6096. }
  6097. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6098. ctx->prealloc_size_y = y_sz;
  6099. ggml_vk_preallocate_buffers(ctx, subctx);
  6100. }
  6101. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  6102. ctx->prealloc_size_split_k = split_k_size;
  6103. ggml_vk_preallocate_buffers(ctx, subctx);
  6104. }
  6105. // Request descriptor sets
  6106. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6107. if (qx_needs_dequant) {
  6108. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6109. }
  6110. if (qy_needs_dequant) {
  6111. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6112. }
  6113. if (quantize_y) {
  6114. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6115. }
  6116. if (split_k > 1) {
  6117. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  6118. }
  6119. }
  6120. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6121. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6122. GGML_ASSERT(d_D != nullptr);
  6123. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz);
  6124. vk_buffer d_X;
  6125. uint64_t x_buf_offset = 0;
  6126. vk_buffer d_Y;
  6127. uint64_t y_buf_offset = 0;
  6128. if (!src0_uma) {
  6129. d_Qx = src0_buf_ctx->dev_buffer;
  6130. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6131. GGML_ASSERT(d_Qx != nullptr);
  6132. }
  6133. if (!src1_uma) {
  6134. d_Qy = src1_buf_ctx->dev_buffer;
  6135. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6136. GGML_ASSERT(d_Qy != nullptr);
  6137. }
  6138. if (qx_needs_dequant) {
  6139. d_X = ctx->prealloc_x;
  6140. GGML_ASSERT(d_X->size >= x_sz);
  6141. } else {
  6142. d_X = d_Qx;
  6143. x_buf_offset = qx_buf_offset;
  6144. GGML_ASSERT(qx_sz == x_sz);
  6145. }
  6146. if (qy_needs_dequant) {
  6147. d_Y = ctx->prealloc_y;
  6148. GGML_ASSERT(d_Y->size >= y_sz);
  6149. } else if (quantize_y) {
  6150. d_Y = ctx->prealloc_y;
  6151. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  6152. } else {
  6153. d_Y = d_Qy;
  6154. y_buf_offset = qy_buf_offset;
  6155. GGML_ASSERT(qy_sz == y_sz);
  6156. }
  6157. if (x_non_contig || qx_needs_dequant) {
  6158. if (ctx->prealloc_x_need_sync) {
  6159. ggml_vk_sync_buffers(ctx, subctx);
  6160. }
  6161. }
  6162. if (x_non_contig) {
  6163. 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));
  6164. } else if (qx_needs_dequant) {
  6165. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6166. 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});
  6167. ggml_vk_sync_buffers(ctx, subctx);
  6168. }
  6169. if (y_non_contig) {
  6170. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6171. ctx->prealloc_y_last_tensor_used != src1) {
  6172. if (ctx->prealloc_y_need_sync) {
  6173. ggml_vk_sync_buffers(ctx, subctx);
  6174. }
  6175. 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));
  6176. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6177. ctx->prealloc_y_last_tensor_used = src1;
  6178. }
  6179. }
  6180. if (quantize_y) {
  6181. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6182. ctx->prealloc_y_last_tensor_used != src1) {
  6183. if (ctx->prealloc_y_need_sync) {
  6184. ggml_vk_sync_buffers(ctx, subctx);
  6185. }
  6186. 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);
  6187. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6188. ctx->prealloc_y_last_tensor_used = src1;
  6189. }
  6190. }
  6191. uint32_t stride_batch_x = ne00*ne01;
  6192. uint32_t stride_batch_y = ne10*ne11;
  6193. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6194. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6195. }
  6196. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  6197. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6198. }
  6199. // compute
  6200. ggml_vk_matmul(
  6201. ctx, subctx, pipeline,
  6202. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  6203. ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, d_sz * split_k },
  6204. ne01, ne11, ne10,
  6205. ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d,
  6206. split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n
  6207. ); // NOLINT
  6208. if (x_non_contig || qx_needs_dequant) {
  6209. ctx->prealloc_x_need_sync = true;
  6210. }
  6211. if (y_non_contig || quantize_y) {
  6212. ctx->prealloc_y_need_sync = true;
  6213. }
  6214. }
  6215. // Device tuning
  6216. static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_t n, uint32_t k, ggml_type src0_type) {
  6217. if (device->mmvq_mode == 1) {
  6218. return true;
  6219. } else if (device->mmvq_mode == -1) {
  6220. return false;
  6221. }
  6222. // General performance issue with q3_k and q6_k due to 2-byte alignment
  6223. if (src0_type == GGML_TYPE_Q3_K || src0_type == GGML_TYPE_Q6_K) {
  6224. return false;
  6225. }
  6226. // MMVQ is generally good for batches
  6227. if (n > 1) {
  6228. return true;
  6229. }
  6230. // Quantization overhead is not worth it for small k
  6231. switch (device->vendor_id) {
  6232. case VK_VENDOR_ID_NVIDIA:
  6233. if (src0_type == GGML_TYPE_Q2_K || src0_type == GGML_TYPE_IQ1_S || src0_type == GGML_TYPE_IQ1_M) {
  6234. return true;
  6235. }
  6236. if (k <= 4096) {
  6237. return false;
  6238. }
  6239. switch (src0_type) {
  6240. case GGML_TYPE_MXFP4:
  6241. case GGML_TYPE_Q8_0:
  6242. return device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  6243. default:
  6244. return true;
  6245. }
  6246. case VK_VENDOR_ID_AMD:
  6247. if (k < 2048) {
  6248. return false;
  6249. }
  6250. switch (src0_type) {
  6251. case GGML_TYPE_Q8_0:
  6252. return device->architecture == vk_device_architecture::AMD_GCN;
  6253. default:
  6254. return true;
  6255. }
  6256. case VK_VENDOR_ID_INTEL:
  6257. if (k < 2048) {
  6258. return false;
  6259. }
  6260. switch (src0_type) {
  6261. // From tests on A770 Linux, may need more tuning
  6262. case GGML_TYPE_Q4_0:
  6263. case GGML_TYPE_Q5_1:
  6264. return false;
  6265. default:
  6266. return true;
  6267. }
  6268. default:
  6269. return true;
  6270. }
  6271. GGML_UNUSED(m);
  6272. }
  6273. 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) {
  6274. ggml_tensor * dst = cgraph->nodes[node_idx];
  6275. const ggml_tensor * src0 = dst->src[0];
  6276. const ggml_tensor * src1 = dst->src[1];
  6277. 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];
  6278. 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];
  6279. 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];
  6280. std::cerr << ")),)");
  6281. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6282. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6283. const uint64_t ne00 = src0->ne[0];
  6284. const uint64_t ne01 = src0->ne[1];
  6285. const uint64_t ne02 = src0->ne[2];
  6286. const uint64_t ne03 = src0->ne[3];
  6287. const uint64_t ne10 = src1->ne[0];
  6288. const uint64_t ne11 = src1->ne[1];
  6289. const uint64_t ne12 = src1->ne[2];
  6290. const uint64_t ne13 = src1->ne[3];
  6291. const uint64_t ne20 = dst->ne[0];
  6292. const uint64_t ne21 = dst->ne[1];
  6293. // const uint64_t ne22 = dst->ne[2];
  6294. // const uint64_t ne23 = dst->ne[3];
  6295. const uint64_t r2 = ne12 / ne02;
  6296. const uint64_t r3 = ne13 / ne03;
  6297. // batch_n indicates that we need to compute a few vector results, and this assumes
  6298. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  6299. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  6300. bool batch_n = ne11 > 1;
  6301. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6302. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6303. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6304. 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);
  6305. vk_pipeline to_fp16_vk_0 = nullptr;
  6306. vk_pipeline to_fp16_vk_1 = nullptr;
  6307. if (x_non_contig) {
  6308. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6309. }
  6310. if (y_non_contig) {
  6311. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6312. } else {
  6313. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6314. }
  6315. // Check for mmq first
  6316. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr;
  6317. vk_pipeline to_q8_1 = nullptr;
  6318. if (dmmv == nullptr) {
  6319. // Fall back to f16 dequant mul mat
  6320. dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11, ne20, ne00);
  6321. quantize_y = false;
  6322. }
  6323. if (quantize_y) {
  6324. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6325. }
  6326. if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) {
  6327. dmmv = ggml_vk_get_64b_indexing_pipeline(ctx, dmmv);
  6328. }
  6329. const bool qx_needs_dequant = x_non_contig;
  6330. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  6331. // Not implemented
  6332. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6333. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6334. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6335. GGML_ASSERT(dmmv != nullptr);
  6336. const uint64_t x_ne = ggml_nelements(src0);
  6337. const uint64_t y_ne = ggml_nelements(src1);
  6338. 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);
  6339. 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;
  6340. 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)) :
  6341. (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6342. {
  6343. if (
  6344. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6345. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6346. GGML_ABORT("Requested preallocation size is too large");
  6347. }
  6348. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6349. ctx->prealloc_size_x = x_sz;
  6350. ggml_vk_preallocate_buffers(ctx, subctx);
  6351. }
  6352. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6353. ctx->prealloc_size_y = y_sz;
  6354. ggml_vk_preallocate_buffers(ctx, subctx);
  6355. }
  6356. // Request descriptor sets
  6357. if (qx_needs_dequant) {
  6358. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6359. }
  6360. if (qy_needs_dequant) {
  6361. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6362. }
  6363. if (quantize_y) {
  6364. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6365. }
  6366. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6367. }
  6368. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6369. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6370. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  6371. vk_subbuffer d_X, d_Y;
  6372. if (qx_needs_dequant) {
  6373. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  6374. } else {
  6375. d_X = d_Qx;
  6376. GGML_ASSERT(qx_sz == x_sz);
  6377. }
  6378. if (qy_needs_dequant || quantize_y) {
  6379. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  6380. } else {
  6381. d_Y = d_Qy;
  6382. }
  6383. if (x_non_contig) {
  6384. if (ctx->prealloc_x_need_sync) {
  6385. ggml_vk_sync_buffers(ctx, subctx);
  6386. }
  6387. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6388. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  6389. }
  6390. if (y_non_contig) {
  6391. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6392. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6393. ctx->prealloc_y_last_tensor_used != src1) {
  6394. if (ctx->prealloc_y_need_sync) {
  6395. ggml_vk_sync_buffers(ctx, subctx);
  6396. }
  6397. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  6398. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6399. ctx->prealloc_y_last_tensor_used = src1;
  6400. }
  6401. }
  6402. if (quantize_y) {
  6403. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6404. ctx->prealloc_y_last_tensor_used != src1) {
  6405. if (ctx->prealloc_y_need_sync) {
  6406. ggml_vk_sync_buffers(ctx, subctx);
  6407. }
  6408. ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne);
  6409. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6410. ctx->prealloc_y_last_tensor_used = src1;
  6411. }
  6412. }
  6413. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  6414. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  6415. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  6416. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  6417. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6418. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6419. }
  6420. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6421. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6422. }
  6423. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6424. uint32_t groups_x = ne01;
  6425. uint32_t groups_z = 1;
  6426. if (ne01 > max_groups_x) {
  6427. groups_z = 64;
  6428. groups_x = CEIL_DIV(groups_x, groups_z);
  6429. }
  6430. uint32_t fusion_flags = 0;
  6431. vk_subbuffer d_F0 = d_D;
  6432. if (ctx->num_additional_fused_ops > 0) {
  6433. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6434. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6435. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6436. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6437. }
  6438. vk_subbuffer d_F1 = d_D;
  6439. if (ctx->num_additional_fused_ops == 2) {
  6440. const ggml_tensor * add = cgraph->nodes[node_idx + 2];
  6441. const ggml_tensor * bias = add->src[0] == cgraph->nodes[node_idx + 1] ? add->src[1] : add->src[0];
  6442. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6443. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6444. }
  6445. // compute
  6446. const vk_mat_vec_push_constants pc = {
  6447. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6448. stride_batch_x, stride_batch_y, stride_batch_d,
  6449. fusion_flags,
  6450. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  6451. };
  6452. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6453. {
  6454. d_X,
  6455. d_Y,
  6456. d_D,
  6457. d_F0,
  6458. d_F1,
  6459. },
  6460. pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  6461. if (x_non_contig) {
  6462. ctx->prealloc_x_need_sync = true;
  6463. }
  6464. if (y_non_contig || quantize_y) {
  6465. ctx->prealloc_y_need_sync = true;
  6466. }
  6467. }
  6468. 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) {
  6469. ggml_tensor * dst = cgraph->nodes[node_idx];
  6470. const ggml_tensor * src0 = dst->src[0];
  6471. const ggml_tensor * src1 = dst->src[1];
  6472. 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];
  6473. 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];
  6474. 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];
  6475. std::cerr << "))");
  6476. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  6477. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  6478. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  6479. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6480. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6481. const uint64_t ne00 = src0->ne[0];
  6482. const uint64_t ne01 = src0->ne[1];
  6483. const uint64_t ne02 = src0->ne[2];
  6484. // const uint64_t ne03 = src0->ne[3];
  6485. //const uint64_t ne10 = src1->ne[0];
  6486. const uint64_t ne11 = src1->ne[1];
  6487. const uint64_t ne12 = src1->ne[2];
  6488. // const uint64_t ne13 = src1->ne[3];
  6489. GGML_ASSERT(ne11 == 1);
  6490. // With grouped query attention there are > 1 Q matrices per K, V matrix.
  6491. uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02;
  6492. if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) {
  6493. gqa_ratio = 1;
  6494. }
  6495. vk_pipeline pipeline = ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1];
  6496. if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) {
  6497. pipeline = ggml_vk_get_64b_indexing_pipeline(ctx, pipeline);
  6498. }
  6499. {
  6500. // Request descriptor sets
  6501. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6502. }
  6503. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  6504. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6505. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  6506. vk_subbuffer d_F0 = d_D;
  6507. uint32_t fusion_flags = 0;
  6508. if (ctx->num_additional_fused_ops > 0) {
  6509. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6510. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6511. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6512. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6513. }
  6514. vk_subbuffer d_F1 = d_D;
  6515. if (ctx->num_additional_fused_ops > 1) {
  6516. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  6517. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6518. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6519. }
  6520. // compute
  6521. vk_mat_vec_p021_push_constants pc = {
  6522. (uint32_t)ne00, (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne12,
  6523. 0, 0, fusion_flags
  6524. };
  6525. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6526. uint32_t workgroups_z = (uint32_t)ne12;
  6527. // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups
  6528. if (gqa_ratio > 1) {
  6529. workgroups_z /= gqa_ratio;
  6530. }
  6531. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6532. {
  6533. d_Qx,
  6534. d_Qy,
  6535. d_D,
  6536. d_F0,
  6537. d_F1,
  6538. }, pc, { 1, (uint32_t)ne01, workgroups_z });
  6539. }
  6540. 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) {
  6541. ggml_tensor * dst = cgraph->nodes[node_idx];
  6542. const ggml_tensor * src0 = dst->src[0];
  6543. const ggml_tensor * src1 = dst->src[1];
  6544. 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];
  6545. 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];
  6546. 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];
  6547. std::cerr << "))");
  6548. GGML_ASSERT(!ggml_is_transposed(src0));
  6549. GGML_ASSERT(!ggml_is_transposed(src1));
  6550. GGML_ASSERT(!ggml_is_permuted(src0));
  6551. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6552. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6553. const uint64_t ne00 = src0->ne[0];
  6554. const uint64_t ne01 = src0->ne[1];
  6555. const uint64_t ne02 = src0->ne[2];
  6556. const uint64_t ne03 = src0->ne[3];
  6557. const uint64_t nb01 = src0->nb[1];
  6558. const uint64_t nb02 = src0->nb[2];
  6559. const uint64_t nb12 = src1->nb[2];
  6560. // const uint64_t ne10 = src1->ne[0];
  6561. const uint64_t ne11 = src1->ne[1];
  6562. const uint64_t ne12 = src1->ne[2];
  6563. // const uint64_t ne13 = src1->ne[3];
  6564. const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t));
  6565. const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float));
  6566. const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float));
  6567. GGML_ASSERT(ne11 == 1);
  6568. GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in supports_op
  6569. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  6570. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  6571. const uint32_t channel_stride_y = nb12 / sizeof(float);
  6572. vk_pipeline pipeline = ctx->device->pipeline_mul_mat_vec_nc_f16_f32;
  6573. if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) {
  6574. pipeline = ggml_vk_get_64b_indexing_pipeline(ctx, pipeline);
  6575. }
  6576. {
  6577. // Request descriptor sets
  6578. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6579. }
  6580. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  6581. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6582. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  6583. vk_subbuffer d_F0 = d_D;
  6584. uint32_t fusion_flags = 0;
  6585. if (ctx->num_additional_fused_ops > 0) {
  6586. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6587. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6588. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6589. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6590. }
  6591. vk_subbuffer d_F1 = d_D;
  6592. if (ctx->num_additional_fused_ops > 1) {
  6593. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  6594. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6595. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6596. }
  6597. // compute
  6598. vk_mat_vec_nc_push_constants pc = {
  6599. (uint32_t)ne00, (uint32_t)ne01,
  6600. row_stride_x, channel_stride_x, channel_stride_y,
  6601. (uint32_t)(ne12 / ne02), (uint32_t)ne12,
  6602. 0, 0,
  6603. nb03, nb13, nb23, fusion_flags
  6604. };
  6605. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6606. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6607. {
  6608. d_Qx,
  6609. d_Qy,
  6610. d_D,
  6611. d_F0,
  6612. d_F1,
  6613. }, pc, { (uint32_t)ne03, (uint32_t)ne01, (uint32_t)ne12 });
  6614. }
  6615. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6616. ggml_tensor * dst = cgraph->nodes[node_idx];
  6617. ggml_tensor * src0 = dst->src[0];
  6618. ggml_tensor * src1 = dst->src[1];
  6619. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  6620. // Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases
  6621. // where the M dimension is very large.
  6622. // Split_k doesn't work with M splitting.
  6623. // This only supports batchsize == 1.
  6624. const size_t nbytes = ggml_nbytes(src0);
  6625. const bool needs_split = dst->ne[2] == 1 && dst->ne[3] == 1 && nbytes > ctx->device->properties.limits.maxStorageBufferRange;
  6626. if (needs_split) {
  6627. // Choose the number of rows that can fit (and divide by two, to allow for any additional offsets)
  6628. const uint32_t M_split = ctx->device->properties.limits.maxStorageBufferRange / (2 * src0->nb[1]);
  6629. uint32_t m_offset = 0;
  6630. while (m_offset < dst->ne[0]) {
  6631. const uint32_t cur_M_size = std::min(M_split, (uint32_t)(dst->ne[0] - m_offset));
  6632. ggml_tensor dst2 = *dst;
  6633. ggml_tensor src02 = *src0;
  6634. dst2.view_src = dst->view_src ? dst->view_src : dst;
  6635. src02.view_src = src0->view_src ? src0->view_src : src0;
  6636. dst2.view_offs += m_offset * dst->nb[0];
  6637. src02.view_offs += m_offset * src0->nb[1];
  6638. dst2.ne[0] = cur_M_size;
  6639. src02.ne[1] = cur_M_size;
  6640. ggml_vk_mul_mat_q_f16(ctx, subctx, &src02, src1, &dst2, true);
  6641. m_offset += cur_M_size;
  6642. }
  6643. } else if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  6644. // detect 0213 permutation, and batch size of 1
  6645. src0->nb[0] <= src0->nb[2] &&
  6646. src0->nb[2] <= src0->nb[1] &&
  6647. src0->nb[1] <= src0->nb[3] &&
  6648. src1->nb[0] <= src1->nb[2] &&
  6649. src1->nb[2] <= src1->nb[1] &&
  6650. src1->nb[1] <= src1->nb[3] &&
  6651. src0->ne[3] == 1 &&
  6652. src1->ne[3] == 1) {
  6653. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, cgraph, node_idx);
  6654. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  6655. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  6656. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, cgraph, node_idx);
  6657. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  6658. // when ne12 and ne13 are one.
  6659. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  6660. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
  6661. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx);
  6662. } else {
  6663. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false);
  6664. }
  6665. }
  6666. 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) {
  6667. 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];
  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. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6672. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6673. const uint64_t ne00 = src0->ne[0];
  6674. const uint64_t ne01 = src0->ne[1];
  6675. const uint64_t ne02 = src0->ne[2];
  6676. // const uint64_t ne03 = src0->ne[3];
  6677. const uint64_t ne10 = src1->ne[0];
  6678. const uint64_t ne11 = src1->ne[1];
  6679. const uint64_t ne12 = src1->ne[2];
  6680. const uint64_t ne13 = src1->ne[3];
  6681. const uint64_t nei0 = ids->ne[0];
  6682. const uint64_t nei1 = ids->ne[1];
  6683. const uint32_t nbi0 = ids->nb[0];
  6684. const uint32_t nbi1 = ids->nb[1];
  6685. const uint32_t nbi2 = ids->nb[2];
  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 uint64_t n_as = ne02;
  6691. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6692. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6693. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6694. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6695. vk_buffer d_Qx = nullptr;
  6696. size_t qx_buf_offset = 0;
  6697. vk_buffer d_Qy = nullptr;
  6698. size_t qy_buf_offset = 0;
  6699. vk_buffer d_ids = nullptr;
  6700. size_t ids_buf_offset = 0;
  6701. bool src0_uma = false;
  6702. bool src1_uma = false;
  6703. bool ids_uma = false;
  6704. if (ctx->device->uma) {
  6705. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6706. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6707. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6708. src0_uma = d_Qx != nullptr;
  6709. src1_uma = d_Qy != nullptr;
  6710. ids_uma = d_ids != nullptr;
  6711. }
  6712. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  6713. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  6714. !ggml_vk_dim01_contiguous(src0);
  6715. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  6716. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  6717. !ggml_vk_dim01_contiguous(src1);
  6718. // If src0 is BF16, try to use a BF16 x BF16 multiply
  6719. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  6720. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  6721. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  6722. // Check for mmq first
  6723. 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;
  6724. if (mmp == nullptr) {
  6725. // Fall back to f16 dequant mul mat
  6726. 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]);
  6727. quantize_y = false;
  6728. }
  6729. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  6730. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  6731. if (qx_needs_dequant) {
  6732. // Fall back to dequant + f16 mulmat
  6733. 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]);
  6734. }
  6735. // Not implemented
  6736. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6737. 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));
  6738. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && nei1 > 8;
  6739. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned, qx_needs_dequant ? f16_type : src0->type);
  6740. if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) {
  6741. pipeline = ggml_vk_get_64b_indexing_pipeline(ctx, pipeline);
  6742. }
  6743. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  6744. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) :ne11;
  6745. const uint64_t x_ne = ggml_nelements(src0);
  6746. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  6747. const uint64_t d_ne = ggml_nelements(dst);
  6748. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  6749. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6750. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  6751. 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);
  6752. const uint64_t ids_sz = nbi2;
  6753. const uint64_t d_sz = sizeof(float) * d_ne;
  6754. vk_pipeline to_fp16_vk_0 = nullptr;
  6755. vk_pipeline to_fp16_vk_1 = nullptr;
  6756. vk_pipeline to_q8_1 = nullptr;
  6757. if (x_non_contig) {
  6758. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  6759. } else {
  6760. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  6761. }
  6762. if (y_non_contig) {
  6763. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  6764. } else {
  6765. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6766. }
  6767. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6768. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6769. if (quantize_y) {
  6770. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6771. }
  6772. vk_pipeline count_experts = ctx->device->pipeline_count_experts;
  6773. uint32_t expert_count_size = sizeof(uint32_t) * n_as;
  6774. {
  6775. if (
  6776. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6777. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6778. GGML_ABORT("Requested preallocation size is too large");
  6779. }
  6780. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6781. ctx->prealloc_size_x = x_sz;
  6782. ggml_vk_preallocate_buffers(ctx, subctx);
  6783. }
  6784. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6785. ctx->prealloc_size_y = y_sz;
  6786. ggml_vk_preallocate_buffers(ctx, subctx);
  6787. }
  6788. if (ctx->prealloc_size_split_k < expert_count_size) {
  6789. ctx->prealloc_size_split_k = expert_count_size;
  6790. ggml_vk_preallocate_buffers(ctx, subctx);
  6791. }
  6792. // Request descriptor sets
  6793. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6794. if (qx_needs_dequant) {
  6795. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6796. }
  6797. if (qy_needs_dequant) {
  6798. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6799. }
  6800. if (quantize_y) {
  6801. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6802. }
  6803. ggml_pipeline_request_descriptor_sets(ctx, count_experts, 1);
  6804. }
  6805. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6806. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6807. GGML_ASSERT(d_D != nullptr);
  6808. vk_buffer d_X;
  6809. uint64_t x_buf_offset = 0;
  6810. vk_buffer d_Y;
  6811. uint64_t y_buf_offset = 0;
  6812. if (!src0_uma) {
  6813. d_Qx = src0_buf_ctx->dev_buffer;
  6814. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6815. GGML_ASSERT(d_Qx != nullptr);
  6816. }
  6817. if (!src1_uma) {
  6818. d_Qy = src1_buf_ctx->dev_buffer;
  6819. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6820. GGML_ASSERT(d_Qy != nullptr);
  6821. }
  6822. if (!ids_uma) {
  6823. d_ids = ids_buf_ctx->dev_buffer;
  6824. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6825. GGML_ASSERT(d_ids != nullptr);
  6826. }
  6827. if (qx_needs_dequant) {
  6828. d_X = ctx->prealloc_x;
  6829. GGML_ASSERT(d_X->size >= x_sz);
  6830. } else {
  6831. d_X = d_Qx;
  6832. x_buf_offset = qx_buf_offset;
  6833. GGML_ASSERT(qx_sz == x_sz);
  6834. }
  6835. if (qy_needs_dequant) {
  6836. d_Y = ctx->prealloc_y;
  6837. GGML_ASSERT(d_Y->size >= y_sz);
  6838. } else if (quantize_y) {
  6839. d_Y = ctx->prealloc_y;
  6840. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  6841. } else {
  6842. d_Y = d_Qy;
  6843. y_buf_offset = qy_buf_offset;
  6844. GGML_ASSERT(qy_sz == y_sz);
  6845. }
  6846. if (x_non_contig || qx_needs_dequant) {
  6847. if (ctx->prealloc_x_need_sync) {
  6848. ggml_vk_sync_buffers(ctx, subctx);
  6849. }
  6850. }
  6851. // Count how many times each expert is used
  6852. vk_subbuffer expert_count_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  6853. if (ctx->prealloc_split_k_need_sync) {
  6854. ggml_vk_sync_buffers(ctx, subctx);
  6855. }
  6856. {
  6857. const std::vector<uint32_t> pc = { (uint32_t)nei0,
  6858. (uint32_t)nei1,
  6859. (uint32_t)(nbi0 / ggml_type_size(ids->type)),
  6860. (uint32_t)(nbi1 / ggml_type_size(ids->type)),
  6861. (uint32_t)(get_misalign_bytes(ctx, ids) / ggml_type_size(ids->type)) };
  6862. ggml_vk_dispatch_pipeline(ctx, subctx, count_experts,
  6863. { vk_subbuffer{ d_ids, ids_buf_offset, ids_sz }, expert_count_buf }, pc, { (uint32_t)n_as, 1, 1});
  6864. }
  6865. if (x_non_contig) {
  6866. 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));
  6867. } else if (qx_needs_dequant) {
  6868. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6869. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  6870. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)x_ne, 1, 1});
  6871. }
  6872. if (y_non_contig) {
  6873. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6874. ctx->prealloc_y_last_tensor_used != src1) {
  6875. if (ctx->prealloc_y_need_sync) {
  6876. ggml_vk_sync_buffers(ctx, subctx);
  6877. }
  6878. 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));
  6879. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6880. ctx->prealloc_y_last_tensor_used = src1;
  6881. }
  6882. }
  6883. if (quantize_y) {
  6884. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6885. ctx->prealloc_y_last_tensor_used != src1) {
  6886. if (ctx->prealloc_y_need_sync) {
  6887. ggml_vk_sync_buffers(ctx, subctx);
  6888. }
  6889. 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);
  6890. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6891. ctx->prealloc_y_last_tensor_used = src1;
  6892. }
  6893. }
  6894. ggml_vk_sync_buffers(ctx, subctx);
  6895. uint32_t stride_batch_x = ne00*ne01;
  6896. uint32_t stride_batch_y = ne10*ne11;
  6897. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6898. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6899. }
  6900. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  6901. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6902. }
  6903. // compute
  6904. ggml_vk_matmul_id(
  6905. ctx, subctx, pipeline,
  6906. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  6907. { d_D, d_buf_offset, d_sz }, { d_ids, ids_buf_offset, ids_sz }, expert_count_buf,
  6908. ne01, ne21, ne10, ne10, ne10, ne01,
  6909. stride_batch_x, stride_batch_y, ne20*ne21,
  6910. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, padded_n
  6911. ); // NOLINT
  6912. if (x_non_contig || qx_needs_dequant) {
  6913. ctx->prealloc_x_need_sync = true;
  6914. }
  6915. if (y_non_contig || quantize_y) {
  6916. ctx->prealloc_y_need_sync = true;
  6917. }
  6918. ctx->prealloc_split_k_need_sync = true;
  6919. }
  6920. 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) {
  6921. ggml_tensor * dst = cgraph->nodes[node_idx];
  6922. ggml_tensor * src0 = dst->src[0];
  6923. ggml_tensor * src1 = dst->src[1];
  6924. ggml_tensor * ids = dst->src[2];
  6925. 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];
  6926. 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];
  6927. 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];
  6928. 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];
  6929. std::cerr << "))");
  6930. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6931. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6932. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6933. const uint64_t ne00 = src0->ne[0];
  6934. const uint64_t ne01 = src0->ne[1];
  6935. // const uint64_t ne02 = src0->ne[2];
  6936. // const uint64_t ne03 = src0->ne[3];
  6937. const uint64_t ne10 = src1->ne[0];
  6938. const uint64_t ne11 = src1->ne[1];
  6939. const uint64_t ne12 = src1->ne[2];
  6940. // const uint64_t ne13 = src1->ne[3];
  6941. const uint64_t nei0 = ids->ne[0];
  6942. const uint64_t nei1 = ids->ne[1];
  6943. GGML_ASSERT(nei1 == 1);
  6944. const uint64_t ne20 = dst->ne[0];
  6945. const uint64_t ne21 = dst->ne[1];
  6946. // const uint64_t ne22 = dst->ne[2];
  6947. // const uint64_t ne23 = dst->ne[3];
  6948. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6949. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6950. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6951. 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);
  6952. vk_pipeline to_fp16_vk_0 = nullptr;
  6953. vk_pipeline to_fp16_vk_1 = nullptr;
  6954. if (x_non_contig) {
  6955. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6956. }
  6957. if (y_non_contig) {
  6958. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6959. } else {
  6960. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6961. }
  6962. // Check for mmq first
  6963. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, GGML_TYPE_Q8_1, ne20, ne00) : nullptr;
  6964. vk_pipeline to_q8_1 = nullptr;
  6965. if (dmmv == nullptr) {
  6966. // Fall back to f16 dequant mul mat
  6967. dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type, ne20, ne00);
  6968. quantize_y = false;
  6969. }
  6970. if (quantize_y) {
  6971. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6972. }
  6973. const bool qx_needs_dequant = x_non_contig;
  6974. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  6975. if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) {
  6976. dmmv = ggml_vk_get_64b_indexing_pipeline(ctx, dmmv);
  6977. }
  6978. // Not implemented
  6979. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6980. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6981. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6982. GGML_ASSERT(dmmv != nullptr);
  6983. const uint64_t x_ne = ggml_nelements(src0);
  6984. const uint64_t y_ne = ggml_nelements(src1);
  6985. 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);
  6986. 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;
  6987. 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)) :
  6988. (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6989. {
  6990. if (
  6991. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6992. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6993. GGML_ABORT("Requested preallocation size is too large");
  6994. }
  6995. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6996. ctx->prealloc_size_x = x_sz;
  6997. ggml_vk_preallocate_buffers(ctx, subctx);
  6998. }
  6999. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  7000. ctx->prealloc_size_y = y_sz;
  7001. ggml_vk_preallocate_buffers(ctx, subctx);
  7002. }
  7003. // Request descriptor sets
  7004. if (qx_needs_dequant) {
  7005. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  7006. }
  7007. if (qy_needs_dequant) {
  7008. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  7009. }
  7010. if (quantize_y) {
  7011. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  7012. }
  7013. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  7014. }
  7015. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  7016. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  7017. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  7018. vk_subbuffer d_ids = ggml_vk_tensor_subbuffer(ctx, ids);
  7019. vk_subbuffer d_F0 = d_D;
  7020. vk_subbuffer d_X, d_Y;
  7021. if (qx_needs_dequant) {
  7022. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  7023. } else {
  7024. d_X = d_Qx;
  7025. }
  7026. if (qy_needs_dequant || quantize_y) {
  7027. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  7028. } else {
  7029. d_Y = d_Qy;
  7030. }
  7031. if (x_non_contig) {
  7032. if (ctx->prealloc_x_need_sync) {
  7033. ggml_vk_sync_buffers(ctx, subctx);
  7034. }
  7035. }
  7036. if (x_non_contig) {
  7037. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  7038. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  7039. }
  7040. if (y_non_contig) {
  7041. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  7042. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  7043. ctx->prealloc_y_last_tensor_used != src1) {
  7044. if (ctx->prealloc_y_need_sync) {
  7045. ggml_vk_sync_buffers(ctx, subctx);
  7046. }
  7047. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  7048. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  7049. ctx->prealloc_y_last_tensor_used = src1;
  7050. }
  7051. }
  7052. if (quantize_y) {
  7053. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  7054. ctx->prealloc_y_last_tensor_used != src1) {
  7055. if (ctx->prealloc_y_need_sync) {
  7056. ggml_vk_sync_buffers(ctx, subctx);
  7057. }
  7058. ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne);
  7059. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  7060. ctx->prealloc_y_last_tensor_used = src1;
  7061. }
  7062. }
  7063. uint32_t stride_batch_y = ne10*ne11;
  7064. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  7065. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  7066. }
  7067. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  7068. uint32_t groups_x = ne01;
  7069. uint32_t groups_z = 1;
  7070. if (ne01 > max_groups_x) {
  7071. groups_z = 64;
  7072. groups_x = CEIL_DIV(groups_x, groups_z);
  7073. }
  7074. uint32_t fusion_flags = 0;
  7075. if (ctx->num_additional_fused_ops > 0) {
  7076. const ggml_tensor * bias = cgraph->nodes[node_idx + 1]->src[1];
  7077. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  7078. if (cgraph->nodes[node_idx + 1]->op == GGML_OP_MUL) {
  7079. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE0;
  7080. } else {
  7081. GGML_ASSERT(cgraph->nodes[node_idx + 1]->op == GGML_OP_ADD_ID);
  7082. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  7083. }
  7084. }
  7085. vk_subbuffer d_F1 = d_D;
  7086. if (ctx->num_additional_fused_ops > 1) {
  7087. const ggml_tensor * scale = cgraph->nodes[node_idx + 2]->src[1];
  7088. d_F1 = ggml_vk_tensor_subbuffer(ctx, scale);
  7089. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE1;
  7090. }
  7091. // compute
  7092. const vk_mat_vec_id_push_constants pc = {
  7093. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  7094. (uint32_t)(ne00 * ne01), stride_batch_y, (uint32_t)(ne20 * ne21),
  7095. fusion_flags,
  7096. (uint32_t)nei0, (uint32_t)ne11,
  7097. };
  7098. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  7099. {
  7100. d_X,
  7101. d_Y,
  7102. d_D,
  7103. d_F0,
  7104. d_F1,
  7105. d_ids,
  7106. },
  7107. pc, { groups_x, (uint32_t)nei0, groups_z });
  7108. if (x_non_contig) {
  7109. ctx->prealloc_x_need_sync = true;
  7110. }
  7111. if (y_non_contig || quantize_y) {
  7112. ctx->prealloc_y_need_sync = true;
  7113. }
  7114. }
  7115. static bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx) {
  7116. ggml_tensor * dst = cgraph->nodes[node_idx];
  7117. ggml_tensor * src0 = dst->src[0];
  7118. ggml_tensor * src2 = dst->src[2];
  7119. return src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type));
  7120. }
  7121. static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  7122. ggml_tensor * dst = cgraph->nodes[node_idx];
  7123. ggml_tensor * src0 = dst->src[0];
  7124. ggml_tensor * src1 = dst->src[1];
  7125. ggml_tensor * src2 = dst->src[2];
  7126. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  7127. if (ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  7128. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, cgraph, node_idx);
  7129. } else {
  7130. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst);
  7131. }
  7132. }
  7133. static bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool small_cache) {
  7134. // Needs to be kept up to date on shader changes
  7135. GGML_UNUSED(hsv);
  7136. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  7137. const uint32_t Br = get_fa_scalar_num_large_rows(hsk, hsv, small_cache);
  7138. const uint32_t Bc = scalar_flash_attention_Bc;
  7139. const uint32_t tmpsh = wg_size * sizeof(float);
  7140. const uint32_t tmpshv4 = wg_size * 4 * sizeof(float);
  7141. const uint32_t masksh = Bc * Br * sizeof(float);
  7142. const uint32_t Qf = Br * (hsk / 4 + 2) * 4 * sizeof(float);
  7143. const uint32_t total_size = tmpsh + tmpshv4 + masksh + Qf;
  7144. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  7145. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported);
  7146. return supported;
  7147. }
  7148. static bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool f32acc) {
  7149. // Needs to be kept up to date on shader changes
  7150. GGML_UNUSED(hsv);
  7151. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  7152. const uint32_t Br = coopmat1_flash_attention_num_large_rows;
  7153. const uint32_t Bc = scalar_flash_attention_Bc;
  7154. const uint32_t hsk_pad = ROUNDUP_POW2(hsk, 16);
  7155. const uint32_t acctype = f32acc ? 4 : 2;
  7156. const uint32_t f16vec4 = 8;
  7157. const uint32_t tmpsh = wg_size * sizeof(float);
  7158. const uint32_t tmpshv4 = wg_size * 4 * acctype;
  7159. const uint32_t qstride = hsk_pad / 4 + 2;
  7160. const uint32_t Qf = Br * qstride * f16vec4;
  7161. const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br;
  7162. const uint32_t sfsh = Bc * sfshstride * acctype;
  7163. const uint32_t kshstride = hsk_pad / 4 + 2;
  7164. const uint32_t ksh = Bc * kshstride * f16vec4;
  7165. const uint32_t slope = Br * sizeof(float);
  7166. const uint32_t total_size = tmpsh + tmpshv4 + Qf + sfsh + ksh + slope;
  7167. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  7168. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported);
  7169. return supported;
  7170. }
  7171. 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) {
  7172. 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];
  7173. 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];
  7174. 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];
  7175. 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];
  7176. if (sinks) {
  7177. 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];
  7178. }
  7179. std::cerr << "))");
  7180. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  7181. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  7182. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  7183. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  7184. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  7185. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  7186. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  7187. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  7188. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  7189. const uint32_t nem2 = mask ? mask->ne[2] : 0;
  7190. const uint32_t nem3 = mask ? mask->ne[3] : 0;
  7191. const uint32_t HSK = nek0;
  7192. const uint32_t HSV = nev0;
  7193. uint32_t N = neq1;
  7194. const uint32_t KV = nek1;
  7195. GGML_ASSERT(ne0 == HSV);
  7196. GGML_ASSERT(ne2 == N);
  7197. // input tensor rows must be contiguous
  7198. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  7199. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  7200. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  7201. GGML_ASSERT(neq0 == HSK);
  7202. GGML_ASSERT(neq1 == N);
  7203. GGML_ASSERT(nev1 == nek1);
  7204. // dst cannot be transposed or permuted
  7205. GGML_ASSERT(nb0 == sizeof(float));
  7206. GGML_ASSERT(nb0 <= nb1);
  7207. GGML_ASSERT(nb1 <= nb2);
  7208. GGML_ASSERT(nb2 <= nb3);
  7209. assert(dst->type == GGML_TYPE_F32);
  7210. assert(q->type == GGML_TYPE_F32);
  7211. assert(k->type == v->type);
  7212. FaCodePath path = ctx->device->coopmat2 ? FA_COOPMAT2 :
  7213. ctx->device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;
  7214. if (path == FA_COOPMAT1) {
  7215. const bool coopmat_shape_supported = (dst->op_params[3] == GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f32acc) ||
  7216. (dst->op_params[3] != GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f16acc);
  7217. const bool coopmat_shmem_supported = ggml_vk_flash_attn_coopmat_shmem_support(ctx->device, HSK, HSV, dst->op_params[3] == GGML_PREC_F32);
  7218. if (!coopmat_shape_supported || !coopmat_shmem_supported) {
  7219. path = FA_SCALAR;
  7220. }
  7221. }
  7222. uint32_t gqa_ratio = 1;
  7223. uint32_t qk_ratio = neq2 / nek2;
  7224. uint32_t workgroups_x = (uint32_t)neq1;
  7225. uint32_t workgroups_y = (uint32_t)neq2;
  7226. uint32_t workgroups_z = (uint32_t)neq3;
  7227. const bool small_cache = nek1 < 1024;
  7228. // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga.
  7229. // For coopmat2 FA, we always use the small size (which is still pretty large for gqa).
  7230. uint32_t max_gqa;
  7231. switch (path) {
  7232. case FA_SCALAR:
  7233. case FA_COOPMAT1:
  7234. // We may switch from coopmat1 to scalar, so use the scalar limit for both
  7235. max_gqa = get_fa_scalar_num_large_rows(HSK, HSV, small_cache);
  7236. break;
  7237. case FA_COOPMAT2:
  7238. max_gqa = get_fa_num_small_rows(FA_COOPMAT2);
  7239. break;
  7240. default:
  7241. GGML_ASSERT(0);
  7242. }
  7243. if (N == 1 && qk_ratio > 1 && qk_ratio <= max_gqa &&
  7244. qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) {
  7245. // grouped query attention - make the N dimension equal to gqa_ratio, reduce
  7246. // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1
  7247. // and change addressing calculations to index Q's dimension 2.
  7248. gqa_ratio = qk_ratio;
  7249. N = gqa_ratio;
  7250. workgroups_y /= N;
  7251. }
  7252. bool small_rows = N <= get_fa_num_small_rows(path);
  7253. // coopmat1 does not actually support "small rows" (it needs 16 rows).
  7254. // So use scalar instead.
  7255. if (small_rows && path == FA_COOPMAT1) {
  7256. path = FA_SCALAR;
  7257. }
  7258. // scalar is faster than coopmat2 when N==1
  7259. if (N == 1 && path == FA_COOPMAT2) {
  7260. path = FA_SCALAR;
  7261. }
  7262. // with large hsk/hsv, scalar path may need to use small_rows to fit in shared memory
  7263. if (path == FA_SCALAR &&
  7264. !ggml_vk_flash_attn_scalar_shmem_support(ctx->device, HSK, HSV, small_cache)) {
  7265. small_rows = true;
  7266. }
  7267. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  7268. uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  7269. uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  7270. // For F32, the shader treats it as a block of size 4 (for vec4 loads)
  7271. if (k->type == GGML_TYPE_F32) {
  7272. k_stride /= 4;
  7273. }
  7274. if (v->type == GGML_TYPE_F32) {
  7275. v_stride /= 4;
  7276. }
  7277. uint32_t alignment = fa_align(path, HSK, HSV, k->type, small_rows, small_cache);
  7278. bool aligned = (KV % alignment) == 0 &&
  7279. // the "aligned" shader variant will forcibly align strides, for performance
  7280. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  7281. // Need to use the coopmat2 variant that clamps loads when HSK/HSV aren't sufficiently aligned.
  7282. if (((HSK | HSV) % 16) != 0 && path == FA_COOPMAT2) {
  7283. aligned = false;
  7284. }
  7285. bool f32acc = path == FA_SCALAR || dst->op_params[3] == GGML_PREC_F32;
  7286. vk_fa_pipeline_state fa_pipeline_state(HSK, HSV, small_rows, small_cache, path, aligned, f32acc);
  7287. vk_pipeline pipeline = nullptr;
  7288. {
  7289. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7290. auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16[k->type];
  7291. auto it = pipelines.find(fa_pipeline_state);
  7292. if (it != pipelines.end()) {
  7293. pipeline = it->second;
  7294. } else {
  7295. pipelines[fa_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7296. }
  7297. }
  7298. assert(pipeline);
  7299. uint32_t split_kv = KV;
  7300. uint32_t split_k = 1;
  7301. // Use a placeholder core count if one isn't available. split_k is a big help for perf.
  7302. const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count : 16;
  7303. // Try to use split_k when KV is large enough to be worth the overhead
  7304. if (workgroups_x == 1 && shader_core_count > 0) {
  7305. // Try to run two workgroups per SM.
  7306. split_k = shader_core_count * 2 / (workgroups_y * workgroups_z);
  7307. if (split_k > 1) {
  7308. // Try to evenly split KV into split_k chunks, but it needs to be a multiple
  7309. // of "align", so recompute split_k based on that.
  7310. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment);
  7311. split_k = CEIL_DIV(KV, split_kv);
  7312. workgroups_x = split_k;
  7313. }
  7314. }
  7315. // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1)
  7316. // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows.
  7317. const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne3 : 0;
  7318. if (split_k_size > ctx->device->properties.limits.maxStorageBufferRange) {
  7319. GGML_ABORT("Requested preallocation size is too large");
  7320. }
  7321. if (ctx->prealloc_size_split_k < split_k_size) {
  7322. ctx->prealloc_size_split_k = split_k_size;
  7323. ggml_vk_preallocate_buffers(ctx, subctx);
  7324. }
  7325. {
  7326. // Request descriptor sets
  7327. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7328. if (split_k > 1) {
  7329. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1);
  7330. }
  7331. }
  7332. float scale = 1.0f;
  7333. float max_bias = 0.0f;
  7334. float logit_softcap = 0.0f;
  7335. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  7336. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  7337. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  7338. if (logit_softcap != 0) {
  7339. scale /= logit_softcap;
  7340. }
  7341. const uint32_t n_head_kv = neq2;
  7342. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  7343. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  7344. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  7345. vk_subbuffer q_buf = ggml_vk_tensor_subbuffer(ctx, q);
  7346. vk_subbuffer k_buf = ggml_vk_tensor_subbuffer(ctx, k);
  7347. vk_subbuffer v_buf = ggml_vk_tensor_subbuffer(ctx, v);
  7348. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  7349. vk_subbuffer mask_buf = mask ? ggml_vk_tensor_subbuffer(ctx, mask) : q_buf;
  7350. vk_subbuffer sinks_buf = sinks ? ggml_vk_tensor_subbuffer(ctx, sinks) : q_buf;
  7351. uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | ((mask != nullptr) << 16) | n_head_log2;
  7352. const vk_flash_attn_push_constants pc = { N, KV,
  7353. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  7354. (uint32_t)neq2, (uint32_t)neq3,
  7355. (uint32_t)nek2, (uint32_t)nek3,
  7356. (uint32_t)nev2, (uint32_t)nev3,
  7357. nem1, nem2, nem3,
  7358. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  7359. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  7360. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  7361. scale, max_bias, logit_softcap,
  7362. mask_n_head_log2, m0, m1,
  7363. gqa_ratio, split_kv, split_k };
  7364. if (split_k > 1) {
  7365. if (ctx->prealloc_split_k_need_sync) {
  7366. ggml_vk_sync_buffers(ctx, subctx);
  7367. }
  7368. vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  7369. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7370. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf},
  7371. // We only use split_k when group query attention is enabled, which means
  7372. // there's no more than one tile of rows (i.e. workgroups_x would have been
  7373. // one). We reuse workgroups_x to mean the number of splits, so we need to
  7374. // cancel out the divide by wg_denoms[0].
  7375. pc, { workgroups_x * pipeline->wg_denoms[0], workgroups_y, workgroups_z });
  7376. ggml_vk_sync_buffers(ctx, subctx);
  7377. const std::array<uint32_t, 5> pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne3, split_k, (sinks != nullptr) };
  7378. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce,
  7379. {split_k_buf, sinks_buf, dst_buf},
  7380. pc2, { (uint32_t)ne1, HSV, (uint32_t)ne3 });
  7381. ctx->prealloc_split_k_need_sync = true;
  7382. } else {
  7383. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7384. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf},
  7385. pc, { workgroups_x, workgroups_y, workgroups_z });
  7386. }
  7387. }
  7388. static vk_conv_shapes ggml_vk_conv_select_shape(ggml_backend_vk_context * ctx, uint32_t K, uint32_t NPQ) {
  7389. auto n_tiles = [&](vk_conv_shapes s) {
  7390. return CEIL_DIV(K, vk_conv_block_sizes[s].K)
  7391. * CEIL_DIV(NPQ, vk_conv_block_sizes[s].NPQ);
  7392. };
  7393. // We can't query number of shader cores on Intel, use 32 as a placeholder
  7394. // so small convolutions will still choose a smaller tile.
  7395. const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32;
  7396. if (K > 64 && n_tiles(CONV_SHAPE_128x128) >= shader_core_count * 2) {
  7397. return CONV_SHAPE_128x128;
  7398. } else if (K <= 32 && n_tiles(CONV_SHAPE_32x256) >= shader_core_count * 2) {
  7399. return CONV_SHAPE_32x256;
  7400. } else {
  7401. return CONV_SHAPE_64x32;
  7402. }
  7403. }
  7404. 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) {
  7405. switch (op) {
  7406. case GGML_OP_GET_ROWS:
  7407. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  7408. if (src0->type == GGML_TYPE_I32) {
  7409. // i32 src only supports i32 result
  7410. GGML_ASSERT(dst->type == GGML_TYPE_I32);
  7411. return ctx->device->pipeline_get_rows[src0->type];
  7412. }
  7413. if (dst->type == GGML_TYPE_F16) {
  7414. return ctx->device->pipeline_get_rows[src0->type];
  7415. }
  7416. if (dst->type == GGML_TYPE_F32) {
  7417. return ctx->device->pipeline_get_rows_f32[src0->type];
  7418. }
  7419. return nullptr;
  7420. case GGML_OP_ACC:
  7421. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7422. return ctx->device->pipeline_acc_f32;
  7423. }
  7424. return nullptr;
  7425. case GGML_OP_ADD:
  7426. case GGML_OP_SUB:
  7427. case GGML_OP_MUL:
  7428. case GGML_OP_DIV:
  7429. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7430. (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
  7431. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
  7432. return nullptr;
  7433. }
  7434. switch (op) {
  7435. case GGML_OP_ADD:
  7436. {
  7437. if (ctx->num_additional_fused_ops > 0) {
  7438. if (ctx->do_add_rms_partials) {
  7439. return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops];
  7440. } else {
  7441. return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  7442. }
  7443. }
  7444. if (ctx->do_add_rms_partials) {
  7445. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_rms_norepeat : ctx->device->pipeline_add_rms;
  7446. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7447. } else {
  7448. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add;
  7449. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7450. }
  7451. }
  7452. case GGML_OP_SUB:
  7453. {
  7454. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub;
  7455. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7456. }
  7457. case GGML_OP_MUL:
  7458. {
  7459. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul;
  7460. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7461. }
  7462. case GGML_OP_DIV:
  7463. {
  7464. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div;
  7465. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7466. }
  7467. default:
  7468. break;
  7469. }
  7470. return nullptr;
  7471. case GGML_OP_ADD_ID:
  7472. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) {
  7473. return ctx->device->pipeline_add_id_f32;
  7474. }
  7475. return nullptr;
  7476. case GGML_OP_CONCAT:
  7477. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7478. return ctx->device->pipeline_concat_f32;
  7479. }
  7480. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7481. return ctx->device->pipeline_concat_f16;
  7482. }
  7483. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  7484. return ctx->device->pipeline_concat_i32;
  7485. }
  7486. return nullptr;
  7487. case GGML_OP_UPSCALE:
  7488. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7489. uint32_t mode = (ggml_get_op_params_i32(dst, 0) & (0xFF | GGML_SCALE_FLAG_ANTIALIAS));
  7490. switch (mode) {
  7491. case GGML_SCALE_MODE_NEAREST:
  7492. return ctx->device->pipeline_upscale_nearest_f32;
  7493. case GGML_SCALE_MODE_BILINEAR:
  7494. return ctx->device->pipeline_upscale_bilinear_f32;
  7495. case GGML_SCALE_MODE_BICUBIC:
  7496. return ctx->device->pipeline_upscale_bicubic_f32;
  7497. case GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ANTIALIAS:
  7498. return ctx->device->pipeline_upscale_bilinear_antialias_f32;
  7499. default:
  7500. return nullptr;
  7501. }
  7502. }
  7503. return nullptr;
  7504. case GGML_OP_SCALE:
  7505. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7506. return ctx->device->pipeline_scale_f32;
  7507. }
  7508. return nullptr;
  7509. case GGML_OP_SQR:
  7510. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7511. return ctx->device->pipeline_sqr_f32;
  7512. }
  7513. return nullptr;
  7514. case GGML_OP_SQRT:
  7515. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7516. return ctx->device->pipeline_sqrt_f32;
  7517. }
  7518. return nullptr;
  7519. case GGML_OP_SIN:
  7520. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7521. return ctx->device->pipeline_sin_f32;
  7522. }
  7523. return nullptr;
  7524. case GGML_OP_COS:
  7525. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7526. return ctx->device->pipeline_cos_f32;
  7527. }
  7528. return nullptr;
  7529. case GGML_OP_LOG:
  7530. if (src0->type == dst->type &&
  7531. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7532. return ctx->device->pipeline_log[dst->type == GGML_TYPE_F16];
  7533. }
  7534. return nullptr;
  7535. case GGML_OP_TRI:
  7536. if (src0->type == dst->type &&
  7537. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7538. return ctx->device->pipeline_tri[dst->type == GGML_TYPE_F16];
  7539. }
  7540. return nullptr;
  7541. case GGML_OP_DIAG:
  7542. if (src0->type == dst->type &&
  7543. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7544. return ctx->device->pipeline_diag[dst->type == GGML_TYPE_F16];
  7545. }
  7546. return nullptr;
  7547. case GGML_OP_CLAMP:
  7548. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7549. return ctx->device->pipeline_clamp_f32;
  7550. }
  7551. return nullptr;
  7552. case GGML_OP_PAD:
  7553. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7554. return ctx->device->pipeline_pad_f32;
  7555. }
  7556. return nullptr;
  7557. case GGML_OP_ROLL:
  7558. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7559. return ctx->device->pipeline_roll_f32;
  7560. }
  7561. return nullptr;
  7562. case GGML_OP_REPEAT:
  7563. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  7564. return ctx->device->pipeline_repeat_f32;
  7565. }
  7566. return nullptr;
  7567. case GGML_OP_REPEAT_BACK:
  7568. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7569. return ctx->device->pipeline_repeat_back_f32;
  7570. }
  7571. return nullptr;
  7572. case GGML_OP_CPY:
  7573. case GGML_OP_CONT:
  7574. case GGML_OP_DUP:
  7575. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  7576. case GGML_OP_SET_ROWS:
  7577. if (src1->type == GGML_TYPE_I64) {
  7578. return ctx->device->pipeline_set_rows_i64[dst->type];
  7579. } else {
  7580. return ctx->device->pipeline_set_rows_i32[dst->type];
  7581. }
  7582. case GGML_OP_SILU_BACK:
  7583. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7584. return ctx->device->pipeline_silu_back_f32;
  7585. }
  7586. return nullptr;
  7587. case GGML_OP_NORM:
  7588. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7589. return ctx->device->pipeline_norm_f32;
  7590. }
  7591. return nullptr;
  7592. case GGML_OP_GROUP_NORM:
  7593. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7594. return ctx->device->pipeline_group_norm_f32;
  7595. }
  7596. return nullptr;
  7597. case GGML_OP_RMS_NORM:
  7598. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7599. if (ctx->do_add_rms_partials) {
  7600. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32;
  7601. } else {
  7602. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32;
  7603. }
  7604. }
  7605. return nullptr;
  7606. case GGML_OP_RMS_NORM_BACK:
  7607. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7608. return ctx->device->pipeline_rms_norm_back_f32;
  7609. }
  7610. return nullptr;
  7611. case GGML_OP_L2_NORM:
  7612. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7613. return ctx->device->pipeline_l2_norm_f32;
  7614. }
  7615. return nullptr;
  7616. case GGML_OP_UNARY:
  7617. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7618. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7619. (src0->type != dst->type)) {
  7620. return nullptr;
  7621. }
  7622. switch (ggml_get_unary_op(dst)) {
  7623. case GGML_UNARY_OP_EXP:
  7624. return ctx->device->pipeline_exp[dst->type == GGML_TYPE_F16];
  7625. case GGML_UNARY_OP_SILU:
  7626. return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16];
  7627. case GGML_UNARY_OP_GELU:
  7628. return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16];
  7629. case GGML_UNARY_OP_GELU_ERF:
  7630. return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16];
  7631. case GGML_UNARY_OP_GELU_QUICK:
  7632. return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16];
  7633. case GGML_UNARY_OP_RELU:
  7634. return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16];
  7635. case GGML_UNARY_OP_XIELU:
  7636. return ctx->device->pipeline_xielu[dst->type == GGML_TYPE_F16];
  7637. case GGML_UNARY_OP_NEG:
  7638. return ctx->device->pipeline_neg[dst->type == GGML_TYPE_F16];
  7639. case GGML_UNARY_OP_TANH:
  7640. return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16];
  7641. case GGML_UNARY_OP_SIGMOID:
  7642. return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16];
  7643. case GGML_UNARY_OP_HARDSIGMOID:
  7644. return ctx->device->pipeline_hardsigmoid[dst->type == GGML_TYPE_F16];
  7645. case GGML_UNARY_OP_HARDSWISH:
  7646. return ctx->device->pipeline_hardswish[dst->type == GGML_TYPE_F16];
  7647. case GGML_UNARY_OP_ABS:
  7648. return ctx->device->pipeline_abs[dst->type == GGML_TYPE_F16];
  7649. case GGML_UNARY_OP_SOFTPLUS:
  7650. return ctx->device->pipeline_softplus[dst->type == GGML_TYPE_F16];
  7651. case GGML_UNARY_OP_STEP:
  7652. return ctx->device->pipeline_step[dst->type == GGML_TYPE_F16];
  7653. case GGML_UNARY_OP_ROUND:
  7654. return ctx->device->pipeline_round[dst->type == GGML_TYPE_F16];
  7655. case GGML_UNARY_OP_CEIL:
  7656. return ctx->device->pipeline_ceil[dst->type == GGML_TYPE_F16];
  7657. case GGML_UNARY_OP_FLOOR:
  7658. return ctx->device->pipeline_floor[dst->type == GGML_TYPE_F16];
  7659. case GGML_UNARY_OP_TRUNC:
  7660. return ctx->device->pipeline_trunc[dst->type == GGML_TYPE_F16];
  7661. default:
  7662. break;
  7663. }
  7664. return nullptr;
  7665. case GGML_OP_GLU:
  7666. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7667. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7668. (src0->type != dst->type)) {
  7669. return nullptr;
  7670. }
  7671. switch (ggml_get_glu_op(dst)) {
  7672. case GGML_GLU_OP_GEGLU:
  7673. return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16];
  7674. case GGML_GLU_OP_REGLU:
  7675. return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16];
  7676. case GGML_GLU_OP_SWIGLU:
  7677. return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16];
  7678. case GGML_GLU_OP_SWIGLU_OAI:
  7679. return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16];
  7680. case GGML_GLU_OP_GEGLU_ERF:
  7681. return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16];
  7682. case GGML_GLU_OP_GEGLU_QUICK:
  7683. return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16];
  7684. default:
  7685. break;
  7686. }
  7687. return nullptr;
  7688. case GGML_OP_DIAG_MASK_INF:
  7689. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7690. return ctx->device->pipeline_diag_mask_inf_f32;
  7691. }
  7692. return nullptr;
  7693. case GGML_OP_SOFT_MAX:
  7694. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  7695. GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32);
  7696. if (ctx->num_additional_fused_ops) {
  7697. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7698. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7699. // use n_experts from push constant if it's not equal to the power of two spec constant
  7700. bool use_push = dst->ne[0] != (1u << idx);
  7701. return ctx->device->pipeline_topk_moe[idx][use_push];
  7702. }
  7703. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  7704. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  7705. }
  7706. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7707. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  7708. }
  7709. return nullptr;
  7710. case GGML_OP_SOFT_MAX_BACK:
  7711. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7712. return ctx->device->pipeline_soft_max_back_f32;
  7713. }
  7714. return nullptr;
  7715. case GGML_OP_ROPE:
  7716. case GGML_OP_ROPE_BACK:
  7717. {
  7718. const ggml_tensor *rope = ctx->num_additional_fused_ops == 2 ? dst->src[0]->src[0] : dst;
  7719. const int mode = ((const int32_t *) rope->op_params)[2];
  7720. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  7721. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  7722. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  7723. if (is_neox) {
  7724. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7725. return ctx->device->pipeline_rope_neox_f32;
  7726. }
  7727. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7728. return ctx->device->pipeline_rope_neox_f32_f16;
  7729. }
  7730. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7731. return ctx->device->pipeline_rope_neox_f16;
  7732. }
  7733. } else if (is_mrope && !is_vision) {
  7734. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7735. return ctx->device->pipeline_rope_multi_f32;
  7736. }
  7737. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7738. return ctx->device->pipeline_rope_multi_f32_f16;
  7739. }
  7740. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7741. return ctx->device->pipeline_rope_multi_f16;
  7742. }
  7743. } else if (is_vision) {
  7744. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7745. return ctx->device->pipeline_rope_vision_f32;
  7746. }
  7747. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7748. return ctx->device->pipeline_rope_vision_f16;
  7749. }
  7750. } else {
  7751. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7752. return ctx->device->pipeline_rope_norm_f32;
  7753. }
  7754. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7755. return ctx->device->pipeline_rope_norm_f32_f16;
  7756. }
  7757. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7758. return ctx->device->pipeline_rope_norm_f16;
  7759. }
  7760. }
  7761. return nullptr;
  7762. }
  7763. case GGML_OP_SUM:
  7764. case GGML_OP_SUM_ROWS:
  7765. case GGML_OP_MEAN:
  7766. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7767. return ctx->device->pipeline_sum_rows_f32;
  7768. }
  7769. return nullptr;
  7770. case GGML_OP_CUMSUM:
  7771. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7772. if (src0->ne[0] <= 512) {
  7773. return ctx->device->pipeline_cumsum_small_f32;
  7774. } else {
  7775. return ctx->device->pipeline_cumsum_f32;
  7776. }
  7777. }
  7778. return nullptr;
  7779. case GGML_OP_SOLVE_TRI:
  7780. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7781. vk_solve_tri_pipeline_state solve_tri_pipeline_state(src0->ne[0], src1->ne[0]);
  7782. vk_pipeline pipeline = nullptr;
  7783. {
  7784. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7785. auto it = ctx->device->pipeline_solve_tri_f32.find(solve_tri_pipeline_state);
  7786. if (it != ctx->device->pipeline_solve_tri_f32.end()) {
  7787. pipeline = it->second;
  7788. } else {
  7789. ctx->device->pipeline_solve_tri_f32[solve_tri_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7790. }
  7791. }
  7792. return pipeline;
  7793. }
  7794. return nullptr;
  7795. case GGML_OP_ARGMAX:
  7796. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7797. return ctx->device->pipeline_argmax_f32;
  7798. }
  7799. return nullptr;
  7800. case GGML_OP_COUNT_EQUAL:
  7801. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) {
  7802. return ctx->device->pipeline_count_equal_i32;
  7803. }
  7804. return nullptr;
  7805. case GGML_OP_IM2COL:
  7806. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7807. return ctx->device->pipeline_im2col_f32;
  7808. }
  7809. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7810. return ctx->device->pipeline_im2col_f32_f16;
  7811. }
  7812. return nullptr;
  7813. case GGML_OP_IM2COL_3D:
  7814. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7815. return ctx->device->pipeline_im2col_3d_f32;
  7816. }
  7817. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7818. return ctx->device->pipeline_im2col_3d_f32_f16;
  7819. }
  7820. return nullptr;
  7821. case GGML_OP_TIMESTEP_EMBEDDING:
  7822. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7823. return ctx->device->pipeline_timestep_embedding_f32;
  7824. }
  7825. return nullptr;
  7826. case GGML_OP_CONV_TRANSPOSE_1D:
  7827. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7828. return ctx->device->pipeline_conv_transpose_1d_f32;
  7829. }
  7830. return nullptr;
  7831. case GGML_OP_POOL_2D:
  7832. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7833. return ctx->device->pipeline_pool2d_f32;
  7834. }
  7835. return nullptr;
  7836. case GGML_OP_RWKV_WKV6:
  7837. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7838. return ctx->device->pipeline_rwkv_wkv6_f32;
  7839. }
  7840. return nullptr;
  7841. case GGML_OP_RWKV_WKV7:
  7842. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7843. return ctx->device->pipeline_rwkv_wkv7_f32;
  7844. }
  7845. return nullptr;
  7846. case GGML_OP_SSM_SCAN:
  7847. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7848. const uint32_t d_state = src0->ne[0];
  7849. if (d_state == 128) {
  7850. return ctx->device->pipeline_ssm_scan_f32_d128;
  7851. } else if (d_state == 256) {
  7852. return ctx->device->pipeline_ssm_scan_f32_d256;
  7853. }
  7854. }
  7855. return nullptr;
  7856. case GGML_OP_SSM_CONV:
  7857. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7858. return ctx->device->pipeline_ssm_conv_f32;
  7859. }
  7860. return nullptr;
  7861. case GGML_OP_OPT_STEP_ADAMW:
  7862. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7863. return ctx->device->pipeline_opt_step_adamw_f32;
  7864. }
  7865. return nullptr;
  7866. case GGML_OP_OPT_STEP_SGD:
  7867. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7868. return ctx->device->pipeline_opt_step_sgd_f32;
  7869. }
  7870. return nullptr;
  7871. case GGML_OP_LEAKY_RELU:
  7872. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7873. return ctx->device->pipeline_leaky_relu_f32;
  7874. }
  7875. return nullptr;
  7876. case GGML_OP_CONV_2D:
  7877. case GGML_OP_CONV_TRANSPOSE_2D:
  7878. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7879. uint32_t K = dst->ne[2]; // Cout
  7880. uint32_t NPQ = dst->ne[3] * dst->ne[1] * dst->ne[0]; // N * OH * OW
  7881. vk_conv_shapes shape = ggml_vk_conv_select_shape(ctx, K, NPQ);
  7882. bool transpose = dst->op == GGML_OP_CONV_TRANSPOSE_2D;
  7883. uint32_t KW = (uint32_t)src0->ne[0];
  7884. uint32_t KH = (uint32_t)src0->ne[1];
  7885. uint32_t s0 = (uint32_t)(ggml_get_op_params_i32(dst, 0));
  7886. uint32_t s1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 1) : s0;
  7887. uint32_t p0 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 2) : 0;
  7888. uint32_t p1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 3) : 0;
  7889. uint32_t d0 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 4) : 1;
  7890. uint32_t d1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 5) : 1;
  7891. vk_conv2d_pipeline_state conv2d_pipeline_state(s0, s1, p0, p1, d0, d1, KW, KH);
  7892. std::map<vk_conv2d_pipeline_state, vk_pipeline> *pipelines = nullptr;
  7893. if (op == GGML_OP_CONV_2D) {
  7894. if (src0->type == GGML_TYPE_F32) {
  7895. pipelines = &ctx->device->pipeline_conv2d_f32[shape];
  7896. } else if (src0->type == GGML_TYPE_F16) {
  7897. pipelines = &ctx->device->pipeline_conv2d_f16_f32[shape];
  7898. }
  7899. } else if (op == GGML_OP_CONV_TRANSPOSE_2D) {
  7900. if (src0->type == GGML_TYPE_F32) {
  7901. pipelines = &ctx->device->pipeline_conv_transpose_2d_f32[shape];
  7902. } else if (src0->type == GGML_TYPE_F16) {
  7903. pipelines = &ctx->device->pipeline_conv_transpose_2d_f16_f32[shape];
  7904. }
  7905. }
  7906. vk_pipeline pipeline = nullptr;
  7907. {
  7908. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7909. auto it = pipelines->find(conv2d_pipeline_state);
  7910. if (it != pipelines->end()) {
  7911. pipeline = it->second;
  7912. } else {
  7913. (*pipelines)[conv2d_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7914. }
  7915. }
  7916. return pipeline;
  7917. }
  7918. return nullptr;
  7919. case GGML_OP_CONV_2D_DW:
  7920. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7921. if (ggml_is_contiguous(src1)) {
  7922. return ctx->device->pipeline_conv2d_dw_whcn_f32;
  7923. } else if (ggml_is_contiguous_channels(src1)) {
  7924. return ctx->device->pipeline_conv2d_dw_cwhn_f32;
  7925. }
  7926. } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7927. if (ggml_is_contiguous(src1)) {
  7928. return ctx->device->pipeline_conv2d_dw_whcn_f16_f32;
  7929. } else if (ggml_is_contiguous_channels(src1)) {
  7930. return ctx->device->pipeline_conv2d_dw_cwhn_f16_f32;
  7931. }
  7932. }
  7933. return nullptr;
  7934. case GGML_OP_ADD1:
  7935. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7936. return ctx->device->pipeline_add1_f16_f16;
  7937. }
  7938. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7939. return ctx->device->pipeline_add1_f16_f32;
  7940. }
  7941. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7942. return ctx->device->pipeline_add1_f32_f32;
  7943. }
  7944. return nullptr;
  7945. case GGML_OP_ARANGE:
  7946. if (dst->type == GGML_TYPE_F32) {
  7947. return ctx->device->pipeline_arange_f32;
  7948. }
  7949. return nullptr;
  7950. case GGML_OP_FILL:
  7951. if (dst->type == GGML_TYPE_F32) {
  7952. return ctx->device->pipeline_fill_f32;
  7953. }
  7954. return nullptr;
  7955. default:
  7956. return nullptr;
  7957. }
  7958. GGML_UNUSED(src2);
  7959. }
  7960. 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) {
  7961. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7962. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7963. p.misalign_offsets = (a_offset << 16) | d_offset;
  7964. GGML_UNUSED(src1);
  7965. GGML_UNUSED(src2);
  7966. GGML_UNUSED(src3);
  7967. }
  7968. 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) {
  7969. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7970. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7971. p.misalign_offsets = (a_offset << 16) | d_offset;
  7972. GGML_UNUSED(src1);
  7973. GGML_UNUSED(src2);
  7974. GGML_UNUSED(src3);
  7975. }
  7976. 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) {
  7977. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7978. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7979. p.misalign_offsets = (a_offset << 16) | d_offset;
  7980. GGML_UNUSED(src1);
  7981. GGML_UNUSED(src2);
  7982. GGML_UNUSED(src3);
  7983. }
  7984. 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) {
  7985. const uint32_t a_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7986. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7987. p.misalign_offsets = (a_offset << 16) | d_offset;
  7988. GGML_UNUSED(src0);
  7989. GGML_UNUSED(src2);
  7990. GGML_UNUSED(src3);
  7991. }
  7992. 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) {
  7993. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7994. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7995. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7996. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  7997. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  7998. GGML_UNUSED(src2);
  7999. GGML_UNUSED(src3);
  8000. }
  8001. 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) {
  8002. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  8003. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  8004. p.a_offset = a_offset;
  8005. p.d_offset = d_offset;
  8006. GGML_UNUSED(src1);
  8007. GGML_UNUSED(src2);
  8008. GGML_UNUSED(src3);
  8009. }
  8010. template<typename PC>
  8011. 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) {
  8012. 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];
  8013. if (src1 != nullptr) {
  8014. 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];
  8015. }
  8016. if (src2 != nullptr) {
  8017. 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];
  8018. }
  8019. if (src3 != nullptr) {
  8020. 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];
  8021. }
  8022. 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];
  8023. std::cerr << "), " << ggml_op_name(op) << ")");
  8024. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  8025. GGML_ASSERT(dst->buffer != nullptr);
  8026. const uint64_t ne00 = src0->ne[0];
  8027. const uint64_t ne01 = src0->ne[1];
  8028. const uint64_t ne02 = src0->ne[2];
  8029. const uint64_t ne03 = src0->ne[3];
  8030. const bool use_src1 = src1 != nullptr;
  8031. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  8032. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  8033. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  8034. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  8035. const bool use_src2 = src2 != nullptr;
  8036. const bool use_src3 = src3 != nullptr;
  8037. init_pushconst_fastdiv(pc);
  8038. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  8039. if (pipeline == nullptr) {
  8040. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  8041. if (src1 != nullptr) {
  8042. std::cerr << " and " << ggml_type_name(src1->type);
  8043. }
  8044. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  8045. GGML_ABORT("fatal error");
  8046. }
  8047. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8048. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0, true);
  8049. vk_subbuffer src1_buf = use_src1 ? ggml_vk_tensor_subbuffer(ctx, src1, true) : vk_subbuffer{};
  8050. vk_subbuffer src2_buf = use_src2 ? ggml_vk_tensor_subbuffer(ctx, src2, true) : vk_subbuffer{};
  8051. vk_subbuffer src3_buf = use_src3 ? ggml_vk_tensor_subbuffer(ctx, src3, true) : vk_subbuffer{};
  8052. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true);
  8053. // Compute misalignment offset for descriptors and store it in in push constants.
  8054. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, src3, dst);
  8055. std::array<uint32_t, 3> elements;
  8056. switch (op) {
  8057. case GGML_OP_NORM:
  8058. case GGML_OP_RMS_NORM_BACK:
  8059. case GGML_OP_L2_NORM:
  8060. case GGML_OP_SOFT_MAX:
  8061. case GGML_OP_SOFT_MAX_BACK:
  8062. case GGML_OP_SUM_ROWS:
  8063. case GGML_OP_CUMSUM:
  8064. case GGML_OP_MEAN:
  8065. case GGML_OP_ARGMAX:
  8066. {
  8067. const uint32_t nr = ggml_nrows(src0);
  8068. if (nr > 262144) {
  8069. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  8070. } else if (nr > 512) {
  8071. elements = { 512, CEIL_DIV(nr, 512), 1 };
  8072. } else {
  8073. elements = { nr, 1, 1 };
  8074. }
  8075. } break;
  8076. case GGML_OP_SOLVE_TRI:
  8077. {
  8078. uint32_t nr = (uint32_t)(ne02 * ne03);
  8079. if (nr > 262144) {
  8080. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  8081. } else if (nr > 512) {
  8082. elements = { 512, CEIL_DIV(nr, 512), 1 };
  8083. } else {
  8084. elements = { nr, 1, 1 };
  8085. }
  8086. }
  8087. break;
  8088. case GGML_OP_RMS_NORM:
  8089. if (ctx->do_add_rms_partials) {
  8090. // Run one element per thread, 128 threads per workgroup
  8091. elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 };
  8092. } else {
  8093. elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 };
  8094. }
  8095. break;
  8096. case GGML_OP_SUM:
  8097. // We use GGML_OP_SUM_ROWS with 1 row.
  8098. elements = { 1, 1, 1 };
  8099. break;
  8100. case GGML_OP_GROUP_NORM:
  8101. {
  8102. const uint32_t num_groups = dst->op_params[0];
  8103. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  8104. } break;
  8105. case GGML_OP_DIAG_MASK_INF:
  8106. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  8107. break;
  8108. case GGML_OP_ROPE:
  8109. case GGML_OP_ROPE_BACK:
  8110. {
  8111. uint32_t nrows = (uint32_t)ggml_nrows(src0);
  8112. uint32_t z = 1;
  8113. if (nrows > ctx->device->properties.limits.maxComputeWorkGroupCount[0]) {
  8114. z = CEIL_DIV(nrows, 32768);
  8115. nrows = 32768;
  8116. }
  8117. elements = { nrows, (uint32_t)ne00, z };
  8118. } break;
  8119. case GGML_OP_GET_ROWS:
  8120. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  8121. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  8122. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  8123. break;
  8124. case GGML_OP_ARGSORT:
  8125. GGML_ASSERT(0);
  8126. break;
  8127. case GGML_OP_IM2COL:
  8128. {
  8129. const bool is_2D = dst->op_params[6] == 1;
  8130. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  8131. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  8132. const uint32_t KW = src0->ne[0];
  8133. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  8134. const uint32_t OW = dst->ne[1];
  8135. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  8136. elements = { OW * KW * KH, OH, batch * IC };
  8137. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  8138. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  8139. } break;
  8140. case GGML_OP_IM2COL_3D:
  8141. {
  8142. const uint32_t IC = ((const uint32_t *)(dst->op_params))[9];
  8143. const uint32_t N = ne13 / IC;
  8144. const uint32_t KD = ne02;
  8145. const uint32_t KH = ne01;
  8146. const uint32_t KW = ne00;
  8147. const uint32_t OD = dst->ne[3] / N;
  8148. const uint32_t OH = dst->ne[2];
  8149. const uint32_t OW = dst->ne[1];
  8150. const uint32_t IC_KD_KH_KW = IC*KD*KH*KW;
  8151. const uint32_t N_OD_OH = N*OD*OH;
  8152. elements = { IC_KD_KH_KW, OW, N_OD_OH };
  8153. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  8154. } break;
  8155. case GGML_OP_TIMESTEP_EMBEDDING:
  8156. {
  8157. const uint32_t dim = dst->op_params[0];
  8158. uint32_t half_ceil = (dim + 1) / 2;
  8159. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  8160. } break;
  8161. case GGML_OP_CONV_TRANSPOSE_1D:
  8162. {
  8163. elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1}
  8164. } break;
  8165. case GGML_OP_POOL_2D:
  8166. {
  8167. const uint32_t N = dst->ne[3];
  8168. const uint32_t OC = dst->ne[2];
  8169. const uint32_t OH = dst->ne[1];
  8170. const uint32_t OW = dst->ne[0];
  8171. elements = { N * OC * OH * OW, 1, 1};
  8172. } break;
  8173. case GGML_OP_CONV_2D:
  8174. case GGML_OP_CONV_TRANSPOSE_2D:
  8175. if constexpr (std::is_same_v<PC, vk_op_conv2d_push_constants>) {
  8176. const uint32_t NPQ = pc.N * pc.OH * pc.OW;
  8177. const vk_conv_shapes shape = ggml_vk_conv_select_shape(ctx, pc.Cout, NPQ);
  8178. const uint32_t NPQ_blocks = CEIL_DIV(NPQ, vk_conv_block_sizes[shape].NPQ);
  8179. elements = { pc.Cout, NPQ_blocks, 1 };
  8180. if (elements[1] > 512) {
  8181. elements[2] = CEIL_DIV(elements[1], 512);
  8182. elements[1] = 512;
  8183. }
  8184. } else {
  8185. GGML_ABORT("invalid push constant type for CONV_2D");
  8186. }
  8187. break;
  8188. case GGML_OP_ADD:
  8189. case GGML_OP_SUB:
  8190. case GGML_OP_DIV:
  8191. case GGML_OP_MUL:
  8192. case GGML_OP_ADD1:
  8193. case GGML_OP_ARANGE:
  8194. case GGML_OP_FILL:
  8195. case GGML_OP_SCALE:
  8196. case GGML_OP_SQR:
  8197. case GGML_OP_SQRT:
  8198. case GGML_OP_SIN:
  8199. case GGML_OP_COS:
  8200. case GGML_OP_LOG:
  8201. case GGML_OP_TRI:
  8202. case GGML_OP_DIAG:
  8203. case GGML_OP_CLAMP:
  8204. case GGML_OP_PAD:
  8205. case GGML_OP_ROLL:
  8206. case GGML_OP_REPEAT:
  8207. case GGML_OP_REPEAT_BACK:
  8208. case GGML_OP_CPY:
  8209. case GGML_OP_CONCAT:
  8210. case GGML_OP_UPSCALE:
  8211. case GGML_OP_UNARY:
  8212. case GGML_OP_GLU:
  8213. case GGML_OP_CONV_2D_DW:
  8214. {
  8215. uint32_t ne = ggml_nelements(dst);
  8216. if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8217. // Convert from number of logical elements to 2- or 4-byte units.
  8218. ne /= ggml_blck_size(src0->type);
  8219. if ((ggml_type_size(src0->type) % 4) == 0) {
  8220. ne *= ggml_type_size(src0->type) / 4;
  8221. } else {
  8222. ne *= ggml_type_size(src0->type) / 2;
  8223. }
  8224. }
  8225. // copy_to_quant has block size of 32, and each thread does QUANT_K elements.
  8226. // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements.
  8227. // So divide by block size here before splitting into 512x512 groups.
  8228. if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8229. ne = CEIL_DIV(ne, ggml_blck_size(dst->type));
  8230. }
  8231. if (ne > 262144) {
  8232. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  8233. } else if (ne > 512) {
  8234. elements = { 512, CEIL_DIV(ne, 512), 1 };
  8235. } else {
  8236. elements = { ne, 1, 1 };
  8237. }
  8238. if (pipeline == ctx->device->pipeline_cpy_transpose_32 ||
  8239. pipeline == ctx->device->pipeline_cpy_transpose_16) {
  8240. // 32x32 tiles
  8241. elements[0] = (uint32_t)CEIL_DIV(dst->ne[0], 32);
  8242. elements[1] = (uint32_t)CEIL_DIV(dst->ne[1], 32);
  8243. elements[2] = (uint32_t)(dst->ne[2]*dst->ne[3]);
  8244. elements[0] = std::min(elements[0], ctx->device->properties.limits.maxComputeWorkGroupCount[0]);
  8245. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  8246. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  8247. }
  8248. } break;
  8249. case GGML_OP_ADD_ID:
  8250. {
  8251. elements = { (uint32_t)ne01, (uint32_t)ne02, 1 };
  8252. } break;
  8253. case GGML_OP_SET_ROWS:
  8254. {
  8255. uint32_t ne = ggml_nelements(src0);
  8256. if (ggml_is_quantized(dst->type)) {
  8257. // quants run 32 threads each doing QUANT_K elements
  8258. ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type));
  8259. } else {
  8260. // scalar types do one element per thread, running 512 threads
  8261. ne = CEIL_DIV(ne, 512);
  8262. }
  8263. if (ne > 262144) {
  8264. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  8265. } else if (ne > 512) {
  8266. elements = { 512, CEIL_DIV(ne, 512), 1 };
  8267. } else {
  8268. elements = { ne, 1, 1 };
  8269. }
  8270. }
  8271. break;
  8272. case GGML_OP_SSM_CONV:
  8273. {
  8274. const uint32_t nr = src0->ne[1];
  8275. const uint32_t n_t = dst->ne[1];
  8276. const uint32_t n_s = dst->ne[2];
  8277. elements = { nr, n_t, n_s };
  8278. }
  8279. break;
  8280. default:
  8281. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  8282. break;
  8283. }
  8284. if (op == GGML_OP_ADD || op == GGML_OP_RMS_NORM) {
  8285. vk_subbuffer a_buf = src0_buf;
  8286. if (ctx->do_add_rms_partials) {
  8287. a_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset);
  8288. }
  8289. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8290. { src0_buf, src1_buf, dst_buf, a_buf }, pc, elements);
  8291. } else if (op == GGML_OP_GLU) {
  8292. // Empty src1 is possible in glu, but the shader needs a buffer
  8293. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  8294. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc, elements);
  8295. } else if (op == GGML_OP_SOFT_MAX) {
  8296. // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer
  8297. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  8298. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  8299. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, subbuf2, dst_buf }, pc, elements);
  8300. } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) {
  8301. // Empty src2 and src3 is possible in rope, but the shader needs a buffer
  8302. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  8303. vk_subbuffer subbuf3 = use_src3 ? src3_buf : src0_buf;
  8304. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, subbuf2, dst_buf, subbuf3 }, pc, elements);
  8305. } else if (op == GGML_OP_IM2COL || op == GGML_OP_IM2COL_3D) {
  8306. if (ctx->device->shader_int64 && ctx->device->buffer_device_address) {
  8307. // buffer device address path doesn't use dst buffer
  8308. dst_buf.size = 1;
  8309. }
  8310. // im2col uses only src1 and dst buffers
  8311. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src1_buf, dst_buf }, pc, elements);
  8312. } else if (op == GGML_OP_COUNT_EQUAL) {
  8313. // count_equal assumes that destination buffer is initialized with zeroes
  8314. ggml_vk_buffer_memset_async(subctx, dst_buf.buffer, dst_buf.offset, 0, dst_buf.size);
  8315. ggml_vk_sync_buffers(ctx, subctx);
  8316. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  8317. } else if (op == GGML_OP_OPT_STEP_SGD) {
  8318. // OPT_STEP_SGD works on src0, it does not need dst
  8319. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf }, pc, elements);
  8320. } else if (use_src3) {
  8321. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, src3_buf, dst_buf }, pc, elements);
  8322. } else if (use_src2) {
  8323. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, dst_buf }, pc, elements);
  8324. } else if (use_src1) {
  8325. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  8326. } else {
  8327. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, dst_buf }, pc, elements);
  8328. }
  8329. }
  8330. 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) {
  8331. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8332. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8333. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8334. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GET_ROWS, {
  8335. (uint32_t)ggml_nelements(src0),
  8336. (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,
  8337. (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,
  8338. (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,
  8339. 0,
  8340. 0.0f, 0.0f, 0,
  8341. });
  8342. }
  8343. static void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8344. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8345. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8346. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8347. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  8348. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  8349. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  8350. int offset = dst->op_params[3] / 4; // offset in bytes
  8351. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ACC, {
  8352. (uint32_t)ggml_nelements(src0),
  8353. (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,
  8354. (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,
  8355. (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,
  8356. 0,
  8357. 0.0f, 0.0f, offset,
  8358. });
  8359. }
  8360. static void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  8361. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  8362. const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  8363. // Make a list of all the tensors used by the op.
  8364. // Last element of the list is the dest tensor.
  8365. const ggml_tensor *tensors[MAX_PARAMETER_COUNT];
  8366. uint32_t num_srcs = ctx->num_additional_fused_ops + 2;
  8367. uint32_t num_tensors = num_srcs + 1;
  8368. GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT);
  8369. tensors[0] = first_node->src[0];
  8370. tensors[1] = first_node->src[1];
  8371. for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) {
  8372. // check whether the previous result is src[0] or src[1]
  8373. if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) {
  8374. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1];
  8375. } else {
  8376. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0];
  8377. }
  8378. }
  8379. tensors[num_srcs] = dst;
  8380. vk_op_multi_add_push_constants pc;
  8381. pc.ne20 = (uint32_t)dst->ne[0];
  8382. pc.ne21 = (uint32_t)dst->ne[1];
  8383. pc.ne22 = (uint32_t)dst->ne[2];
  8384. pc.ne23 = (uint32_t)dst->ne[3];
  8385. for (uint32_t i = 0; i < num_tensors; ++i) {
  8386. const ggml_tensor *t = tensors[i];
  8387. pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float);
  8388. pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float);
  8389. pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float);
  8390. pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float);
  8391. }
  8392. pc.rms_partials = ctx->do_add_rms_partials;
  8393. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, tensors[0], tensors[1], nullptr, dst, dst->op);
  8394. if (pipeline == nullptr) {
  8395. std::cerr << "ggml_vulkan: Error: Missing multi_add";
  8396. GGML_ABORT("fatal error");
  8397. }
  8398. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8399. ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT];
  8400. vk_buffer buf[MAX_PARAMETER_COUNT];
  8401. size_t offset[MAX_PARAMETER_COUNT];
  8402. bool uma[MAX_PARAMETER_COUNT];
  8403. for (uint32_t i = 0; i < num_tensors; ++i) {
  8404. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8405. buf[i] = nullptr;
  8406. offset[i] = 0;
  8407. uma[i] = false;
  8408. if (ctx->device->uma) {
  8409. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8410. uma[i] = buf[i] != nullptr;
  8411. }
  8412. if (!uma[i]) {
  8413. buf[i] = buf_ctx[i]->dev_buffer;
  8414. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8415. }
  8416. GGML_ASSERT(buf[i] != nullptr);
  8417. }
  8418. // If any remaining descriptors are unused, just point them at src[0]
  8419. for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) {
  8420. buf[i] = buf[0];
  8421. offset[i] = 0;
  8422. }
  8423. if (ctx->do_add_rms_partials) {
  8424. buf[num_tensors] = ctx->prealloc_add_rms_partials;
  8425. offset[num_tensors] = ctx->prealloc_size_add_rms_partials_offset;
  8426. }
  8427. std::array<uint32_t, 3> elements;
  8428. uint32_t ne = ggml_nelements(dst);
  8429. if (ne > 262144) {
  8430. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  8431. } else if (ne > 512) {
  8432. elements = { 512, CEIL_DIV(ne, 512), 1 };
  8433. } else {
  8434. elements = { ne, 1, 1 };
  8435. }
  8436. static_assert(MAX_PARAMETER_COUNT == 12);
  8437. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8438. {
  8439. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8440. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8441. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8442. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8443. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8444. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8445. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8446. ggml_vk_subbuffer(ctx, buf[7], offset[7]),
  8447. ggml_vk_subbuffer(ctx, buf[8], offset[8]),
  8448. ggml_vk_subbuffer(ctx, buf[9], offset[9]),
  8449. ggml_vk_subbuffer(ctx, buf[10], offset[10]),
  8450. ggml_vk_subbuffer(ctx, buf[11], offset[11]),
  8451. }, pc, elements);
  8452. }
  8453. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8454. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8455. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8456. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8457. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD, {
  8458. (uint32_t)ggml_nelements(src0),
  8459. (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,
  8460. (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,
  8461. (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,
  8462. 0,
  8463. 0.0f, 0.0f, ctx->do_add_rms_partials,
  8464. });
  8465. }
  8466. static void ggml_vk_sub(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8467. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8468. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8469. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8470. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SUB, {
  8471. (uint32_t)ggml_nelements(src0),
  8472. (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,
  8473. (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,
  8474. (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,
  8475. 0,
  8476. 0.0f, 0.0f, 0,
  8477. });
  8478. }
  8479. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8480. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8481. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8482. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8483. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_MUL, {
  8484. (uint32_t)ggml_nelements(src0),
  8485. (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,
  8486. (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,
  8487. (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,
  8488. 0,
  8489. 0.0f, 0.0f, 0,
  8490. });
  8491. }
  8492. static void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8493. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8494. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8495. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8496. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_DIV, {
  8497. (uint32_t)ggml_nelements(src0),
  8498. (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,
  8499. (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,
  8500. (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,
  8501. 0,
  8502. 0.0f, 0.0f, 0,
  8503. });
  8504. }
  8505. 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) {
  8506. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8507. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8508. const uint32_t src2_type_size = ggml_type_size(src2->type);
  8509. ggml_vk_op_f32<vk_op_add_id_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_ADD_ID, {
  8510. (uint32_t)dst->ne[0],
  8511. (uint32_t)dst->ne[1],
  8512. (uint32_t)src0->nb[1] / src0_type_size,
  8513. (uint32_t)src0->nb[2] / src0_type_size,
  8514. (uint32_t)src1->nb[1] / src1_type_size,
  8515. (uint32_t)src2->nb[1] / src2_type_size,
  8516. });
  8517. }
  8518. 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) {
  8519. GGML_ASSERT(version == 6 || version == 7);
  8520. int num_srcs = version == 6 ? 6 : 7;
  8521. for (int i = 0; i < num_srcs; i++) {
  8522. GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type));
  8523. }
  8524. GGML_ASSERT(dst->buffer != nullptr);
  8525. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op);
  8526. GGML_ASSERT(pipeline != nullptr);
  8527. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8528. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8529. vk_subbuffer src_buf[7] = {};
  8530. for (int i = 0; i < num_srcs; i++) {
  8531. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8532. }
  8533. std::array<uint32_t, 3> elements = {
  8534. (uint32_t)(pc.B * pc.H),
  8535. 1,
  8536. 1
  8537. };
  8538. if (version == 6) {
  8539. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8540. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf},
  8541. pc, elements);
  8542. } else if (version == 7) {
  8543. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8544. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8545. pc, elements);
  8546. } else {
  8547. // shouldn't happen
  8548. GGML_ASSERT(false);
  8549. }
  8550. }
  8551. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8552. const size_t seq_length = dst->src[0]->ne[2];
  8553. const size_t n_embed = dst->ne[0];
  8554. const size_t n_heads = dst->src[0]->ne[1];
  8555. const size_t n_seqs = dst->src[5]->ne[1];
  8556. ggml_vk_op_f32_wkv(
  8557. ctx, subctx, dst,
  8558. {
  8559. (uint32_t)n_seqs,
  8560. (uint32_t)seq_length,
  8561. (uint32_t)n_embed,
  8562. (uint32_t)n_heads,
  8563. },
  8564. 6
  8565. );
  8566. }
  8567. static void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8568. const size_t seq_length = dst->src[0]->ne[2];
  8569. const size_t n_embed = dst->ne[0];
  8570. const size_t n_heads = dst->src[0]->ne[1];
  8571. const size_t n_seqs = dst->src[6]->ne[1];
  8572. ggml_vk_op_f32_wkv(
  8573. ctx, subctx, dst,
  8574. {
  8575. (uint32_t)n_seqs,
  8576. (uint32_t)seq_length,
  8577. (uint32_t)n_embed,
  8578. (uint32_t)n_heads,
  8579. },
  8580. 7
  8581. );
  8582. }
  8583. static void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8584. const ggml_tensor * src0 = dst->src[0];
  8585. const ggml_tensor * src1 = dst->src[1];
  8586. const ggml_tensor * src2 = dst->src[2];
  8587. const ggml_tensor * src3 = dst->src[3];
  8588. const ggml_tensor * src4 = dst->src[4];
  8589. const ggml_tensor * src5 = dst->src[5];
  8590. GGML_ASSERT(dst->buffer != nullptr);
  8591. const uint32_t head_dim = src0->ne[1];
  8592. const uint32_t n_head = src1->ne[1];
  8593. const uint32_t n_group = src4->ne[1];
  8594. const uint32_t n_tok = src1->ne[2];
  8595. const uint32_t n_seq = src1->ne[3];
  8596. bool is_mamba2 = (src3->nb[1] == sizeof(float));
  8597. GGML_ASSERT(is_mamba2);
  8598. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op);
  8599. GGML_ASSERT(pipeline != nullptr);
  8600. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8601. const int64_t s_off = ggml_nelements(src1) * sizeof(float);
  8602. const vk_op_ssm_scan_push_constants pc = {
  8603. (uint32_t)src0->nb[2], (uint32_t)src0->nb[3],
  8604. (uint32_t)src1->nb[2], (uint32_t)src1->nb[3],
  8605. (uint32_t)src2->nb[1], (uint32_t)src2->nb[2],
  8606. (uint32_t)src3->nb[1],
  8607. (uint32_t)src4->nb[2], (uint32_t)src4->nb[3],
  8608. (uint32_t)src5->nb[2], (uint32_t)src5->nb[3],
  8609. (uint32_t)s_off,
  8610. n_head, head_dim, n_group, n_tok
  8611. };
  8612. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8613. vk_subbuffer src_buf[7] = {};
  8614. for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
  8615. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8616. }
  8617. std::array<uint32_t, 3> elements;
  8618. const uint32_t d_state = src0->ne[0];
  8619. uint32_t num_subgroups = d_state / ctx->device->subgroup_size;
  8620. const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, num_subgroups);
  8621. const uint32_t num_workgroups_y = n_seq;
  8622. elements = { num_workgroups_x, num_workgroups_y, 1 };
  8623. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8624. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8625. pc, elements);
  8626. }
  8627. static void ggml_vk_ssm_conv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8628. const ggml_tensor * src0 = dst->src[0];
  8629. const ggml_tensor * src1 = dst->src[1];
  8630. ggml_vk_op_f32<vk_op_ssm_conv_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SSM_CONV, {
  8631. (uint32_t)src0->nb[1], (uint32_t)src0->nb[2],
  8632. (uint32_t)src1->nb[1],
  8633. (uint32_t)dst->nb[0], (uint32_t)dst->nb[1], (uint32_t)dst->nb[2],
  8634. (uint32_t)src1->ne[0],
  8635. (uint32_t)src0->ne[0],
  8636. (uint32_t)src0->ne[1],
  8637. (uint32_t)dst->ne[1],
  8638. (uint32_t)dst->ne[2],
  8639. });
  8640. }
  8641. 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) {
  8642. const ggml_tensor * x = dst->src[0];
  8643. const ggml_tensor * g = dst->src[1];
  8644. const ggml_tensor * gm = dst->src[2];
  8645. const ggml_tensor * gv = dst->src[3];
  8646. const ggml_tensor * p = dst->src[4];
  8647. GGML_ASSERT(x->type == GGML_TYPE_F32);
  8648. GGML_ASSERT(g->type == GGML_TYPE_F32);
  8649. GGML_ASSERT(gm->type == GGML_TYPE_F32);
  8650. GGML_ASSERT(gv->type == GGML_TYPE_F32);
  8651. GGML_ASSERT(p->type == GGML_TYPE_F32);
  8652. GGML_ASSERT(dst->buffer != nullptr);
  8653. GGML_ASSERT(ggml_is_contiguous(x));
  8654. GGML_ASSERT(ggml_is_contiguous(g));
  8655. GGML_ASSERT(ggml_is_contiguous(gm));
  8656. GGML_ASSERT(ggml_is_contiguous(gv));
  8657. GGML_ASSERT(ggml_is_contiguous(p));
  8658. GGML_ASSERT(ggml_are_same_shape(x, g));
  8659. GGML_ASSERT(ggml_are_same_shape(x, gm));
  8660. GGML_ASSERT(ggml_are_same_shape(x, gv));
  8661. GGML_ASSERT(ggml_nelements(p) == 7);
  8662. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW);
  8663. GGML_ASSERT(pipeline != nullptr);
  8664. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8665. vk_subbuffer x_buf = ggml_vk_tensor_subbuffer(ctx, x);
  8666. vk_subbuffer g_buf = ggml_vk_tensor_subbuffer(ctx, g);
  8667. vk_subbuffer gm_buf = ggml_vk_tensor_subbuffer(ctx, gm);
  8668. vk_subbuffer gv_buf = ggml_vk_tensor_subbuffer(ctx, gv);
  8669. vk_subbuffer p_buf = ggml_vk_tensor_subbuffer(ctx, p);
  8670. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(x), 1, 1 };
  8671. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8672. {x_buf, g_buf, gm_buf, gv_buf, p_buf},
  8673. pc, elements);
  8674. }
  8675. static void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8676. const size_t n = ggml_nelements(dst->src[0]);
  8677. ggml_vk_op_f32_opt_step_adamw(
  8678. ctx, subctx, dst,
  8679. { (uint32_t)n, 0, 0.0f, 0.0f, 0.0f, 0.0f }
  8680. );
  8681. }
  8682. 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) {
  8683. const size_t n = ggml_nelements(dst->src[0]);
  8684. 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 });
  8685. }
  8686. static void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8687. int * op_params = (int *)dst->op_params;
  8688. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8689. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8690. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8691. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONCAT, {
  8692. (uint32_t)ggml_nelements(dst),
  8693. (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,
  8694. (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,
  8695. (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,
  8696. 0,
  8697. 0.0f, 0.0f, op_params[0],
  8698. });
  8699. }
  8700. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8701. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8702. const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0);
  8703. GGML_TENSOR_UNARY_OP_LOCALS
  8704. float sf0 = (float)ne0 / ne00;
  8705. float sf1 = (float)ne1 / ne01;
  8706. float sf2 = (float)ne2 / ne02;
  8707. float sf3 = (float)ne3 / ne03;
  8708. float pixel_offset = 0.5f;
  8709. if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) {
  8710. sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0;
  8711. sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1;
  8712. pixel_offset = 0.0f;
  8713. }
  8714. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  8715. (uint32_t)ggml_nelements(dst), 0, 0,
  8716. (uint32_t)ne00, (uint32_t)ne01,
  8717. (uint32_t)nb00 / src0_type_size, (uint32_t)nb01 / src0_type_size, (uint32_t)nb02 / src0_type_size, (uint32_t)nb03 / src0_type_size,
  8718. (uint32_t)ne0, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  8719. sf0, sf1, sf2, sf3, pixel_offset
  8720. });
  8721. }
  8722. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8723. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8724. p.param1 = ggml_get_op_params_f32(dst, 0);
  8725. p.param2 = ggml_get_op_params_f32(dst, 1);
  8726. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p));
  8727. }
  8728. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8729. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst));
  8730. }
  8731. static void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8732. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst));
  8733. }
  8734. static void ggml_vk_add1(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8735. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8736. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8737. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8738. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD1, {
  8739. (uint32_t)ggml_nelements(src0),
  8740. (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,
  8741. (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,
  8742. (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,
  8743. 0,
  8744. 0.0f, 0.0f, 0,
  8745. });
  8746. }
  8747. static void ggml_vk_arange(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8748. VK_LOG_DEBUG("ggml_vk_arange(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")");
  8749. vk_op_push_constants pc = {
  8750. (uint32_t)ggml_nelements(dst),
  8751. 1,
  8752. ggml_get_op_params_f32(dst, 0),
  8753. ggml_get_op_params_f32(dst, 2),
  8754. 0.0f, 0.0f,
  8755. };
  8756. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_ARANGE);
  8757. GGML_ASSERT(pipeline != nullptr);
  8758. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8759. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
  8760. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(dst), 1, 1 };
  8761. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
  8762. }
  8763. static void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8764. VK_LOG_DEBUG("ggml_vk_fill(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")");
  8765. vk_op_push_constants pc = {
  8766. (uint32_t)ggml_nelements(dst),
  8767. 1,
  8768. ggml_get_op_params_f32(dst, 0),
  8769. 0.0f,
  8770. 0.0f, 0.0f,
  8771. };
  8772. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_FILL);
  8773. GGML_ASSERT(pipeline != nullptr);
  8774. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8775. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
  8776. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(dst), 1, 1 };
  8777. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
  8778. }
  8779. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8780. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst));
  8781. }
  8782. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8783. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst));
  8784. }
  8785. static void ggml_vk_log(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8786. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_LOG, vk_op_unary_push_constants_init(src0, dst));
  8787. }
  8788. static void ggml_vk_tri(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8789. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8790. p.param1 = ggml_get_op_params_f32(dst, 0);
  8791. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TRI, std::move(p));
  8792. }
  8793. static void ggml_vk_diag(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8794. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8795. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_DIAG, std::move(p));
  8796. }
  8797. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8798. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8799. p.param1 = ggml_get_op_params_f32(dst, 0);
  8800. p.param2 = ggml_get_op_params_f32(dst, 1);
  8801. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p));
  8802. }
  8803. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8804. vk_op_pad_push_constants p = vk_op_pad_push_constants_init(src0, dst);
  8805. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p));
  8806. }
  8807. static void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8808. const int32_t s0 = ggml_get_op_params_i32(dst, 0);
  8809. const int32_t s1 = ggml_get_op_params_i32(dst, 1);
  8810. const int32_t s2 = ggml_get_op_params_i32(dst, 2);
  8811. const int32_t s3 = ggml_get_op_params_i32(dst, 3);
  8812. const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
  8813. const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
  8814. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8815. memcpy(&p.param1, &s01_packed, sizeof(float));
  8816. memcpy(&p.param2, &s23_packed, sizeof(float));
  8817. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p));
  8818. }
  8819. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8820. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8821. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p));
  8822. }
  8823. static void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8824. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8825. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p));
  8826. }
  8827. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8828. uint32_t ne = (uint32_t)ggml_nelements(src0);
  8829. if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8830. // Convert from number of logical elements to 2- or 4-byte units.
  8831. ne /= ggml_blck_size(src0->type);
  8832. if ((ggml_type_size(src0->type) % 4) == 0) {
  8833. ne *= ggml_type_size(src0->type) / 4;
  8834. } else {
  8835. ne *= ggml_type_size(src0->type) / 2;
  8836. }
  8837. }
  8838. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne);
  8839. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p));
  8840. }
  8841. 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) {
  8842. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8843. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8844. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8845. // Skip empty skip_rows operations. For most ops the empty check at the start
  8846. // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst
  8847. // with empty srcs.
  8848. if (ggml_is_empty(src0) || ggml_is_empty(src1)) {
  8849. return;
  8850. }
  8851. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SET_ROWS, {
  8852. (uint32_t)ggml_nelements(src0),
  8853. (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,
  8854. (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,
  8855. (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,
  8856. 0,
  8857. 0.0f, 0.0f, 0,
  8858. });
  8859. }
  8860. 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) {
  8861. 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 });
  8862. }
  8863. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8864. float * op_params = (float *)dst->op_params;
  8865. 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 });
  8866. }
  8867. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8868. const int * int_op_params = (const int *)dst->op_params;
  8869. const float * float_op_params = (const float *)dst->op_params;
  8870. const uint32_t num_groups = int_op_params[0];
  8871. const float eps = float_op_params[1];
  8872. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  8873. 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 });
  8874. }
  8875. static uint32_t ggml_vk_rms_num_partials(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8876. const uint32_t ne = (uint32_t)node->ne[0];
  8877. const uint32_t denom = ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0];
  8878. const uint32_t num_partials = CEIL_DIV(ne, denom);
  8879. return num_partials;
  8880. }
  8881. static uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8882. const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node);
  8883. const uint32_t num_bytes = ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment);
  8884. return num_bytes;
  8885. }
  8886. 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) {
  8887. const int n_dims = ((const int32_t *) dst->op_params)[1];
  8888. const int mode = ((const int32_t *) dst->op_params)[2];
  8889. // const int n_ctx = ((const int32_t *) dst->op_params)[3];
  8890. const int n_ctx_orig = ((const int32_t *) dst->op_params)[4];
  8891. const float freq_base = ((const float *) dst->op_params)[5];
  8892. const float freq_scale = ((const float *) dst->op_params)[6];
  8893. const float ext_factor = ((const float *) dst->op_params)[7];
  8894. const float attn_factor = ((const float *) dst->op_params)[8];
  8895. const float beta_fast = ((const float *) dst->op_params)[9];
  8896. const float beta_slow = ((const float *) dst->op_params)[10];
  8897. int sections[4] {};
  8898. if (mode & GGML_ROPE_TYPE_MROPE) {
  8899. memcpy(sections, (const int32_t *) dst->op_params + 11, sizeof(int)*4);
  8900. }
  8901. const bool is_imrope = mode == GGML_ROPE_TYPE_IMROPE;
  8902. float corr_dims[2];
  8903. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8904. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  8905. uint32_t nb01 = src0->nb[1] / ggml_type_size(src0->type);
  8906. uint32_t nb02 = src0->nb[2] / ggml_type_size(src0->type);
  8907. vk_op_rope_push_constants rope {
  8908. (uint32_t)mode, (uint32_t)src0->ne[0], (uint32_t)ggml_nrows(src0), (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  8909. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  8910. has_ff, (uint32_t)src0->ne[2], nb01, nb02,
  8911. { sections[0], sections[1], sections[2], sections[3] }, is_imrope, backprop, set_rows_stride,
  8912. };
  8913. return rope;
  8914. }
  8915. 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) {
  8916. ggml_tensor * dst;
  8917. const ggml_tensor * src0;
  8918. const ggml_tensor * src1;
  8919. if (ctx->num_additional_fused_ops > 0) {
  8920. // fused rms_norm + mul
  8921. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8922. ggml_tensor *other_src = mul->src[0] == cgraph->nodes[node_idx + 0] ? mul->src[1] : mul->src[0];
  8923. dst = mul;
  8924. src0 = cgraph->nodes[node_idx]->src[0];
  8925. src1 = other_src;
  8926. } else {
  8927. dst = cgraph->nodes[node_idx];
  8928. src0 = src1 = dst->src[0];
  8929. }
  8930. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8931. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8932. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8933. uint32_t param3 = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0;
  8934. vk_op_binary_push_constants bin {
  8935. (uint32_t)ggml_nelements(src0),
  8936. (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,
  8937. (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,
  8938. (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,
  8939. 0,
  8940. op_params[0], 0.0f, (int32_t)param3,
  8941. };
  8942. // more than one fused op means rms_norm+mul+rope
  8943. if (ctx->num_additional_fused_ops > 1) {
  8944. static constexpr uint32_t max_tensors = 7;
  8945. const ggml_tensor *tensors[max_tensors] {};
  8946. ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  8947. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8948. ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  8949. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  8950. bool do_set_rows = ctx->num_additional_fused_ops == 4;
  8951. tensors[0] = rms->src[0];
  8952. tensors[1] = other_src;
  8953. tensors[2] = mul;
  8954. tensors[3] = rope->src[1]; // pos
  8955. tensors[4] = rope->src[2]; // ff
  8956. tensors[5] = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; // dst
  8957. tensors[6] = do_set_rows ? tensors[5]->src[1] : nullptr;
  8958. const uint32_t set_rows_stride = do_set_rows ? tensors[5]->nb[1] / ggml_type_size(tensors[5]->type) : 0;
  8959. vk_op_rms_norm_mul_rope_push_constants pc;
  8960. pc.bin = bin;
  8961. pc.rope = ggml_vk_make_rope_constants(rope, rope->src[0], tensors[4] != nullptr, false, set_rows_stride);
  8962. 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;
  8963. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8964. ggml_backend_vk_buffer_context * buf_ctx[max_tensors];
  8965. vk_buffer buf[max_tensors];
  8966. size_t offset[max_tensors];
  8967. bool uma[max_tensors];
  8968. for (uint32_t i = 0; i < max_tensors; ++i) {
  8969. if (!tensors[i]) {
  8970. // If any remaining descriptors are unused, just point them at src[0]
  8971. buf[i] = buf[0];
  8972. offset[i] = 0;
  8973. continue;
  8974. }
  8975. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8976. buf[i] = nullptr;
  8977. offset[i] = 0;
  8978. uma[i] = false;
  8979. if (ctx->device->uma) {
  8980. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8981. uma[i] = buf[i] != nullptr;
  8982. }
  8983. if (!uma[i]) {
  8984. buf[i] = buf_ctx[i]->dev_buffer;
  8985. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8986. }
  8987. GGML_ASSERT(buf[i] != nullptr);
  8988. }
  8989. std::array<uint32_t, 3> elements;
  8990. elements = { (uint32_t)rms->src[0]->ne[1], (uint32_t)rms->src[0]->ne[2], (uint32_t)rms->src[0]->ne[3] };
  8991. static_assert(max_tensors == 7);
  8992. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8993. {
  8994. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8995. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8996. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8997. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8998. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8999. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  9000. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  9001. }, pc, elements);
  9002. } else {
  9003. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM, std::move(bin));
  9004. }
  9005. if (ctx->do_add_rms_partials_offset_calculation) {
  9006. ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0);
  9007. ctx->do_add_rms_partials = false;
  9008. ctx->do_add_rms_partials_offset_calculation = false;
  9009. }
  9010. }
  9011. 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) {
  9012. float * op_params = (float *)dst->op_params;
  9013. 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 });
  9014. }
  9015. static void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9016. float * op_params = (float *)dst->op_params;
  9017. 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 });
  9018. }
  9019. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9020. 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 });
  9021. }
  9022. static void ggml_vk_xielu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9023. float * op_params = (float *)dst->op_params;
  9024. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UNARY,
  9025. {
  9026. (uint32_t)ggml_nelements(src0), 0,
  9027. op_params[1], op_params[2], op_params[3], op_params[4]
  9028. }
  9029. );
  9030. }
  9031. static void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9032. const float * op_params_f = (const float *)dst->op_params;
  9033. const bool swapped = (bool)dst->op_params[1];
  9034. const bool split = src1 != nullptr;
  9035. const float alpha = op_params_f[2];
  9036. const float limit = op_params_f[3];
  9037. GGML_ASSERT(ggml_is_contiguous(src0));
  9038. if (!split) {
  9039. GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]);
  9040. } else {
  9041. GGML_ASSERT(src0->ne[0] == src1->ne[0]);
  9042. GGML_ASSERT(src0->ne[0] == dst->ne[0]);
  9043. GGML_ASSERT(src0->type == src1->type);
  9044. }
  9045. const uint32_t mode = split ? 2 : (swapped ? 1 : 0);
  9046. ggml_vk_op_f32<vk_op_glu_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GLU,
  9047. {
  9048. (uint32_t)ggml_nelements(dst),
  9049. (uint32_t)src0->ne[0],
  9050. (uint32_t)dst->ne[0],
  9051. mode,
  9052. alpha,
  9053. limit
  9054. });
  9055. }
  9056. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9057. int32_t * op_params = (int32_t *)dst->op_params;
  9058. 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] });
  9059. }
  9060. 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) {
  9061. float * op_params = (float *)dst->op_params;
  9062. float scale = op_params[0];
  9063. float max_bias = op_params[1];
  9064. const uint32_t ncols = (uint32_t)src0->ne[0];
  9065. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  9066. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  9067. const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u;
  9068. const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u;
  9069. const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u;
  9070. const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u;
  9071. const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u;
  9072. const uint32_t n_head_kv = src0->ne[2];
  9073. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  9074. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  9075. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  9076. vk_op_soft_max_push_constants pc {
  9077. ncols,
  9078. src1 != nullptr ? nrows_y : (uint32_t)0,
  9079. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],
  9080. ne12, ne13,
  9081. nb11, nb12, nb13,
  9082. scale, max_bias,
  9083. m0, m1,
  9084. n_head_log2,
  9085. nrows_x,
  9086. src2 != nullptr
  9087. };
  9088. if (ncols <= 16384) {
  9089. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_SOFT_MAX, std::move(pc));
  9090. } else {
  9091. vk_subbuffer buf_a = ggml_vk_tensor_subbuffer(ctx, src0);
  9092. vk_subbuffer buf_b = src1 ? ggml_vk_tensor_subbuffer(ctx, src1) : buf_a;
  9093. vk_subbuffer buf_c = src2 ? ggml_vk_tensor_subbuffer(ctx, src2) : buf_a;
  9094. vk_subbuffer buf_d = ggml_vk_tensor_subbuffer(ctx, dst);
  9095. uint32_t elems_per_wg = 128 * 4;
  9096. uint32_t num_wgs = CEIL_DIV(ncols, elems_per_wg);
  9097. size_t tmp_size = num_wgs * nrows_x * sizeof(float);
  9098. if (ctx->prealloc_size_x < tmp_size) {
  9099. ctx->prealloc_size_x = tmp_size;
  9100. ggml_vk_preallocate_buffers(ctx, subctx);
  9101. }
  9102. if (ctx->prealloc_size_y < tmp_size) {
  9103. ctx->prealloc_size_y = tmp_size;
  9104. ggml_vk_preallocate_buffers(ctx, subctx);
  9105. }
  9106. if (ctx->prealloc_x_need_sync || ctx->prealloc_y_need_sync) {
  9107. ggml_vk_sync_buffers(ctx, subctx);
  9108. }
  9109. vk_subbuffer buf_x = { ctx->prealloc_x, 0, tmp_size };
  9110. vk_subbuffer buf_y = { ctx->prealloc_y, 0, tmp_size };
  9111. std::array<uint32_t, 3> elements = { num_wgs, nrows_x, 1 };
  9112. vk_pipeline pipeline1 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large1_f32_f16 : ctx->device->pipeline_soft_max_large1_f32;
  9113. vk_pipeline pipeline2 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large2_f32_f16 : ctx->device->pipeline_soft_max_large2_f32;
  9114. vk_pipeline pipeline3 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large3_f32_f16 : ctx->device->pipeline_soft_max_large3_f32;
  9115. ggml_pipeline_request_descriptor_sets(ctx, pipeline1, 1);
  9116. ggml_pipeline_request_descriptor_sets(ctx, pipeline2, 1);
  9117. ggml_pipeline_request_descriptor_sets(ctx, pipeline3, 1);
  9118. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline1, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  9119. ggml_vk_sync_buffers(ctx, subctx);
  9120. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline2, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  9121. ggml_vk_sync_buffers(ctx, subctx);
  9122. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline3, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  9123. ctx->prealloc_x_need_sync = true;
  9124. ctx->prealloc_y_need_sync = true;
  9125. }
  9126. }
  9127. 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) {
  9128. float * op_params = (float *)dst->op_params;
  9129. 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 });
  9130. }
  9131. static void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  9132. topk_moe_mode mode = ctx->fused_topk_moe_mode;
  9133. ggml_tensor * logits = cgraph->nodes[node_idx + 0]->src[0];
  9134. ggml_tensor * bias = (mode == TOPK_MOE_SIGMOID_NORM_BIAS) ? cgraph->nodes[node_idx + 2]->src[1] : logits;
  9135. ggml_tensor * weights = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  9136. ggml_tensor * ids = (mode == TOPK_MOE_SIGMOID_NORM_BIAS) ? cgraph->nodes[node_idx + 4] :
  9137. (mode == TOPK_MOE_LATE_SOFTMAX) ? cgraph->nodes[node_idx + 1] :
  9138. cgraph->nodes[node_idx + 3];
  9139. GGML_ASSERT(logits->type == GGML_TYPE_F32);
  9140. GGML_ASSERT(bias->type == GGML_TYPE_F32);
  9141. GGML_ASSERT(weights->type == GGML_TYPE_F32);
  9142. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  9143. const int n_experts = logits->ne[0];
  9144. const int n_rows = logits->ne[1];
  9145. const int n_expert_used = weights->ne[1];
  9146. GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) n_experts);
  9147. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, cgraph->nodes[node_idx], GGML_OP_SOFT_MAX);
  9148. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9149. vk_subbuffer logits_buf = ggml_vk_tensor_subbuffer(ctx, logits);
  9150. vk_subbuffer bias_buf = ggml_vk_tensor_subbuffer(ctx, bias);
  9151. vk_subbuffer weights_buf = ggml_vk_tensor_subbuffer(ctx, weights);
  9152. vk_subbuffer ids_buf = ggml_vk_tensor_subbuffer(ctx, ids);
  9153. vk_op_topk_moe_push_constants pc {};
  9154. pc.n_rows = n_rows;
  9155. pc.n_experts_push = n_experts;
  9156. pc.n_expert_used = n_expert_used;
  9157. pc.clamp_min = -std::numeric_limits<float>::infinity();
  9158. pc.clamp_max = std::numeric_limits<float>::infinity();
  9159. if (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) {
  9160. ggml_tensor * clamp = cgraph->nodes[node_idx + 7];
  9161. GGML_ASSERT(clamp->op == GGML_OP_CLAMP);
  9162. pc.clamp_min = ggml_get_op_params_f32(clamp, 0);
  9163. pc.clamp_max = ggml_get_op_params_f32(clamp, 1);
  9164. }
  9165. if (mode == TOPK_MOE_SIGMOID_NORM_BIAS) {
  9166. ggml_tensor * clamp = cgraph->nodes[node_idx + 8];
  9167. GGML_ASSERT(clamp->op == GGML_OP_CLAMP);
  9168. pc.clamp_min = ggml_get_op_params_f32(clamp, 0);
  9169. pc.clamp_max = ggml_get_op_params_f32(clamp, 1);
  9170. }
  9171. #define GATING_FUNC_SOFTMAX 0
  9172. #define GATING_FUNC_SIGMOID 1
  9173. #define GATING_FUNC_SOFTMAX_WEIGHT 2
  9174. pc.gating_func = mode == TOPK_MOE_SIGMOID_NORM_BIAS ? GATING_FUNC_SIGMOID :
  9175. mode == TOPK_MOE_LATE_SOFTMAX ? GATING_FUNC_SOFTMAX_WEIGHT :
  9176. GATING_FUNC_SOFTMAX;
  9177. pc.has_bias = mode == TOPK_MOE_SIGMOID_NORM_BIAS;
  9178. pc.with_norm = mode == TOPK_MOE_EARLY_SOFTMAX_NORM || mode == TOPK_MOE_SIGMOID_NORM_BIAS;
  9179. if (ctx->fused_topk_moe_scale) {
  9180. GGML_ASSERT(weights->op == GGML_OP_SCALE);
  9181. pc.output_scale = ggml_get_op_params_f32(weights, 0);
  9182. pc.output_bias = ggml_get_op_params_f32(weights, 1);
  9183. } else {
  9184. pc.output_scale = 1.0f;
  9185. pc.output_bias = 0.0f;
  9186. }
  9187. GGML_ASSERT(n_expert_used <= n_experts);
  9188. const uint32_t rows_per_block = 4;
  9189. std::array<uint32_t, 3> elements = { CEIL_DIV(n_rows, rows_per_block), 1, 1 };
  9190. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {logits_buf, bias_buf, weights_buf, ids_buf}, pc, elements);
  9191. }
  9192. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_cgraph * cgraph, int node_idx, bool backprop) {
  9193. ggml_tensor * dst = cgraph->nodes[node_idx];
  9194. const ggml_tensor * src0 = dst->src[0];
  9195. const ggml_tensor * src1 = dst->src[1];
  9196. const ggml_tensor * src2 = dst->src[2];
  9197. const ggml_tensor * src3 = nullptr;
  9198. const int n_dims = ((int32_t *) dst->op_params)[1];
  9199. const int mode = ((int32_t *) dst->op_params)[2];
  9200. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  9201. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  9202. const float freq_base = ((float *) dst->op_params)[5];
  9203. const float beta_fast = ((float *) dst->op_params)[9];
  9204. const float beta_slow = ((float *) dst->op_params)[10];
  9205. int sections[4] {};
  9206. if (mode & GGML_ROPE_TYPE_MROPE) {
  9207. memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4);
  9208. }
  9209. float corr_dims[2];
  9210. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  9211. uint32_t set_rows_stride = 0;
  9212. // Fused rope + view + set_rows passes the set_rows destination stride in set_rows_stride
  9213. // and overrides the dst and sets src3=row_indices
  9214. if (ctx->num_additional_fused_ops > 0) {
  9215. set_rows_stride = cgraph->nodes[node_idx + 2]->nb[1] / ggml_type_size(cgraph->nodes[node_idx + 2]->type);
  9216. src3 = cgraph->nodes[node_idx + 2]->src[1];
  9217. dst = cgraph->nodes[node_idx + 2];
  9218. }
  9219. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, src3, dst, GGML_OP_ROPE,
  9220. ggml_vk_make_rope_constants(cgraph->nodes[node_idx], src0, src2 != nullptr, backprop, set_rows_stride));
  9221. }
  9222. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9223. const uint32_t * op_params = (const uint32_t *)dst->op_params;
  9224. uint32_t ncols = src0->ne[0];
  9225. uint32_t nrows = ggml_nrows(src0);
  9226. uint32_t ncols_pad_log2 = (uint32_t)ceilf(log2f(float(ncols)));
  9227. uint32_t ncolsp2 = 1 << ncols_pad_log2;
  9228. vk_op_argsort_push_constants pc { ncols, ncolsp2, ncols_pad_log2, nrows, op_params[0], 0, 0, 0, 0, };
  9229. // Pick the largest workgroup size <= ncolsp2
  9230. uint32_t pipeline_idx = std::min(ncols_pad_log2, num_argsort_pipelines - 1);
  9231. // Use the "small" argsort shader if the whole sort can be done by a single workgroup.
  9232. bool use_small = ncols_pad_log2 <= ctx->device->max_workgroup_size_log2 &&
  9233. ctx->device->pipeline_argsort_f32[pipeline_idx] != nullptr;
  9234. vk_pipeline pipeline = use_small ? ctx->device->pipeline_argsort_f32[pipeline_idx]
  9235. : ctx->device->pipeline_argsort_large_f32[pipeline_idx];
  9236. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  9237. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  9238. vk_subbuffer subbuf1 = dst_buf;
  9239. // Reserve space for ivec2 per element, with rows padded to a power of two
  9240. if (!use_small) {
  9241. const size_t x_sz = size_t{ncolsp2} * nrows * 2 * sizeof(int);
  9242. if (ctx->prealloc_size_x < x_sz) {
  9243. ctx->prealloc_size_x = x_sz;
  9244. ggml_vk_preallocate_buffers(ctx, subctx);
  9245. }
  9246. if (ctx->prealloc_x_need_sync) {
  9247. ggml_vk_sync_buffers(ctx, subctx);
  9248. }
  9249. subbuf1 = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  9250. }
  9251. std::array<uint32_t, 3> elements;
  9252. elements[0] = ncolsp2;
  9253. elements[1] = std::min((uint32_t)ggml_nrows(src0), ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  9254. elements[2] = 1;
  9255. // First dispatch initializes tmp_idx and does the first N passes where
  9256. // there is only communication between threads in the same workgroup.
  9257. {
  9258. vk_op_argsort_push_constants pc2 = pc;
  9259. pc2.outer_start = 0;
  9260. pc2.outer_end = std::min(ncols_pad_log2, ctx->device->max_workgroup_size_log2);
  9261. pc2.inner_start = 0;
  9262. pc2.inner_end = 100;
  9263. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9264. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements);
  9265. }
  9266. if (!use_small) {
  9267. ggml_vk_sync_buffers(ctx, subctx);
  9268. // Loop over outer/inner passes, synchronizing between each pass.
  9269. for (uint32_t outer = ctx->device->max_workgroup_size_log2; outer < ncols_pad_log2; ++outer) {
  9270. for (uint32_t inner = 0; inner < outer + 1; ++inner) {
  9271. vk_op_argsort_push_constants pc2 = pc;
  9272. pc2.outer_start = outer;
  9273. pc2.outer_end = outer + 1;
  9274. pc2.inner_start = inner;
  9275. pc2.inner_end = inner + 1;
  9276. // When the inner idx is large enough, there's only communication
  9277. // within a workgroup. So the remaining inner iterations can all
  9278. // run in the same dispatch.
  9279. if (outer - inner < pipeline_idx) {
  9280. pc2.inner_end = 100;
  9281. inner = outer;
  9282. pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx];
  9283. } else {
  9284. // Smaller workgroup empirically seems to perform better
  9285. pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx - 2];
  9286. }
  9287. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9288. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements);
  9289. ggml_vk_sync_buffers(ctx, subctx);
  9290. }
  9291. }
  9292. ctx->prealloc_x_need_sync = true;
  9293. }
  9294. }
  9295. static void ggml_vk_topk(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9296. uint32_t ncols = src0->ne[0];
  9297. uint32_t nrows = ggml_nrows(src0);
  9298. uint32_t k = dst->ne[0];
  9299. vk_op_topk_push_constants pc { ncols, ncols, ncols, k, nrows, 0, 0 };
  9300. if (ctx->prealloc_x_need_sync) {
  9301. ggml_vk_sync_buffers(ctx, subctx);
  9302. }
  9303. std::array<uint32_t, 3> elements;
  9304. elements[1] = std::min(nrows, ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  9305. elements[2] = 1;
  9306. uint32_t num_elements = ncols;
  9307. // Each iteration reduces a workgroup's worth of elements down to the K
  9308. // largest elements. Repeat until we have the top K elements.
  9309. // Need to do at least one iteration to write out the results.
  9310. bool done_one_iter = false;
  9311. uint32_t dbl_buf_index = 0;
  9312. size_t dbl_buf_size;
  9313. while (num_elements > k || !done_one_iter) {
  9314. // Prefer going as small as num_topk_pipelines - 3 for perf reasons.
  9315. // But if K is larger, then we need a larger workgroup
  9316. uint32_t max_pipeline = num_topk_pipelines - 1;
  9317. uint32_t preferred_pipeline = std::max(num_topk_pipelines - 3, (uint32_t)log2f(float(k)) + 2);
  9318. max_pipeline = std::min(preferred_pipeline, max_pipeline);
  9319. uint32_t min_pipeline = (uint32_t)log2f(float(k)) + 1;
  9320. // require full subgroup
  9321. min_pipeline = std::max(min_pipeline, ctx->device->subgroup_size_log2);
  9322. uint32_t pipeline_idx = (uint32_t)ceilf(log2f(float(num_elements)));
  9323. pipeline_idx = std::min(pipeline_idx, max_pipeline);
  9324. pipeline_idx = std::max(pipeline_idx, min_pipeline);
  9325. if (num_elements > (1u << pipeline_idx)) {
  9326. // If we could finish on this loop iteration (i.e. a single workgroup)
  9327. // then do so. It's better than the overhead of another pass.
  9328. for (uint32_t i = pipeline_idx; i < num_topk_pipelines; ++i) {
  9329. if (num_elements <= (1u << i)) {
  9330. pipeline_idx = i;
  9331. break;
  9332. }
  9333. }
  9334. }
  9335. vk_pipeline pipeline = ctx->device->pipeline_topk_f32[pipeline_idx];
  9336. // If the device doesn't support a pipeline this large, use smaller
  9337. while (!pipeline) {
  9338. pipeline_idx--;
  9339. GGML_ASSERT(pipeline_idx >= min_pipeline);
  9340. pipeline = ctx->device->pipeline_topk_f32[pipeline_idx];
  9341. }
  9342. vk_op_topk_push_constants pc2 = pc;
  9343. pc2.ncols_input = num_elements;
  9344. // Number of elements remaining after this pass
  9345. uint32_t num_dst_elements = (num_elements / pipeline->wg_denoms[0]) * k + std::min(k, num_elements % pipeline->wg_denoms[0]);
  9346. pc2.ncols_output = num_dst_elements;
  9347. if (!done_one_iter) {
  9348. // Reserve space for ivec2 per element, double buffered
  9349. // K per workgroup per row
  9350. dbl_buf_size = num_dst_elements * nrows * 2 * sizeof(int);
  9351. dbl_buf_size = ROUNDUP_POW2(dbl_buf_size, ctx->device->properties.limits.minStorageBufferOffsetAlignment);
  9352. const size_t x_sz = dbl_buf_size * 2;
  9353. if (ctx->prealloc_size_x < x_sz) {
  9354. ctx->prealloc_size_x = x_sz;
  9355. ggml_vk_preallocate_buffers(ctx, subctx);
  9356. }
  9357. }
  9358. vk_subbuffer src_buf;
  9359. vk_subbuffer dst_buf;
  9360. if (num_elements == ncols) {
  9361. pc2.first_pass = 1;
  9362. src_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  9363. } else {
  9364. src_buf = { ctx->prealloc_x, dbl_buf_index * dbl_buf_size, dbl_buf_size };
  9365. }
  9366. if (num_dst_elements == k) {
  9367. pc2.last_pass = 1;
  9368. dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  9369. } else {
  9370. dst_buf = { ctx->prealloc_x, (dbl_buf_index ^ 1) * dbl_buf_size, dbl_buf_size };
  9371. }
  9372. elements[0] = num_elements;
  9373. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9374. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src_buf, dst_buf }, pc2, elements);
  9375. num_elements = num_dst_elements;
  9376. dbl_buf_index ^= 1;
  9377. if (num_elements > k) {
  9378. ggml_vk_sync_buffers(ctx, subctx);
  9379. }
  9380. done_one_iter = true;
  9381. }
  9382. ctx->prealloc_x_need_sync = true;
  9383. }
  9384. static void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9385. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, ggml_nelements(src0));
  9386. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM, p);
  9387. }
  9388. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9389. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9390. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, p);
  9391. }
  9392. static void ggml_vk_mean(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9393. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9394. p.weight = 1.0f / (float)src0->ne[0];
  9395. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_MEAN, p);
  9396. }
  9397. static void ggml_vk_cumsum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9398. vk_op_sum_rows_push_constants pc = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9399. // Use the single pass shader when the rows are small or there are enough rows to fill the GPU.
  9400. // For fewer, larger rows, use the multipass shader to spread each row across SMs.
  9401. if (dst->ne[0] <= 4096 || ggml_nrows(dst) >= ctx->device->shader_core_count) {
  9402. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CUMSUM, pc);
  9403. return;
  9404. }
  9405. // First pass computes partial sums within a block, and stores the last partial
  9406. // to the temp buffer. Second pass sums the block partials from the temp buffer
  9407. // and adds that to the result of the first pass.
  9408. vk_pipeline pipeline1 = ctx->device->pipeline_cumsum_multipass1_f32;
  9409. vk_pipeline pipeline2 = ctx->device->pipeline_cumsum_multipass2_f32;
  9410. GGML_ASSERT(pipeline1 != nullptr && pipeline2 != nullptr);
  9411. ggml_pipeline_request_descriptor_sets(ctx, pipeline1, 1);
  9412. ggml_pipeline_request_descriptor_sets(ctx, pipeline2, 1);
  9413. std::array<uint32_t, 3> elements;
  9414. elements[0] = dst->ne[0];
  9415. elements[1] = (uint32_t)ggml_nrows(dst);
  9416. elements[2] = 1;
  9417. size_t temp_size = sizeof(float) * elements[0] * ggml_nrows(dst);
  9418. if (ctx->prealloc_size_split_k < temp_size) {
  9419. ctx->prealloc_size_split_k = temp_size;
  9420. ggml_vk_preallocate_buffers(ctx, subctx);
  9421. }
  9422. vk_subbuffer src_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  9423. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  9424. vk_subbuffer temp_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  9425. if (ctx->prealloc_split_k_need_sync) {
  9426. ggml_vk_sync_buffers(ctx, subctx);
  9427. }
  9428. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline1, {src_buf, dst_buf, temp_buf}, pc, elements);
  9429. ggml_vk_sync_buffers(ctx, subctx);
  9430. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline2, {src_buf, dst_buf, temp_buf}, pc, elements);
  9431. ctx->prealloc_split_k_need_sync = true;
  9432. }
  9433. static void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9434. 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 });
  9435. }
  9436. 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) {
  9437. 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 });
  9438. }
  9439. 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) {
  9440. const uint32_t src0_type_size = ggml_type_size(src0->type);
  9441. const uint32_t src1_type_size = ggml_type_size(src1->type);
  9442. const uint32_t dst_type_size = ggml_type_size(dst->type);
  9443. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SOLVE_TRI, {
  9444. (uint32_t)ggml_nelements(src0),
  9445. (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,
  9446. (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,
  9447. (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,
  9448. 0,
  9449. 0.0f, 0.0f, 0,
  9450. });
  9451. }
  9452. static void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9453. const int32_t s0 = dst->op_params[0];
  9454. const int32_t s1 = dst->op_params[1];
  9455. const int32_t p0 = dst->op_params[2];
  9456. const int32_t p1 = dst->op_params[3];
  9457. const int32_t d0 = dst->op_params[4];
  9458. const int32_t d1 = dst->op_params[5];
  9459. const bool is_2D = dst->op_params[6] == 1;
  9460. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  9461. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  9462. const uint32_t IW = src1->ne[0];
  9463. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  9464. const uint32_t KW = src0->ne[0];
  9465. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  9466. const uint32_t OW = dst->ne[1];
  9467. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  9468. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  9469. const uint32_t pelements = OW * KW * KH;
  9470. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  9471. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  9472. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  9473. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  9474. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL, {
  9475. dst_addr,
  9476. batch_offset, offset_delta,
  9477. IC, IW, IH, OW, OH, KW, KH,
  9478. pelements,
  9479. IC * KH * KW,
  9480. s0, s1, p0, p1, d0, d1, batch * IC
  9481. });
  9482. }
  9483. 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) {
  9484. GGML_TENSOR_BINARY_OP_LOCALS
  9485. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  9486. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  9487. const int32_t s2 = ((const int32_t *)(dst->op_params))[2];
  9488. const int32_t p0 = ((const int32_t *)(dst->op_params))[3];
  9489. const int32_t p1 = ((const int32_t *)(dst->op_params))[4];
  9490. const int32_t p2 = ((const int32_t *)(dst->op_params))[5];
  9491. const int32_t d0 = ((const int32_t *)(dst->op_params))[6];
  9492. const int32_t d1 = ((const int32_t *)(dst->op_params))[7];
  9493. const int32_t d2 = ((const int32_t *)(dst->op_params))[8];
  9494. const int32_t IC = ((const int32_t *)(dst->op_params))[9];
  9495. const int64_t N = ne13 / IC;
  9496. const int64_t ID = ne12;
  9497. const int64_t IH = ne11;
  9498. const int64_t IW = ne10;
  9499. const int64_t KD = ne02;
  9500. const int64_t KH = ne01;
  9501. const int64_t KW = ne00;
  9502. const int64_t OD = ne3 / N;
  9503. const int64_t OH = ne2;
  9504. const int64_t OW = ne1;
  9505. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  9506. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  9507. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  9508. vk_op_im2col_3d_push_constants pc {};
  9509. pc.dst_addr = dst_addr;
  9510. pc.nb10 = nb10 / ggml_type_size(src1->type);
  9511. pc.nb11 = nb11 / ggml_type_size(src1->type);
  9512. pc.nb12 = nb12 / ggml_type_size(src1->type);
  9513. pc.nb13 = nb13 / ggml_type_size(src1->type);
  9514. pc.s0 = s0;
  9515. pc.s1 = s1;
  9516. pc.s2 = s2;
  9517. pc.p0 = p0;
  9518. pc.p1 = p1;
  9519. pc.p2 = p2;
  9520. pc.d0 = d0;
  9521. pc.d1 = d1;
  9522. pc.d2 = d2;
  9523. pc.IW = IW;
  9524. pc.IH = IH;
  9525. pc.ID = ID;
  9526. pc.IC = IC;
  9527. pc.KW = KW;
  9528. pc.OH = OH;
  9529. pc.KD_KH_KW = KD*KH*KW;
  9530. pc.KH_KW = KH*KW;
  9531. pc.IC_KD_KH_KW = IC*KD*KH*KW;
  9532. pc.N_OD_OH = N*OD*OH;
  9533. pc.OD_OH = OD*OH;
  9534. pc.OD_OH_OW_IC_KD_KH_KW = OD*OH*OW*IC*KD*KH*KW;
  9535. pc.OH_OW_IC_KD_KH_KW = OH*OW*IC*KD*KH*KW;
  9536. pc.OW_IC_KD_KH_KW = OW*IC*KD*KH*KW;
  9537. ggml_vk_op_f32<vk_op_im2col_3d_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL_3D, std::move(pc));
  9538. }
  9539. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9540. const uint32_t dim = dst->op_params[0];
  9541. const uint32_t max_period = dst->op_params[1];
  9542. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  9543. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  9544. nb1, dim, max_period,
  9545. });
  9546. }
  9547. 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) {
  9548. // src0: (K, Cout, Cin, 1) -- kernel
  9549. // src1: (L, Cin, 1, 1) -- input
  9550. // dst: (*, Cout, 1, 1)
  9551. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  9552. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  9553. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  9554. GGML_TENSOR_BINARY_OP_LOCALS
  9555. GGML_ASSERT(nb00 == sizeof(float));
  9556. GGML_ASSERT(nb10 == sizeof(float));
  9557. const int32_t s0 = dst->op_params[0];
  9558. vk_op_conv_transpose_1d_push_constants p{};
  9559. p.Cout = static_cast<uint32_t>(ne01);
  9560. p.Cin = static_cast<uint32_t>(ne02);
  9561. p.K = static_cast<uint32_t>(ne00);
  9562. p.L = static_cast<uint32_t>(ne10);
  9563. p.KL = static_cast<uint32_t>(ne0);
  9564. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  9565. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  9566. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  9567. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  9568. p.s0 = static_cast<uint32_t>(s0);
  9569. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p));
  9570. }
  9571. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9572. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  9573. const int32_t k1 = dst->op_params[1];
  9574. const int32_t k0 = dst->op_params[2];
  9575. const int32_t s1 = dst->op_params[3];
  9576. const int32_t s0 = dst->op_params[4];
  9577. const int32_t p1 = dst->op_params[5];
  9578. const int32_t p0 = dst->op_params[6];
  9579. const uint32_t IH = src0->ne[1];
  9580. const uint32_t IW = src0->ne[0];
  9581. const uint32_t N = dst->ne[3];
  9582. const uint32_t OC = dst->ne[2];
  9583. const uint32_t OH = dst->ne[1];
  9584. const uint32_t OW = dst->ne[0];
  9585. const uint32_t parallel_elements = N * OC * OH * OW;
  9586. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  9587. IW, IH, OW, OH, OC,
  9588. parallel_elements,
  9589. op,
  9590. k0, k1, s0, s1, p0, p1,
  9591. });
  9592. }
  9593. static void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  9594. const ggml_tensor * src1, ggml_tensor * dst) {
  9595. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  9596. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  9597. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  9598. GGML_TENSOR_BINARY_OP_LOCALS
  9599. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  9600. GGML_ASSERT(nb10 == sizeof(float));
  9601. GGML_ASSERT(nb0 == sizeof(float));
  9602. bool transpose = dst->op == GGML_OP_CONV_TRANSPOSE_2D;
  9603. vk_op_conv2d_push_constants p{};
  9604. p.Cout = static_cast<uint32_t>(!transpose ? ne03 : ne02);
  9605. p.Cin = static_cast<uint32_t>(!transpose ? ne02 : ne03);
  9606. p.N = static_cast<uint32_t>(ne13);
  9607. GGML_ASSERT(p.Cout == ne2);
  9608. GGML_ASSERT(p.Cin == ne12);
  9609. p.W = static_cast<uint32_t>(ne10);
  9610. p.H = static_cast<uint32_t>(ne11);
  9611. p.OW = static_cast<uint32_t>(ne0);
  9612. p.OH = static_cast<uint32_t>(ne1);
  9613. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  9614. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  9615. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  9616. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  9617. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  9618. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  9619. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  9620. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  9621. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  9622. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, dst->op, std::move(p));
  9623. }
  9624. 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) {
  9625. vk_op_conv2d_dw_push_constants p{};
  9626. p.ne = ggml_nelements(dst);
  9627. p.channels = dst->ne[2];
  9628. p.batches = dst->ne[3];
  9629. p.dst_w = dst->ne[0];
  9630. p.dst_h = dst->ne[1];
  9631. p.src_w = src1->ne[0];
  9632. p.src_h = src1->ne[1];
  9633. p.knl_w = src0->ne[0];
  9634. p.knl_h = src0->ne[1];
  9635. p.stride_x = dst->op_params[0];
  9636. p.stride_y = dst->op_params[1];
  9637. p.pad_x = dst->op_params[2];
  9638. p.pad_y = dst->op_params[3];
  9639. p.dilation_x = dst->op_params[4];
  9640. p.dilation_y = dst->op_params[5];
  9641. GGML_ASSERT(src0->ne[3] == p.channels);
  9642. GGML_ASSERT(src1->ne[3] == p.batches);
  9643. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p));
  9644. }
  9645. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9646. const float * op_params = (const float *)dst->op_params;
  9647. 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 });
  9648. }
  9649. #ifdef GGML_VULKAN_RUN_TESTS
  9650. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  9651. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  9652. return;
  9653. }
  9654. i0 = std::max(i0, 5);
  9655. i1 = std::max(i1, 5);
  9656. i2 = std::max(i2, 0);
  9657. fprintf(stderr, " ");
  9658. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9659. fprintf(stderr, "%7d ", idx1);
  9660. }
  9661. fprintf(stderr, "\n");
  9662. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9663. fprintf(stderr, "%7d: ", idx0);
  9664. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9665. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  9666. float val;
  9667. if (type == GGML_TYPE_F32) {
  9668. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  9669. } else if (type == GGML_TYPE_F16) {
  9670. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  9671. } else {
  9672. GGML_ABORT("fatal error");
  9673. }
  9674. fprintf(stderr, "% 7.2f ", val);
  9675. } else {
  9676. fprintf(stderr, " ");
  9677. }
  9678. }
  9679. fprintf(stderr, "\n");
  9680. }
  9681. }
  9682. template <typename X_TYPE, typename Y_TYPE>
  9683. 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) {
  9684. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  9685. const size_t x_ne = m * k * batch;
  9686. const size_t y_ne = k * n * batch;
  9687. const size_t d_ne = m * n * batch;
  9688. vk_pipeline p;
  9689. std::string shname;
  9690. if (shader_size == 0) {
  9691. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9692. p = ctx->device->pipeline_matmul_f32->a_s;
  9693. shname = "F32_ALIGNED_S";
  9694. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9695. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  9696. shname = "F32_F16_ALIGNED_S";
  9697. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9698. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  9699. shname = "F16_F32_ALIGNED_S";
  9700. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9701. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  9702. shname = "F16_ALIGNED_S";
  9703. } else {
  9704. GGML_ABORT("fatal error");
  9705. }
  9706. } else if (shader_size == 1) {
  9707. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9708. p = ctx->device->pipeline_matmul_f32->a_m;
  9709. shname = "F32_ALIGNED_M";
  9710. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9711. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  9712. shname = "F32_F16_ALIGNED_M";
  9713. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9714. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  9715. shname = "F16_F32_ALIGNED_M";
  9716. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9717. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  9718. shname = "F16_ALIGNED_M";
  9719. } else {
  9720. GGML_ABORT("fatal error");
  9721. }
  9722. } else if (shader_size == 2) {
  9723. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9724. p = ctx->device->pipeline_matmul_f32->a_l;
  9725. shname = "F32_ALIGNED_L";
  9726. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9727. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  9728. shname = "F32_F16_ALIGNED_L";
  9729. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9730. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  9731. shname = "F16_F32_ALIGNED_L";
  9732. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9733. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  9734. shname = "F16_ALIGNED_L";
  9735. } else {
  9736. GGML_ABORT("fatal error");
  9737. }
  9738. } else {
  9739. GGML_ASSERT(0);
  9740. }
  9741. const size_t kpad = ggml_vk_align_size(k, p->align);
  9742. if (k != kpad) {
  9743. if (shader_size == 0) {
  9744. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9745. p = ctx->device->pipeline_matmul_f32->s;
  9746. shname = "F32_S";
  9747. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9748. p = ctx->device->pipeline_matmul_f32_f16->s;
  9749. shname = "F32_F16_S";
  9750. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9751. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  9752. shname = "F16_F32_S";
  9753. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9754. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  9755. shname = "F16_S";
  9756. }
  9757. } else if (shader_size == 1) {
  9758. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9759. p = ctx->device->pipeline_matmul_f32->m;
  9760. shname = "F32_M";
  9761. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9762. p = ctx->device->pipeline_matmul_f32_f16->m;
  9763. shname = "F32_F16_M";
  9764. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9765. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  9766. shname = "F16_F32_M";
  9767. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9768. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  9769. shname = "F16_M";
  9770. }
  9771. } else if (shader_size == 2) {
  9772. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9773. p = ctx->device->pipeline_matmul_f32->l;
  9774. shname = "F32_L";
  9775. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9776. p = ctx->device->pipeline_matmul_f32_f16->l;
  9777. shname = "F32_F16_L";
  9778. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9779. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  9780. shname = "F16_F32_L";
  9781. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9782. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  9783. shname = "F16_L";
  9784. }
  9785. }
  9786. }
  9787. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9788. if (split_k > 1) {
  9789. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9790. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9791. // Resize buffer
  9792. if (ctx->prealloc_split_k != nullptr) {
  9793. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9794. }
  9795. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9796. }
  9797. }
  9798. ggml_pipeline_allocate_descriptor_sets(ctx);
  9799. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9800. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9801. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9802. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  9803. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  9804. float* d = (float *) malloc(sizeof(float) * d_ne);
  9805. for (size_t i = 0; i < x_ne; i++) {
  9806. if (std::is_same<float, X_TYPE>()) {
  9807. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9808. // x[i] = 1.0f;
  9809. // x[i] = i + 1;
  9810. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9811. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9812. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9813. // x[i] = ggml_fp32_to_fp16(1.0f);
  9814. // x[i] = ggml_fp32_to_fp16(i + 1);
  9815. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9816. } else {
  9817. GGML_ABORT("fatal error");
  9818. }
  9819. }
  9820. for (size_t i = 0; i < y_ne; i++) {
  9821. if (std::is_same<float, Y_TYPE>()) {
  9822. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9823. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9824. // y[i] = i + 1;
  9825. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9826. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9827. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9828. // y[i] = ggml_fp32_to_fp16(i + 1);
  9829. } else {
  9830. GGML_ABORT("fatal error");
  9831. }
  9832. }
  9833. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  9834. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  9835. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9836. ggml_vk_ctx_begin(ctx->device, subctx);
  9837. for (size_t i = 0; i < num_it; i++) {
  9838. ggml_vk_matmul(
  9839. 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),
  9840. m, n, k,
  9841. k, k, m, k*m, k*n, m*n,
  9842. split_k, batch, batch, batch, 1, 1, n
  9843. );
  9844. }
  9845. ggml_vk_ctx_end(subctx);
  9846. auto begin = std::chrono::high_resolution_clock::now();
  9847. ggml_vk_submit(subctx, ctx->fence);
  9848. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  9849. ctx->device->device.resetFences({ ctx->fence });
  9850. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9851. auto end = std::chrono::high_resolution_clock::now();
  9852. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9853. // copy dst to host
  9854. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  9855. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  9856. ggml_init_params iparams = {
  9857. /*.mem_size =*/ 1024*1024*1024,
  9858. /*.mem_buffer =*/ NULL,
  9859. /*.no_alloc =*/ true,
  9860. };
  9861. ggml_context * ggml_ctx = ggml_init(iparams);
  9862. ggml_type src0_type;
  9863. ggml_type src1_type;
  9864. if (std::is_same<float, X_TYPE>()) {
  9865. src0_type = GGML_TYPE_F32;
  9866. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9867. src0_type = GGML_TYPE_F16;
  9868. } else {
  9869. GGML_ABORT("fatal error");
  9870. }
  9871. if (std::is_same<float, Y_TYPE>()) {
  9872. src1_type = GGML_TYPE_F32;
  9873. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9874. src1_type = GGML_TYPE_F16;
  9875. } else {
  9876. GGML_ABORT("fatal error");
  9877. }
  9878. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  9879. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  9880. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9881. src0_ggml->data = x;
  9882. src1_ggml->data = y;
  9883. tensor_ggml->data = d_chk;
  9884. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9885. ggml_build_forward_expand(cgraph, tensor_ggml);
  9886. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9887. ggml_free(ggml_ctx);
  9888. double avg_err = 0.0;
  9889. int first_err_n = -1;
  9890. int first_err_m = -1;
  9891. int first_err_b = -1;
  9892. for (size_t i = 0; i < m*n*batch; i++) {
  9893. double err = std::fabs(d[i] - d_chk[i]);
  9894. avg_err += err;
  9895. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9896. first_err_b = i / (m * n);
  9897. first_err_n = (i % (m * n)) / m;
  9898. first_err_m = (i % (m * n)) % m;
  9899. }
  9900. }
  9901. avg_err /= m * n;
  9902. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9903. 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;
  9904. if (avg_err > 0.1 || std::isnan(avg_err)) {
  9905. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9906. std::cerr << "Actual result: " << std::endl << std::endl;
  9907. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9908. std::cerr << "Expected result: " << std::endl << std::endl;
  9909. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9910. if (split_k > 1) {
  9911. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9912. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9913. std::cerr << "d_buf0: " << std::endl << std::endl;
  9914. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9915. std::cerr << "d_buf1: " << std::endl << std::endl;
  9916. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9917. std::cerr << "d_buf2: " << std::endl << std::endl;
  9918. 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);
  9919. std::cerr << "d_buf3: " << std::endl << std::endl;
  9920. 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);
  9921. free(split_k_buf);
  9922. }
  9923. }
  9924. free(d_chk);
  9925. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  9926. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  9927. ggml_vk_destroy_buffer(d_X);
  9928. ggml_vk_destroy_buffer(d_Y);
  9929. ggml_vk_destroy_buffer(d_D);
  9930. free(x);
  9931. free(y);
  9932. free(d);
  9933. }
  9934. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  9935. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  9936. return;
  9937. }
  9938. i0 = std::max(i0, 5);
  9939. i1 = std::max(i1, 5);
  9940. i2 = std::max(i2, 0);
  9941. i3 = std::max(i3, 0);
  9942. fprintf(stderr, " ");
  9943. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9944. fprintf(stderr, "%7d ", idx1);
  9945. }
  9946. fprintf(stderr, "\n");
  9947. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9948. fprintf(stderr, "%7d: ", idx0);
  9949. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9950. 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]) {
  9951. float val;
  9952. if (tensor->type == GGML_TYPE_F32) {
  9953. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  9954. } else if (tensor->type == GGML_TYPE_F16) {
  9955. 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]));
  9956. } else {
  9957. GGML_ABORT("fatal error");
  9958. }
  9959. fprintf(stderr, "% 7.2f ", val);
  9960. } else {
  9961. fprintf(stderr, " ");
  9962. }
  9963. }
  9964. fprintf(stderr, "\n");
  9965. }
  9966. }
  9967. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  9968. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  9969. }
  9970. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  9971. if (quant == GGML_TYPE_F32) {
  9972. memcpy(to, from, sizeof(float) * ne);
  9973. return;
  9974. }
  9975. const auto * tt = ggml_get_type_traits(quant);
  9976. ggml_to_float_t dequant_fn = tt->to_float;
  9977. dequant_fn(from, to, ne);
  9978. }
  9979. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9980. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  9981. const size_t x_sz = sizeof(float) * ne;
  9982. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  9983. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9984. float * x = (float *) malloc(x_sz);
  9985. void * qx = malloc(qx_sz);
  9986. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9987. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9988. float * x_ref = (float *) malloc(x_sz);
  9989. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  9990. for (size_t i = 0; i < ne; i++) {
  9991. x[i] = rand() / (float)RAND_MAX;
  9992. }
  9993. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  9994. ggml_vk_quantize_data(x, qx, ne, quant);
  9995. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  9996. ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9997. ggml_pipeline_allocate_descriptor_sets(ctx);
  9998. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9999. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10000. ggml_vk_ctx_begin(ctx->device, subctx);
  10001. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  10002. 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});
  10003. ggml_vk_ctx_end(subctx);
  10004. auto begin = std::chrono::high_resolution_clock::now();
  10005. ggml_vk_submit(subctx, ctx->fence);
  10006. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  10007. ctx->device->device.resetFences({ ctx->fence });
  10008. ggml_vk_queue_command_pools_cleanup(ctx->device);
  10009. auto end = std::chrono::high_resolution_clock::now();
  10010. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  10011. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  10012. int first_err = -1;
  10013. double avg_err = 0.0;
  10014. for (size_t i = 0; i < ne; i++) {
  10015. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  10016. avg_err += error;
  10017. if (first_err < 0 && error > 0.05) {
  10018. first_err = i;
  10019. }
  10020. }
  10021. avg_err /= ne;
  10022. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  10023. if (avg_err > 0.1) {
  10024. std::cerr << "first_error = " << first_err << std::endl;
  10025. std::cerr << "Actual result: " << std::endl << std::endl;
  10026. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  10027. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  10028. }
  10029. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  10030. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  10031. std::cerr << x_ref[i] << ", ";
  10032. }
  10033. std::cerr << std::endl;
  10034. }
  10035. ggml_vk_destroy_buffer(x_buf);
  10036. ggml_vk_destroy_buffer(qx_buf);
  10037. free(x);
  10038. free(qx);
  10039. free(x_ref);
  10040. free(x_chk);
  10041. }
  10042. // This does not work without ggml q8_1 quantization support
  10043. //
  10044. // typedef uint16_t ggml_half;
  10045. // typedef uint32_t ggml_half2;
  10046. //
  10047. // #define QK8_1 32
  10048. // typedef struct {
  10049. // union {
  10050. // struct {
  10051. // ggml_half d; // delta
  10052. // ggml_half s; // d * sum(qs[i])
  10053. // } GGML_COMMON_AGGR_S;
  10054. // ggml_half2 ds;
  10055. // } GGML_COMMON_AGGR_U;
  10056. // int8_t qs[QK8_1]; // quants
  10057. // } block_q8_1;
  10058. //
  10059. // static void ggml_vk_test_quantize(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  10060. // VK_LOG_DEBUG("ggml_vk_test_quantize(" << ne << ")");
  10061. // GGML_ASSERT(quant == GGML_TYPE_Q8_1);
  10062. //
  10063. // const size_t x_sz = sizeof(float) * ne;
  10064. // const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  10065. // float * x = (float *) malloc(x_sz);
  10066. // block_q8_1 * qx = (block_q8_1 *)malloc(qx_sz);
  10067. // block_q8_1 * qx_res = (block_q8_1 *)malloc(qx_sz);
  10068. // vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10069. // vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10070. //
  10071. // for (size_t i = 0; i < ne; i++) {
  10072. // x[i] = rand() / (float)RAND_MAX;
  10073. // }
  10074. //
  10075. // vk_pipeline p = ggml_vk_get_quantize_pipeline(ctx, quant);
  10076. //
  10077. // ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  10078. //
  10079. // ggml_pipeline_allocate_descriptor_sets(ctx);
  10080. //
  10081. // ggml_vk_buffer_write(x_buf, 0, x, x_sz);
  10082. //
  10083. // vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10084. // ggml_vk_ctx_begin(ctx->device, subctx);
  10085. // ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, x_buf), ggml_vk_subbuffer(ctx, qx_buf), ne);
  10086. // ggml_vk_ctx_end(subctx);
  10087. //
  10088. // auto begin = std::chrono::high_resolution_clock::now();
  10089. //
  10090. // ggml_vk_submit(subctx, ctx->fence);
  10091. // VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_quantize waitForFences");
  10092. // ctx->device->device.resetFences({ ctx->fence });
  10093. // ggml_vk_queue_command_pools_cleanup(ctx->device);
  10094. //
  10095. // auto end = std::chrono::high_resolution_clock::now();
  10096. //
  10097. // double ms_quant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  10098. // ggml_vk_buffer_read(qx_buf, 0, qx, qx_sz);
  10099. //
  10100. // ggml_vk_quantize_data(x, qx_res, ne, quant);
  10101. //
  10102. // int first_err = -1;
  10103. //
  10104. // for (size_t i = 0; i < ne / 32; i++) {
  10105. // 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));
  10106. //
  10107. // if (first_err < 0 && error > 0.1) {
  10108. // first_err = i;
  10109. // }
  10110. //
  10111. // 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));
  10112. //
  10113. // if (first_err < 0 && error > 0.1) {
  10114. // first_err = i;
  10115. // }
  10116. //
  10117. // for (size_t j = 0; j < 32; j++) {
  10118. // uint64_t error = std::abs(qx_res[i].qs[j] - qx[i].qs[j]);
  10119. //
  10120. // if (first_err < 0 && error > 1) {
  10121. // first_err = i;
  10122. // }
  10123. // }
  10124. // }
  10125. //
  10126. // std::cerr << "TEST QUANTIZE " << ggml_type_name(quant) << " time=" << ms_quant << "ms " << (first_err == -1 ? "CORRECT" : "INCORRECT") << std::endl;
  10127. //
  10128. // if (first_err != -1) {
  10129. // std::cerr << "first_error = " << first_err << std::endl;
  10130. // std::cerr << "Actual result: " << std::endl << std::endl;
  10131. // 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) << " ";
  10132. // for (size_t j = 0; j < 32; j++) {
  10133. // std::cout << " qs" << j << "=" << (uint32_t)qx[first_err].qs[j] << " ";
  10134. // }
  10135. // std::cerr << std::endl << std::endl << "Expected result: " << std::endl << std::endl;
  10136. // 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) << " ";
  10137. // for (size_t j = 0; j < 32; j++) {
  10138. // std::cout << " qs" << j << "=" << (uint32_t)qx_res[first_err].qs[j] << " ";
  10139. // }
  10140. // std::cerr << std::endl;
  10141. // }
  10142. //
  10143. // ggml_vk_destroy_buffer(x_buf);
  10144. // ggml_vk_destroy_buffer(qx_buf);
  10145. //
  10146. // free(x);
  10147. // free(qx);
  10148. // free(qx_res);
  10149. // }
  10150. 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) {
  10151. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  10152. const size_t x_ne = m * k * batch;
  10153. const size_t y_ne = k * n * batch;
  10154. const size_t d_ne = m * n * batch;
  10155. vk_matmul_pipeline2 * pipelines;
  10156. if (mmq) {
  10157. pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1;
  10158. } else {
  10159. pipelines = ctx->device->pipeline_dequant_mul_mat_mat;
  10160. }
  10161. const bool fp16acc = ctx->device->fp16;
  10162. vk_pipeline p;
  10163. std::string shname;
  10164. if (shader_size == 0) {
  10165. p = fp16acc ? pipelines[quant].f16acc->a_s : pipelines[quant].f32acc->a_s;
  10166. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  10167. } else if (shader_size == 1) {
  10168. p = fp16acc ? pipelines[quant].f16acc->a_m : pipelines[quant].f32acc->a_m;
  10169. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  10170. } else if (shader_size == 2) {
  10171. p = fp16acc ? pipelines[quant].f16acc->a_l : pipelines[quant].f32acc->a_l;
  10172. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  10173. } else {
  10174. GGML_ASSERT(0);
  10175. }
  10176. const size_t kpad = mmq ? 0 : ggml_vk_align_size(k, p->align);
  10177. if (mmq || k != kpad) {
  10178. if (shader_size == 0) {
  10179. p = fp16acc ? pipelines[quant].f16acc->s : pipelines[quant].f32acc->s;
  10180. shname = std::string(ggml_type_name(quant)) + "_S";
  10181. } else if (shader_size == 1) {
  10182. p = fp16acc ? pipelines[quant].f16acc->m : pipelines[quant].f32acc->m;
  10183. shname = std::string(ggml_type_name(quant)) + "_M";
  10184. } else if (shader_size == 2) {
  10185. p = fp16acc ? pipelines[quant].f16acc->l : pipelines[quant].f32acc->l;
  10186. shname = std::string(ggml_type_name(quant)) + "_L";
  10187. } else {
  10188. GGML_ASSERT(0);
  10189. }
  10190. }
  10191. if (p == nullptr) {
  10192. std::cerr << "error: no pipeline for ggml_vk_test_dequant_matmul " << ggml_type_name(quant) << std::endl;
  10193. return;
  10194. }
  10195. const size_t x_sz = sizeof(float) * x_ne;
  10196. const size_t y_sz = sizeof(float) * y_ne;
  10197. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  10198. const size_t qy_sz = mmq ? y_ne * ggml_type_size(GGML_TYPE_Q8_1)/ggml_blck_size(GGML_TYPE_Q8_1) : y_sz;
  10199. const size_t d_sz = sizeof(float) * d_ne;
  10200. float * x = (float *) malloc(x_sz);
  10201. float * y = (float *) malloc(y_sz);
  10202. void * qx = malloc(qx_sz);
  10203. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10204. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10205. vk_buffer qy_buf = ggml_vk_create_buffer_check(ctx->device, qy_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10206. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10207. float * d = (float *) malloc(d_sz);
  10208. float * d_chk = (float *) malloc(d_sz);
  10209. for (size_t i = 0; i < x_ne; i++) {
  10210. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  10211. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  10212. // x[i] = i % k;
  10213. }
  10214. ggml_vk_quantize_data(x, qx, x_ne, quant);
  10215. for (size_t i = 0; i < y_ne; i++) {
  10216. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  10217. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  10218. // y[i] = i % k;
  10219. }
  10220. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  10221. if (split_k > 1) {
  10222. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  10223. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  10224. // Resize buffer
  10225. if (ctx->prealloc_split_k != nullptr) {
  10226. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10227. }
  10228. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  10229. }
  10230. }
  10231. if (mmq) {
  10232. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_quantize_q8_1, num_it);
  10233. }
  10234. ggml_pipeline_allocate_descriptor_sets(ctx);
  10235. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  10236. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  10237. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10238. ggml_vk_ctx_begin(ctx->device, subctx);
  10239. if (mmq) {
  10240. for (size_t i = 0; i < num_it; i++) {
  10241. ggml_vk_quantize_q8_1(ctx, subctx, { y_buf, 0, y_sz }, { qy_buf, 0, qy_sz }, y_ne);
  10242. ggml_vk_matmul(
  10243. 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 },
  10244. m, n, k,
  10245. k, k, m, k*m, k*n, m*n,
  10246. split_k, batch, batch, batch, 1, 1, n
  10247. );
  10248. }
  10249. } else {
  10250. for (size_t i = 0; i < num_it; i++) {
  10251. ggml_vk_matmul(
  10252. 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 },
  10253. m, n, k,
  10254. k, k, m, k*m, k*n, m*n,
  10255. split_k, batch, batch, batch, 1, 1, n
  10256. );
  10257. }
  10258. }
  10259. ggml_vk_ctx_end(subctx);
  10260. auto begin = std::chrono::high_resolution_clock::now();
  10261. ggml_vk_submit(subctx, ctx->fence);
  10262. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  10263. ctx->device->device.resetFences({ ctx->fence });
  10264. ggml_vk_queue_command_pools_cleanup(ctx->device);
  10265. auto end = std::chrono::high_resolution_clock::now();
  10266. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  10267. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  10268. ggml_init_params iparams = {
  10269. /*.mem_size =*/ 1024*1024*1024,
  10270. /*.mem_buffer =*/ NULL,
  10271. /*.no_alloc =*/ true,
  10272. };
  10273. ggml_context * ggml_ctx = ggml_init(iparams);
  10274. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  10275. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  10276. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  10277. src0_ggml->data = qx;
  10278. src1_ggml->data = y;
  10279. tensor_ggml->data = d_chk;
  10280. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  10281. ggml_build_forward_expand(cgraph, tensor_ggml);
  10282. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  10283. ggml_free(ggml_ctx);
  10284. double avg_err = 0.0;
  10285. int first_err_n = -1;
  10286. int first_err_m = -1;
  10287. int first_err_b = -1;
  10288. for (size_t i = 0; i < m*n*batch; i++) {
  10289. double err = std::fabs(d[i] - d_chk[i]);
  10290. avg_err += err;
  10291. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  10292. first_err_b = i / (m * n);
  10293. first_err_n = (i % (m * n)) / m;
  10294. first_err_m = (i % (m * n)) % m;
  10295. }
  10296. }
  10297. avg_err /= m * n;
  10298. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  10299. std::cerr << "TEST dequant matmul " << shname;
  10300. if (mmq) {
  10301. std::cerr << " mmq";
  10302. }
  10303. 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;
  10304. if (avg_err > 0.01 || std::isnan(avg_err)) {
  10305. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  10306. std::cerr << "Actual result: " << std::endl << std::endl;
  10307. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  10308. std::cerr << std::endl;
  10309. std::cerr << "Expected result: " << std::endl << std::endl;
  10310. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  10311. std::cerr << "src0: " << std::endl << std::endl;
  10312. ggml_vk_print_matrix_area(x, GGML_TYPE_F32, k, m, first_err_m, first_err_n, first_err_b);
  10313. std::cerr << std::endl;
  10314. std::cerr << "src1: " << std::endl << std::endl;
  10315. ggml_vk_print_matrix_area(y, GGML_TYPE_F32, k, n, first_err_m, first_err_n, first_err_b);
  10316. if (split_k > 1) {
  10317. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  10318. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  10319. std::cerr << "d_buf0: " << std::endl << std::endl;
  10320. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  10321. std::cerr << "d_buf1: " << std::endl << std::endl;
  10322. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  10323. std::cerr << "d_buf2: " << std::endl << std::endl;
  10324. 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);
  10325. std::cerr << "d_buf3: " << std::endl << std::endl;
  10326. 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);
  10327. free(split_k_buf);
  10328. }
  10329. }
  10330. ggml_vk_destroy_buffer(qx_buf);
  10331. ggml_vk_destroy_buffer(y_buf);
  10332. ggml_vk_destroy_buffer(qy_buf);
  10333. ggml_vk_destroy_buffer(d_buf);
  10334. free(x);
  10335. free(qx);
  10336. free(y);
  10337. free(d);
  10338. free(d_chk);
  10339. }
  10340. #endif
  10341. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx) {
  10342. #if defined(GGML_VULKAN_RUN_TESTS)
  10343. const std::vector<size_t> vals {
  10344. 512, 512, 128,
  10345. 128, 512, 512,
  10346. 4096, 512, 4096,
  10347. 11008, 512, 4096,
  10348. 4096, 512, 11008,
  10349. 32000, 512, 4096,
  10350. 8, 8, 8,
  10351. 100, 46, 576,
  10352. 623, 111, 128,
  10353. 100, 46, 558,
  10354. 512, 1, 256,
  10355. 128, 110, 622,
  10356. 511, 511, 127,
  10357. 511, 511, 7,
  10358. 511, 511, 17,
  10359. 49, 49, 128,
  10360. 128, 49, 49,
  10361. 4096, 49, 4096,
  10362. };
  10363. const size_t num_it = 100;
  10364. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  10365. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  10366. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  10367. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true);
  10368. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true);
  10369. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true);
  10370. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0);
  10371. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0);
  10372. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0);
  10373. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true);
  10374. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true);
  10375. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true);
  10376. abort();
  10377. for (size_t i = 0; i < vals.size(); i += 3) {
  10378. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  10379. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  10380. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  10381. std::cerr << '\n';
  10382. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  10383. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  10384. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  10385. std::cerr << '\n';
  10386. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  10387. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  10388. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  10389. std::cerr << '\n' << std::endl;
  10390. if (vals[i + 2] % 32 == 0) {
  10391. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  10392. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  10393. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  10394. std::cerr << '\n';
  10395. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  10396. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  10397. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  10398. std::cerr << '\n';
  10399. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  10400. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  10401. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  10402. std::cerr << '\n' << std::endl;
  10403. }
  10404. if (vals[i + 2] % 256 == 0) {
  10405. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  10406. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  10407. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  10408. std::cerr << '\n';
  10409. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  10410. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  10411. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  10412. std::cerr << '\n';
  10413. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  10414. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  10415. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  10416. std::cerr << '\n' << std::endl;
  10417. }
  10418. }
  10419. GGML_ABORT("fatal error");
  10420. #endif
  10421. if (subctx) {
  10422. // Submit and wait for any pending work before reallocating the buffers
  10423. ggml_vk_ctx_end(subctx);
  10424. ggml_vk_submit(subctx, {});
  10425. ctx->submit_pending = true;
  10426. ggml_vk_synchronize(ctx);
  10427. ggml_vk_ctx_begin(ctx->device, subctx);
  10428. }
  10429. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  10430. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  10431. // Resize buffer
  10432. if (ctx->prealloc_x != nullptr) {
  10433. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10434. }
  10435. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  10436. }
  10437. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  10438. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  10439. // Resize buffer
  10440. if (ctx->prealloc_y != nullptr) {
  10441. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10442. }
  10443. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  10444. }
  10445. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  10446. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  10447. // Resize buffer
  10448. if (ctx->prealloc_split_k != nullptr) {
  10449. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10450. }
  10451. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  10452. }
  10453. 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)) {
  10454. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")");
  10455. // Resize buffer
  10456. if (ctx->prealloc_add_rms_partials != nullptr) {
  10457. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  10458. }
  10459. ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials);
  10460. }
  10461. }
  10462. static void ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_cgraph * cgraph, ggml_tensor* tensor, int tensor_idx, bool almost_ready);
  10463. // Returns true if node has enqueued work into the queue, false otherwise
  10464. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  10465. 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){
  10466. ggml_tensor * node = cgraph->nodes[node_idx];
  10467. if (ggml_is_empty(node) || ggml_op_is_empty(node->op) || !node->buffer) {
  10468. return false;
  10469. }
  10470. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  10471. ctx->semaphore_idx = 0;
  10472. ggml_tensor * src0 = node->src[0];
  10473. ggml_tensor * src1 = node->src[1];
  10474. ggml_tensor * src2 = node->src[2];
  10475. ggml_tensor * src3 = node->src[3];
  10476. if (node->op == GGML_OP_ADD) {
  10477. int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops;
  10478. if (next_node_idx < cgraph->n_nodes &&
  10479. cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM &&
  10480. cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] &&
  10481. ggml_nrows(cgraph->nodes[next_node_idx]) == 1 &&
  10482. ctx->device->add_rms_fusion) {
  10483. uint32_t size = ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]);
  10484. ctx->do_add_rms_partials_offset_calculation = true;
  10485. if (ctx->prealloc_size_add_rms_partials_offset + size <= ctx->prealloc_size_add_rms_partials) {
  10486. ctx->do_add_rms_partials = true;
  10487. }
  10488. }
  10489. }
  10490. vk_context compute_ctx;
  10491. if (ctx->compute_ctx.expired()) {
  10492. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10493. ctx->compute_ctx = compute_ctx;
  10494. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10495. } else {
  10496. compute_ctx = ctx->compute_ctx.lock();
  10497. }
  10498. {
  10499. // This logic detects dependencies between modes in the graph and calls ggml_vk_sync_buffers
  10500. // to synchronize them. This handles most "normal" synchronization when computing the graph, and when
  10501. // there is no auxiliary memory use, it shouldn't be necessary to call ggml_vk_sync_buffers
  10502. // outside of this logic. When a node uses one of the prealloc buffers for something like
  10503. // dequantization or split_k, additional synchronization is needed between those passes.
  10504. bool need_sync = false;
  10505. // Check whether "node" requires synchronization. The node requires synchronization if it
  10506. // overlaps in memory with another unsynchronized node and at least one of them is a write.
  10507. // Destination nodes are checked against both the written/read lists. Source nodes are only
  10508. // checked against the written list. Two nodes overlap in memory if they come from the same
  10509. // buffer and the tensor or view ranges overlap.
  10510. auto const &overlaps_unsynced = [&](const ggml_tensor *node, const std::vector<const ggml_tensor *> &unsynced_nodes) -> bool {
  10511. if (unsynced_nodes.size() == 0) {
  10512. return false;
  10513. }
  10514. auto n_base = vk_tensor_offset(node) + node->view_offs;
  10515. auto n_size = ggml_nbytes(node);
  10516. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context;
  10517. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  10518. for (auto &other : unsynced_nodes) {
  10519. ggml_backend_vk_buffer_context * o_buf_ctx = (ggml_backend_vk_buffer_context *)other->buffer->context;
  10520. vk_buffer o_buf = o_buf_ctx->dev_buffer;
  10521. if (a_buf == o_buf) {
  10522. auto o_base = vk_tensor_offset(other) + other->view_offs;
  10523. auto o_size = ggml_nbytes(other);
  10524. if ((o_base <= n_base && n_base < o_base + o_size) ||
  10525. (n_base <= o_base && o_base < n_base + n_size)) {
  10526. return true;
  10527. }
  10528. }
  10529. }
  10530. return false;
  10531. };
  10532. // For all fused ops, check if the destination node or any of the source
  10533. // nodes require synchronization.
  10534. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) {
  10535. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  10536. // If the node actually writes to memory, then check if it needs to sync
  10537. if (ctx->fused_ops_write_mask & (1 << i)) {
  10538. if (overlaps_unsynced(cur_node, ctx->unsynced_nodes_read) || overlaps_unsynced(cur_node, ctx->unsynced_nodes_written)) {
  10539. need_sync = true;
  10540. break;
  10541. }
  10542. }
  10543. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  10544. if (!cur_node->src[j]) {
  10545. continue;
  10546. }
  10547. if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) {
  10548. need_sync = true;
  10549. break;
  10550. }
  10551. }
  10552. }
  10553. if (need_sync) {
  10554. if (vk_enable_sync_logger) {
  10555. std::cerr << "sync" << std::endl;
  10556. }
  10557. ctx->unsynced_nodes_written.clear();
  10558. ctx->unsynced_nodes_read.clear();
  10559. ggml_vk_sync_buffers(ctx, compute_ctx);
  10560. if (vk_perf_logger_enabled && vk_perf_logger_concurrent) {
  10561. ctx->query_node_idx[ctx->query_idx] = node_idx;
  10562. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  10563. }
  10564. }
  10565. // Add all fused nodes to the unsynchronized lists.
  10566. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  10567. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  10568. // Multiple outputs could be written, e.g. in topk_moe. Add them all to the list.
  10569. if (ctx->fused_ops_write_mask & (1 << i)) {
  10570. ctx->unsynced_nodes_written.push_back(cur_node);
  10571. }
  10572. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  10573. if (!cur_node->src[j]) {
  10574. continue;
  10575. }
  10576. ctx->unsynced_nodes_read.push_back(cur_node->src[j]);
  10577. }
  10578. }
  10579. }
  10580. if (vk_enable_sync_logger) {
  10581. for (int i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  10582. auto *n = cgraph->nodes[node_idx + i];
  10583. std::cerr << node_idx + i << " " << ggml_op_name(n->op) << " " << n->name;
  10584. if (n->op == GGML_OP_GLU) {
  10585. std::cerr << " " << ggml_glu_op_name(ggml_get_glu_op(n)) << " " << (n->src[1] ? "split" : "single") << " ";
  10586. }
  10587. if (n->op == GGML_OP_ROPE) {
  10588. const int mode = ((const int32_t *) n->op_params)[2];
  10589. std::cerr << " rope mode: " << mode;
  10590. }
  10591. std::cerr << std::endl;
  10592. }
  10593. }
  10594. switch (node->op) {
  10595. case GGML_OP_REPEAT:
  10596. ggml_vk_repeat(ctx, compute_ctx, src0, node);
  10597. break;
  10598. case GGML_OP_REPEAT_BACK:
  10599. ggml_vk_repeat_back(ctx, compute_ctx, src0, node);
  10600. break;
  10601. case GGML_OP_ACC:
  10602. ggml_vk_acc(ctx, compute_ctx, src0, src1, node);
  10603. break;
  10604. case GGML_OP_GET_ROWS:
  10605. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node);
  10606. break;
  10607. case GGML_OP_ADD:
  10608. if (ctx->num_additional_fused_ops) {
  10609. ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx);
  10610. } else {
  10611. ggml_vk_add(ctx, compute_ctx, src0, src1, node);
  10612. }
  10613. break;
  10614. case GGML_OP_SUB:
  10615. ggml_vk_sub(ctx, compute_ctx, src0, src1, node);
  10616. break;
  10617. case GGML_OP_MUL:
  10618. ggml_vk_mul(ctx, compute_ctx, src0, src1, node);
  10619. break;
  10620. case GGML_OP_DIV:
  10621. ggml_vk_div(ctx, compute_ctx, src0, src1, node);
  10622. break;
  10623. case GGML_OP_ADD_ID:
  10624. ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node);
  10625. break;
  10626. case GGML_OP_CONCAT:
  10627. ggml_vk_concat(ctx, compute_ctx, src0, src1, node);
  10628. break;
  10629. case GGML_OP_UPSCALE:
  10630. ggml_vk_upscale(ctx, compute_ctx, src0, node);
  10631. break;
  10632. case GGML_OP_ADD1:
  10633. ggml_vk_add1(ctx, compute_ctx, src0, src1, node);
  10634. break;
  10635. case GGML_OP_ARANGE:
  10636. ggml_vk_arange(ctx, compute_ctx, node);
  10637. break;
  10638. case GGML_OP_FILL:
  10639. ggml_vk_fill(ctx, compute_ctx, node);
  10640. break;
  10641. case GGML_OP_SCALE:
  10642. ggml_vk_scale(ctx, compute_ctx, src0, node);
  10643. break;
  10644. case GGML_OP_SQR:
  10645. ggml_vk_sqr(ctx, compute_ctx, src0, node);
  10646. break;
  10647. case GGML_OP_SQRT:
  10648. ggml_vk_sqrt(ctx, compute_ctx, src0, node);
  10649. break;
  10650. case GGML_OP_SIN:
  10651. ggml_vk_sin(ctx, compute_ctx, src0, node);
  10652. break;
  10653. case GGML_OP_COS:
  10654. ggml_vk_cos(ctx, compute_ctx, src0, node);
  10655. break;
  10656. case GGML_OP_LOG:
  10657. ggml_vk_log(ctx, compute_ctx, src0, node);
  10658. break;
  10659. case GGML_OP_TRI:
  10660. ggml_vk_tri(ctx, compute_ctx, src0, node);
  10661. break;
  10662. case GGML_OP_DIAG:
  10663. ggml_vk_diag(ctx, compute_ctx, src0, node);
  10664. break;
  10665. case GGML_OP_CLAMP:
  10666. ggml_vk_clamp(ctx, compute_ctx, src0, node);
  10667. break;
  10668. case GGML_OP_PAD:
  10669. ggml_vk_pad(ctx, compute_ctx, src0, node);
  10670. break;
  10671. case GGML_OP_ROLL:
  10672. ggml_vk_roll(ctx, compute_ctx, src0, node);
  10673. break;
  10674. case GGML_OP_CPY:
  10675. case GGML_OP_CONT:
  10676. case GGML_OP_DUP:
  10677. ggml_vk_cpy(ctx, compute_ctx, src0, node);
  10678. break;
  10679. case GGML_OP_SET_ROWS:
  10680. ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node);
  10681. break;
  10682. case GGML_OP_SILU_BACK:
  10683. ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node);
  10684. break;
  10685. case GGML_OP_NORM:
  10686. ggml_vk_norm(ctx, compute_ctx, src0, node);
  10687. break;
  10688. case GGML_OP_GROUP_NORM:
  10689. ggml_vk_group_norm(ctx, compute_ctx, src0, node);
  10690. break;
  10691. case GGML_OP_RMS_NORM:
  10692. ggml_vk_rms_norm(ctx, compute_ctx, cgraph, node_idx, (float *)node->op_params);
  10693. break;
  10694. case GGML_OP_RMS_NORM_BACK:
  10695. ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node);
  10696. break;
  10697. case GGML_OP_L2_NORM:
  10698. ggml_vk_l2_norm(ctx, compute_ctx, src0, node);
  10699. break;
  10700. case GGML_OP_UNARY:
  10701. if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) {
  10702. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10703. break;
  10704. }
  10705. switch (ggml_get_unary_op(node)) {
  10706. case GGML_UNARY_OP_EXP:
  10707. case GGML_UNARY_OP_SILU:
  10708. case GGML_UNARY_OP_GELU:
  10709. case GGML_UNARY_OP_GELU_ERF:
  10710. case GGML_UNARY_OP_GELU_QUICK:
  10711. case GGML_UNARY_OP_RELU:
  10712. case GGML_UNARY_OP_NEG:
  10713. case GGML_UNARY_OP_TANH:
  10714. case GGML_UNARY_OP_SIGMOID:
  10715. case GGML_UNARY_OP_HARDSIGMOID:
  10716. case GGML_UNARY_OP_HARDSWISH:
  10717. case GGML_UNARY_OP_ABS:
  10718. case GGML_UNARY_OP_SOFTPLUS:
  10719. case GGML_UNARY_OP_STEP:
  10720. case GGML_UNARY_OP_ROUND:
  10721. case GGML_UNARY_OP_CEIL:
  10722. case GGML_UNARY_OP_FLOOR:
  10723. case GGML_UNARY_OP_TRUNC:
  10724. ggml_vk_unary(ctx, compute_ctx, src0, node);
  10725. break;
  10726. case GGML_UNARY_OP_XIELU:
  10727. ggml_vk_xielu(ctx, compute_ctx, src0, node);
  10728. break;
  10729. default:
  10730. return false;
  10731. }
  10732. break;
  10733. case GGML_OP_GLU:
  10734. switch (ggml_get_glu_op(node)) {
  10735. case GGML_GLU_OP_GEGLU:
  10736. case GGML_GLU_OP_REGLU:
  10737. case GGML_GLU_OP_SWIGLU:
  10738. case GGML_GLU_OP_SWIGLU_OAI:
  10739. case GGML_GLU_OP_GEGLU_ERF:
  10740. case GGML_GLU_OP_GEGLU_QUICK:
  10741. ggml_vk_glu(ctx, compute_ctx, src0, src1, node);
  10742. break;
  10743. default:
  10744. return false;
  10745. }
  10746. break;
  10747. case GGML_OP_DIAG_MASK_INF:
  10748. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node);
  10749. break;
  10750. case GGML_OP_SOFT_MAX:
  10751. if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) {
  10752. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10753. } else {
  10754. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node);
  10755. }
  10756. break;
  10757. case GGML_OP_SOFT_MAX_BACK:
  10758. ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node);
  10759. break;
  10760. case GGML_OP_ROPE:
  10761. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, false);
  10762. break;
  10763. case GGML_OP_ROPE_BACK:
  10764. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, true);
  10765. break;
  10766. case GGML_OP_ARGSORT:
  10767. if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) {
  10768. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10769. } else {
  10770. ggml_vk_argsort(ctx, compute_ctx, src0, node);
  10771. }
  10772. break;
  10773. case GGML_OP_TOP_K:
  10774. ggml_vk_topk(ctx, compute_ctx, src0, node);
  10775. break;
  10776. case GGML_OP_SUM:
  10777. ggml_vk_sum(ctx, compute_ctx, src0, node);
  10778. break;
  10779. case GGML_OP_SUM_ROWS:
  10780. ggml_vk_sum_rows(ctx, compute_ctx, src0, node);
  10781. break;
  10782. case GGML_OP_CUMSUM:
  10783. ggml_vk_cumsum(ctx, compute_ctx, src0, node);
  10784. break;
  10785. case GGML_OP_MEAN:
  10786. ggml_vk_mean(ctx, compute_ctx, src0, node);
  10787. break;
  10788. case GGML_OP_ARGMAX:
  10789. ggml_vk_argmax(ctx, compute_ctx, src0, node);
  10790. break;
  10791. case GGML_OP_COUNT_EQUAL:
  10792. ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node);
  10793. break;
  10794. case GGML_OP_SOLVE_TRI:
  10795. ggml_vk_solve_tri(ctx, compute_ctx, src0, src1, node);
  10796. break;
  10797. case GGML_OP_IM2COL:
  10798. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node);
  10799. break;
  10800. case GGML_OP_IM2COL_3D:
  10801. ggml_vk_im2col_3d(ctx, compute_ctx, src0, src1, node);
  10802. break;
  10803. case GGML_OP_TIMESTEP_EMBEDDING:
  10804. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node);
  10805. break;
  10806. case GGML_OP_CONV_TRANSPOSE_1D:
  10807. ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node);
  10808. break;
  10809. case GGML_OP_POOL_2D:
  10810. ggml_vk_pool_2d(ctx, compute_ctx, src0, node);
  10811. break;
  10812. case GGML_OP_CONV_2D:
  10813. case GGML_OP_CONV_TRANSPOSE_2D:
  10814. ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node);
  10815. break;
  10816. case GGML_OP_CONV_2D_DW:
  10817. ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node);
  10818. break;
  10819. case GGML_OP_LEAKY_RELU:
  10820. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node);
  10821. break;
  10822. case GGML_OP_MUL_MAT:
  10823. ggml_vk_mul_mat(ctx, compute_ctx, cgraph, node_idx);
  10824. break;
  10825. case GGML_OP_MUL_MAT_ID:
  10826. ggml_vk_mul_mat_id(ctx, compute_ctx, cgraph, node_idx);
  10827. break;
  10828. case GGML_OP_FLASH_ATTN_EXT:
  10829. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node);
  10830. break;
  10831. case GGML_OP_RWKV_WKV6:
  10832. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node);
  10833. break;
  10834. case GGML_OP_RWKV_WKV7:
  10835. ggml_vk_rwkv_wkv7(ctx, compute_ctx, node);
  10836. break;
  10837. case GGML_OP_SSM_SCAN:
  10838. ggml_vk_ssm_scan(ctx, compute_ctx, node);
  10839. break;
  10840. case GGML_OP_SSM_CONV:
  10841. ggml_vk_ssm_conv(ctx, compute_ctx, node);
  10842. break;
  10843. case GGML_OP_OPT_STEP_ADAMW:
  10844. ggml_vk_opt_step_adamw(ctx, compute_ctx, node);
  10845. break;
  10846. case GGML_OP_OPT_STEP_SGD:
  10847. ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node);
  10848. break;
  10849. default:
  10850. return false;
  10851. }
  10852. ctx->tensor_ctxs[node_idx] = compute_ctx;
  10853. #if defined(GGML_VULKAN_CHECK_RESULTS)
  10854. // Force context reset on each node so that each tensor ends up in its own context
  10855. // and can be run and compared to its CPU equivalent separately
  10856. last_node = true;
  10857. #endif
  10858. if (submit || last_node) {
  10859. ggml_vk_ctx_end(compute_ctx);
  10860. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  10861. if (last_node) {
  10862. compute_ctx->exit_tensor_idx = node_idx_begin;
  10863. }
  10864. else {
  10865. compute_ctx->exit_tensor_idx = -1;
  10866. }
  10867. ctx->compute_ctx.reset();
  10868. ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, almost_ready);
  10869. }
  10870. return true;
  10871. }
  10872. static void ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, ggml_tensor * tensor, int tensor_idx, bool almost_ready = false) {
  10873. GGML_UNUSED(cgraph);
  10874. GGML_UNUSED(tensor);
  10875. 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 << ")");
  10876. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  10877. // Only run if ctx hasn't been submitted yet
  10878. if (!subctx->seqs.empty()) {
  10879. #ifdef GGML_VULKAN_CHECK_RESULTS
  10880. ggml_vk_check_results_0(ctx, cgraph, tensor_idx);
  10881. #endif
  10882. // Do staging buffer copies
  10883. for (auto& cpy : subctx->in_memcpys) {
  10884. memcpy(cpy.dst, cpy.src, cpy.n);
  10885. }
  10886. for (auto& mset : subctx->memsets) {
  10887. memset(mset.dst, mset.val, mset.n);
  10888. }
  10889. if (almost_ready && !ctx->almost_ready_fence_pending) {
  10890. ggml_vk_submit(subctx, ctx->almost_ready_fence);
  10891. ctx->almost_ready_fence_pending = true;
  10892. } else {
  10893. ggml_vk_submit(subctx, {});
  10894. }
  10895. ctx->submit_pending = true;
  10896. #ifdef GGML_VULKAN_CHECK_RESULTS
  10897. ggml_vk_synchronize(ctx);
  10898. ggml_vk_check_results_1(ctx, cgraph, tensor_idx);
  10899. #endif
  10900. }
  10901. if (tensor_idx == subctx->exit_tensor_idx) {
  10902. // Do staging buffer copies
  10903. for (auto& cpy : subctx->out_memcpys) {
  10904. memcpy(cpy.dst, cpy.src, cpy.n);
  10905. }
  10906. subctx->in_memcpys.clear();
  10907. subctx->out_memcpys.clear();
  10908. subctx->memsets.clear();
  10909. }
  10910. }
  10911. // Clean up after graph processing is done
  10912. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  10913. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  10914. ctx->prealloc_y_last_pipeline_used = {};
  10915. ctx->unsynced_nodes_written.clear();
  10916. ctx->unsynced_nodes_read.clear();
  10917. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  10918. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  10919. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  10920. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  10921. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  10922. }
  10923. ctx->gc.semaphores.clear();
  10924. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  10925. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  10926. }
  10927. ctx->gc.tl_semaphores.clear();
  10928. ctx->semaphore_idx = 0;
  10929. ctx->event_idx = 0;
  10930. for (auto& event : ctx->gc.events) {
  10931. ctx->device->device.resetEvent(event);
  10932. }
  10933. ctx->tensor_ctxs.clear();
  10934. ctx->gc.contexts.clear();
  10935. ctx->pipeline_descriptor_set_requirements = 0;
  10936. ctx->descriptor_set_idx = 0;
  10937. }
  10938. // Clean up on backend free
  10939. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  10940. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  10941. // discard any unsubmitted command buffers
  10942. ctx->transfer_ctx.reset();
  10943. // wait for any pending command buffers to finish
  10944. ggml_vk_synchronize(ctx);
  10945. ggml_vk_graph_cleanup(ctx);
  10946. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10947. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10948. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10949. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  10950. ggml_vk_destroy_buffer(ctx->sync_staging);
  10951. ctx->prealloc_y_last_pipeline_used = nullptr;
  10952. ctx->prealloc_size_x = 0;
  10953. ctx->prealloc_size_y = 0;
  10954. ctx->prealloc_size_split_k = 0;
  10955. for (auto& event : ctx->gc.events) {
  10956. ctx->device->device.destroyEvent(event);
  10957. }
  10958. ctx->gc.events.clear();
  10959. ctx->device->device.destroyFence(ctx->fence);
  10960. ctx->device->device.destroyFence(ctx->almost_ready_fence);
  10961. for (auto& pool : ctx->descriptor_pools) {
  10962. ctx->device->device.destroyDescriptorPool(pool);
  10963. }
  10964. ctx->descriptor_pools.clear();
  10965. ctx->descriptor_sets.clear();
  10966. ctx->compute_cmd_pool.destroy(ctx->device->device);
  10967. ctx->transfer_cmd_pool.destroy(ctx->device->device);
  10968. if (vk_perf_logger_enabled) {
  10969. ctx->perf_logger->print_timings(true);
  10970. }
  10971. }
  10972. static int ggml_vk_get_device_count() {
  10973. ggml_vk_instance_init();
  10974. return vk_instance.device_indices.size();
  10975. }
  10976. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  10977. ggml_vk_instance_init();
  10978. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  10979. vk::PhysicalDeviceProperties props;
  10980. devices[device].getProperties(&props);
  10981. snprintf(description, description_size, "%s", props.deviceName.data());
  10982. }
  10983. // backend interface
  10984. #define UNUSED GGML_UNUSED
  10985. // device backend
  10986. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  10987. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  10988. }
  10989. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10990. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  10991. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10992. ggml_vk_destroy_buffer(ctx->dev_buffer);
  10993. delete ctx;
  10994. }
  10995. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  10996. return vk_ptr_base;
  10997. UNUSED(buffer);
  10998. }
  10999. static enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  11000. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  11001. if (tensor->view_src != nullptr) {
  11002. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  11003. }
  11004. return GGML_STATUS_SUCCESS;
  11005. }
  11006. 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) {
  11007. VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")");
  11008. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  11009. vk_buffer buf = buf_ctx->dev_buffer;
  11010. uint32_t val32 = (uint32_t)value * 0x01010101;
  11011. ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size);
  11012. }
  11013. 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) {
  11014. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  11015. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  11016. vk_buffer buf = buf_ctx->dev_buffer;
  11017. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  11018. }
  11019. 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) {
  11020. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  11021. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  11022. vk_buffer buf = buf_ctx->dev_buffer;
  11023. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  11024. }
  11025. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  11026. if (ggml_backend_buffer_is_vk(src->buffer)) {
  11027. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  11028. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  11029. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  11030. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  11031. 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));
  11032. return true;
  11033. }
  11034. return false;
  11035. UNUSED(buffer);
  11036. }
  11037. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  11038. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  11039. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  11040. }
  11041. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  11042. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  11043. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  11044. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  11045. /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor,
  11046. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  11047. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  11048. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  11049. /* .clear = */ ggml_backend_vk_buffer_clear,
  11050. /* .reset = */ NULL,
  11051. };
  11052. // vk buffer type
  11053. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  11054. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  11055. return ctx->name.c_str();
  11056. }
  11057. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  11058. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  11059. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  11060. vk_buffer dev_buffer = nullptr;
  11061. try {
  11062. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  11063. } catch (const vk::SystemError& e) {
  11064. return nullptr;
  11065. }
  11066. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  11067. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  11068. }
  11069. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  11070. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  11071. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  11072. }
  11073. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  11074. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  11075. return ctx->device->suballocation_block_size;
  11076. }
  11077. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  11078. return ggml_nbytes(tensor);
  11079. UNUSED(buft);
  11080. }
  11081. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  11082. ggml_vk_instance_init();
  11083. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  11084. vk_device dev = ggml_vk_get_device(dev_num);
  11085. return &dev->buffer_type;
  11086. }
  11087. // host buffer type
  11088. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  11089. return GGML_VK_NAME "_Host";
  11090. UNUSED(buft);
  11091. }
  11092. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  11093. return GGML_VK_NAME "_Host";
  11094. UNUSED(buffer);
  11095. }
  11096. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  11097. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  11098. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  11099. }
  11100. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  11101. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  11102. size += 32; // Behave like the CPU buffer type
  11103. void * ptr = nullptr;
  11104. try {
  11105. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  11106. } catch (vk::SystemError& e) {
  11107. GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory (%s)\n", e.what());
  11108. // fallback to cpu buffer
  11109. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  11110. }
  11111. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  11112. buffer->buft = buft;
  11113. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  11114. return buffer;
  11115. UNUSED(buft);
  11116. }
  11117. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  11118. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  11119. UNUSED(buft);
  11120. }
  11121. static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  11122. return vk_instance.devices[0]->suballocation_block_size;
  11123. UNUSED(buft);
  11124. }
  11125. // Should be changed to return device-specific host buffer type
  11126. // but that probably requires changes in llama.cpp
  11127. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  11128. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  11129. /* .iface = */ {
  11130. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  11131. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  11132. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  11133. /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size,
  11134. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  11135. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  11136. },
  11137. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  11138. /* .context = */ nullptr,
  11139. };
  11140. // Make sure device 0 is initialized
  11141. ggml_vk_instance_init();
  11142. ggml_vk_get_device(0);
  11143. return &ggml_backend_vk_buffer_type_host;
  11144. }
  11145. // backend
  11146. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  11147. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11148. return ctx->name.c_str();
  11149. }
  11150. static void ggml_backend_vk_free(ggml_backend_t backend) {
  11151. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11152. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  11153. ggml_vk_cleanup(ctx);
  11154. delete ctx;
  11155. delete backend;
  11156. }
  11157. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  11158. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11159. return &ctx->device->buffer_type;
  11160. }
  11161. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  11162. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  11163. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11164. 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");
  11165. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  11166. vk_context transfer_ctx;
  11167. if (ctx->transfer_ctx.expired()) {
  11168. // Initialize new transfer context
  11169. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11170. ctx->transfer_ctx = transfer_ctx;
  11171. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  11172. } else {
  11173. transfer_ctx = ctx->transfer_ctx.lock();
  11174. }
  11175. vk_buffer buf = buf_ctx->dev_buffer;
  11176. auto dst_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset;
  11177. bool ret = ggml_vk_buffer_write_async(transfer_ctx, buf, dst_offset, data, size);
  11178. if (!ret) {
  11179. ggml_vk_ensure_sync_staging_buffer(ctx, size);
  11180. ggml_vk_sync_buffers(nullptr, transfer_ctx);
  11181. vk::BufferCopy buffer_cpy;
  11182. buffer_cpy.srcOffset = 0;
  11183. buffer_cpy.dstOffset = dst_offset;
  11184. buffer_cpy.size = size;
  11185. transfer_ctx->s->buffer.copyBuffer(ctx->sync_staging->buffer, buf->buffer, { buffer_cpy });
  11186. deferred_memcpy(ctx->sync_staging->ptr, data, size, &transfer_ctx->in_memcpys);
  11187. ggml_vk_synchronize(ctx);
  11188. }
  11189. }
  11190. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  11191. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  11192. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11193. 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");
  11194. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  11195. vk_context transfer_ctx;
  11196. if (ctx->transfer_ctx.expired()) {
  11197. // Initialize new transfer context
  11198. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11199. ctx->transfer_ctx = transfer_ctx;
  11200. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  11201. } else {
  11202. transfer_ctx = ctx->transfer_ctx.lock();
  11203. }
  11204. vk_buffer buf = buf_ctx->dev_buffer;
  11205. auto src_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset;
  11206. bool ret = ggml_vk_buffer_read_async(transfer_ctx, buf, src_offset, data, size);
  11207. // If that failed, copy synchronously through a staging buffer
  11208. if (!ret) {
  11209. ggml_vk_ensure_sync_staging_buffer(ctx, size);
  11210. ggml_vk_sync_buffers(nullptr, transfer_ctx);
  11211. vk::BufferCopy buffer_cpy;
  11212. buffer_cpy.srcOffset = src_offset;
  11213. buffer_cpy.dstOffset = 0;
  11214. buffer_cpy.size = size;
  11215. transfer_ctx->s->buffer.copyBuffer(buf->buffer, ctx->sync_staging->buffer, { buffer_cpy });
  11216. deferred_memcpy(data, ctx->sync_staging->ptr, size, &transfer_ctx->out_memcpys);
  11217. ggml_vk_synchronize(ctx);
  11218. }
  11219. }
  11220. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  11221. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  11222. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11223. 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)) {
  11224. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  11225. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  11226. vk_context transfer_ctx;
  11227. if (ctx->transfer_ctx.expired()) {
  11228. // Initialize new transfer context
  11229. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11230. ctx->transfer_ctx = transfer_ctx;
  11231. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  11232. } else {
  11233. transfer_ctx = ctx->transfer_ctx.lock();
  11234. }
  11235. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  11236. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  11237. 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));
  11238. return true;
  11239. }
  11240. return false;
  11241. }
  11242. static void ggml_vk_synchronize(ggml_backend_vk_context * ctx) {
  11243. VK_LOG_DEBUG("ggml_vk_synchronize()");
  11244. bool do_transfer = !ctx->transfer_ctx.expired();
  11245. vk_context transfer_ctx;
  11246. if (do_transfer) {
  11247. transfer_ctx = ctx->transfer_ctx.lock();
  11248. ggml_vk_ctx_end(transfer_ctx);
  11249. for (auto& cpy : transfer_ctx->in_memcpys) {
  11250. memcpy(cpy.dst, cpy.src, cpy.n);
  11251. }
  11252. ggml_vk_submit(transfer_ctx, {});
  11253. ctx->submit_pending = true;
  11254. }
  11255. if (ctx->submit_pending) {
  11256. {
  11257. std::lock_guard<std::mutex> guard(queue_mutex);
  11258. ctx->device->compute_queue.queue.submit({}, ctx->fence);
  11259. }
  11260. ggml_vk_wait_for_fence(ctx);
  11261. ctx->submit_pending = false;
  11262. }
  11263. if (do_transfer) {
  11264. for (auto& cpy : transfer_ctx->out_memcpys) {
  11265. memcpy(cpy.dst, cpy.src, cpy.n);
  11266. }
  11267. ctx->transfer_ctx.reset();
  11268. }
  11269. }
  11270. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  11271. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  11272. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11273. ggml_vk_synchronize(ctx);
  11274. ggml_vk_graph_cleanup(ctx);
  11275. }
  11276. static bool ggml_vk_is_empty(ggml_tensor * node) {
  11277. 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;
  11278. }
  11279. 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) {
  11280. if (!ggml_can_fuse(cgraph, node_idx, ops)) {
  11281. return false;
  11282. }
  11283. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
  11284. // additional constraints specific to this fusion
  11285. const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
  11286. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  11287. GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
  11288. GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
  11289. // rms_norm only supports f32
  11290. if (mul->src[0]->type != GGML_TYPE_F32 ||
  11291. mul->src[1]->type != GGML_TYPE_F32 ||
  11292. mul->type != GGML_TYPE_F32) {
  11293. return false;
  11294. }
  11295. // if rms_norm is the B operand, then we don't handle broadcast
  11296. if (rms_norm == mul->src[1] &&
  11297. !ggml_are_same_shape(mul->src[0], rms_norm)) {
  11298. return false;
  11299. }
  11300. // rms_norm shader assumes contiguous rows
  11301. if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
  11302. return false;
  11303. }
  11304. }
  11305. auto const &mm_add_ok = [&](const ggml_tensor *mul, const ggml_tensor *add) {
  11306. const ggml_tensor *bias = add->src[0] == mul ? add->src[1] : add->src[0];
  11307. // mat-vec only
  11308. if (ggml_nrows(mul) != 1) {
  11309. return false;
  11310. }
  11311. // shaders assume the types match
  11312. if (mul->type != bias->type) {
  11313. return false;
  11314. }
  11315. // shaders reuse the D shape for bias
  11316. if (!ggml_are_same_shape(mul, bias) ||
  11317. !ggml_are_same_stride(mul, bias)) {
  11318. return false;
  11319. }
  11320. // unaligned bias isn't handled
  11321. if (get_misalign_bytes(ctx, bias) != 0) {
  11322. return false;
  11323. }
  11324. return true;
  11325. };
  11326. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT && ops.begin()[1] == GGML_OP_ADD) {
  11327. // additional constraints specific to this fusion
  11328. const ggml_tensor *mul = cgraph->nodes[node_idx];
  11329. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  11330. if (!mm_add_ok(mul, add)) {
  11331. return false;
  11332. }
  11333. if (ops.size() == 3) {
  11334. if (ops.begin()[2] != GGML_OP_ADD) {
  11335. return false;
  11336. }
  11337. if (!mm_add_ok(add, cgraph->nodes[node_idx + 2])) {
  11338. return false;
  11339. }
  11340. }
  11341. }
  11342. auto const &mmid_mul_ok = [&](const ggml_tensor *mmid, const ggml_tensor *mul) {
  11343. const ggml_tensor *scale = mul->src[1];
  11344. if (mmid != mul->src[0]) {
  11345. return false;
  11346. }
  11347. // mat-vec only
  11348. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  11349. return false;
  11350. }
  11351. // shaders assume the types match
  11352. if (mmid->type != scale->type) {
  11353. return false;
  11354. }
  11355. // shaders assume the bias is contiguous
  11356. if (!ggml_is_contiguous(scale)) {
  11357. return false;
  11358. }
  11359. // unaligned bias isn't handled
  11360. if (get_misalign_bytes(ctx, scale) != 0) {
  11361. return false;
  11362. }
  11363. // shader only indexes by expert index
  11364. if (scale->ne[0] != 1 ||
  11365. scale->ne[1] != mul->ne[1] ||
  11366. scale->ne[2] != 1 ||
  11367. scale->ne[3] != 1) {
  11368. return false;
  11369. }
  11370. return true;
  11371. };
  11372. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_ADD_ID) {
  11373. // additional constraints specific to this fusion
  11374. const ggml_tensor *mul = cgraph->nodes[node_idx];
  11375. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  11376. const ggml_tensor *bias = add->src[1];
  11377. if (mul != add->src[0]) {
  11378. return false;
  11379. }
  11380. // mat-vec only
  11381. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  11382. return false;
  11383. }
  11384. // shaders assume the types match
  11385. if (mul->type != bias->type) {
  11386. return false;
  11387. }
  11388. // shaders assume the bias is contiguous
  11389. if (!ggml_is_contiguous(bias)) {
  11390. return false;
  11391. }
  11392. // the ID tensor must be the same for mul_mat_id and add_id
  11393. if (mul->src[2] != add->src[2]) {
  11394. return false;
  11395. }
  11396. // unaligned bias isn't handled
  11397. if (get_misalign_bytes(ctx, bias) != 0) {
  11398. return false;
  11399. }
  11400. if (ops.size() == 3) {
  11401. if (ops.begin()[2] != GGML_OP_MUL) {
  11402. return false;
  11403. }
  11404. const ggml_tensor *mul = cgraph->nodes[node_idx + 2];
  11405. return mmid_mul_ok(add, mul);
  11406. }
  11407. }
  11408. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_MUL) {
  11409. // additional constraints specific to this fusion
  11410. const ggml_tensor *mmid = cgraph->nodes[node_idx];
  11411. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  11412. if (!mmid_mul_ok(mmid, mul)) {
  11413. return false;
  11414. }
  11415. }
  11416. return true;
  11417. }
  11418. static bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11419. int node_idx, topk_moe_mode mode) {
  11420. const ggml_tensor * softmax;
  11421. const ggml_tensor * weights;
  11422. const ggml_tensor * get_rows;
  11423. const ggml_tensor * argsort;
  11424. switch (mode) {
  11425. case TOPK_MOE_EARLY_SOFTMAX_NORM:
  11426. softmax = cgraph->nodes[node_idx + 0];
  11427. weights = cgraph->nodes[node_idx + 9];
  11428. get_rows = cgraph->nodes[node_idx + 4];
  11429. argsort = cgraph->nodes[node_idx + 2];
  11430. break;
  11431. case TOPK_MOE_SIGMOID_NORM_BIAS:
  11432. softmax = cgraph->nodes[node_idx + 0]; // really sigmoid
  11433. weights = cgraph->nodes[node_idx + 10];
  11434. get_rows = cgraph->nodes[node_idx + 5];
  11435. argsort = cgraph->nodes[node_idx + 3];
  11436. if (ggml_get_unary_op(softmax) != GGML_UNARY_OP_SIGMOID) {
  11437. return false;
  11438. }
  11439. // bias is expected to be 1D
  11440. if (ggml_nrows(cgraph->nodes[node_idx + 2]->src[1]) != 1 ||
  11441. !ggml_is_contiguous(cgraph->nodes[node_idx + 2]->src[1])) {
  11442. return false;
  11443. }
  11444. // sigmoid fusion seems to generate infinities on moltenvk
  11445. if (ctx->device->driver_id == vk::DriverId::eMoltenvk) {
  11446. return false;
  11447. }
  11448. break;
  11449. case TOPK_MOE_EARLY_SOFTMAX:
  11450. softmax = cgraph->nodes[node_idx + 0];
  11451. weights = cgraph->nodes[node_idx + 4];
  11452. get_rows = cgraph->nodes[node_idx + 4];
  11453. argsort = cgraph->nodes[node_idx + 2];
  11454. break;
  11455. case TOPK_MOE_LATE_SOFTMAX:
  11456. softmax = cgraph->nodes[node_idx + 4];
  11457. weights = cgraph->nodes[node_idx + 5];
  11458. get_rows = cgraph->nodes[node_idx + 2];
  11459. argsort = cgraph->nodes[node_idx + 0];
  11460. break;
  11461. default:
  11462. return false;
  11463. }
  11464. ggml_tensor * probs = get_rows->src[0];
  11465. if (probs->op != GGML_OP_RESHAPE) {
  11466. return false;
  11467. }
  11468. probs = probs->src[0];
  11469. ggml_tensor * selection_probs = argsort->src[0];
  11470. if (probs != selection_probs && mode != TOPK_MOE_SIGMOID_NORM_BIAS) {
  11471. return false;
  11472. }
  11473. if (!ggml_is_contiguous(softmax->src[0]) || !ggml_is_contiguous(weights)) {
  11474. return false;
  11475. }
  11476. if (softmax->op == GGML_OP_SOFT_MAX) {
  11477. const float * op_params = (const float *)softmax->op_params;
  11478. float scale = op_params[0];
  11479. float max_bias = op_params[1];
  11480. if (scale != 1.0f || max_bias != 0.0f) {
  11481. return false;
  11482. }
  11483. // don't fuse when masks or sinks are present
  11484. if (softmax->src[1] || softmax->src[2]) {
  11485. return false;
  11486. }
  11487. }
  11488. const int n_expert = softmax->ne[0];
  11489. if (n_expert > (1 << (num_topk_moe_pipelines-1))) {
  11490. return false;
  11491. }
  11492. if (!ctx->device->subgroup_arithmetic ||
  11493. !ctx->device->subgroup_shuffle ||
  11494. !ctx->device->subgroup_require_full_support ||
  11495. ctx->device->disable_fusion) {
  11496. return false;
  11497. }
  11498. return true;
  11499. }
  11500. static bool ggml_vk_can_fuse_rope_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11501. int node_idx) {
  11502. GGML_UNUSED(ctx);
  11503. const ggml_tensor *rope = cgraph->nodes[node_idx + 0];
  11504. const ggml_tensor *view = cgraph->nodes[node_idx + 1];
  11505. const ggml_tensor *set_rows = cgraph->nodes[node_idx + 2];
  11506. // ne3 not tested
  11507. if (rope->src[0]->ne[3] != 1) {
  11508. return false;
  11509. }
  11510. if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) {
  11511. return false;
  11512. }
  11513. if (set_rows->src[1]->type != GGML_TYPE_I64) {
  11514. return false;
  11515. }
  11516. // The view should flatten two dims of rope into one dim
  11517. if (!ggml_is_contiguous(view) ||
  11518. view->ne[0] != rope->ne[0] * rope->ne[1]) {
  11519. return false;
  11520. }
  11521. // Only norm/neox/mrope shaders have the fusion code
  11522. const int mode = ((const int32_t *) rope->op_params)[2];
  11523. if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_MROPE) {
  11524. return false;
  11525. }
  11526. return true;
  11527. }
  11528. // Check whether the tensors overlap in memory but are not equal.
  11529. // Fusions can potenitally overwrite src tensors in ways that are not prevented
  11530. // by ggml-alloc. If the fusion is entirely elementwise, then it's OK for them
  11531. // to overlap if they are exactly equal.
  11532. // XXX TODO this check is probably missing from several fusion optimizations.
  11533. static bool ggml_vk_tensors_overlap_but_not_equal(const ggml_tensor * a, const ggml_tensor * b) {
  11534. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)a->buffer->context;
  11535. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  11536. ggml_backend_vk_buffer_context * b_buf_ctx = (ggml_backend_vk_buffer_context *)b->buffer->context;
  11537. vk_buffer b_buf = b_buf_ctx->dev_buffer;
  11538. if (a_buf == b_buf) {
  11539. auto a_base = vk_tensor_offset(a) + a->view_offs;
  11540. auto a_size = ggml_nbytes(a);
  11541. auto b_base = vk_tensor_offset(b) + b->view_offs;
  11542. auto b_size = ggml_nbytes(b);
  11543. if (a_base == b_base && a_size == b_size) {
  11544. return false;
  11545. }
  11546. if ((b_base <= a_base && a_base < b_base + b_size) ||
  11547. (a_base <= b_base && b_base < a_base + a_size)) {
  11548. return true;
  11549. }
  11550. }
  11551. return false;
  11552. }
  11553. static bool ggml_vk_can_fuse_rms_norm_mul_rope(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11554. int node_idx) {
  11555. GGML_UNUSED(ctx);
  11556. const ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  11557. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  11558. const ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  11559. const int mode = ((const int32_t *) rope->op_params)[2];
  11560. // noncontig tensors aren't tested, and don't seem common in practice
  11561. if (!ggml_is_contiguous(rms) ||
  11562. !ggml_is_contiguous(mul) ||
  11563. !ggml_is_contiguous(rope)) {
  11564. return false;
  11565. }
  11566. // only norm/neox are handled in the shader
  11567. if (mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_NORMAL) {
  11568. return false;
  11569. }
  11570. // shared memory size for passing data from mul->rope
  11571. if (mul->ne[0] > 1024) {
  11572. return false;
  11573. }
  11574. // must not overwrite srcs in a way that's not elementwise
  11575. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  11576. if (ggml_vk_tensors_overlap_but_not_equal(rms->src[0], rope) ||
  11577. ggml_vk_tensors_overlap_but_not_equal(other_src, rope)) {
  11578. return false;
  11579. }
  11580. // conditions for pipeline creation
  11581. if (!(ctx->device->float_controls_rte_fp16 &&
  11582. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= ctx->device->properties.limits.maxPushConstantsSize)) {
  11583. return false;
  11584. }
  11585. return true;
  11586. }
  11587. static uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) {
  11588. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  11589. if (first_node->op != GGML_OP_ADD) {
  11590. return 0;
  11591. }
  11592. if (!ctx->device->multi_add) {
  11593. return 0;
  11594. }
  11595. int32_t num_adds = 1;
  11596. while (node_idx + num_adds < cgraph->n_nodes &&
  11597. cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD &&
  11598. num_adds < MAX_FUSED_ADDS) {
  11599. num_adds++;
  11600. }
  11601. // The shader currently requires same shapes (but different strides are allowed),
  11602. // everything f32, and no misalignment
  11603. for (int32_t i = 0; i < num_adds; ++i) {
  11604. const ggml_tensor *next_node = cgraph->nodes[node_idx + i];
  11605. if (!ggml_are_same_shape(first_node, next_node->src[0]) ||
  11606. !ggml_are_same_shape(first_node, next_node->src[1]) ||
  11607. next_node->type != GGML_TYPE_F32 ||
  11608. next_node->src[0]->type != GGML_TYPE_F32 ||
  11609. next_node->src[1]->type != GGML_TYPE_F32 ||
  11610. get_misalign_bytes(ctx, next_node) ||
  11611. get_misalign_bytes(ctx, next_node->src[0]) ||
  11612. get_misalign_bytes(ctx, next_node->src[1])) {
  11613. num_adds = i;
  11614. }
  11615. }
  11616. // Verify we can fuse these
  11617. ggml_op adds[MAX_FUSED_ADDS];
  11618. for (int32_t i = 0; i < num_adds; ++i) {
  11619. adds[i] = GGML_OP_ADD;
  11620. }
  11621. // decrease num_adds if they can't all be fused
  11622. while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) {
  11623. num_adds--;
  11624. }
  11625. // a single add is not "fused", so just return zero
  11626. if (num_adds == 1) {
  11627. return 0;
  11628. }
  11629. return num_adds;
  11630. }
  11631. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  11632. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  11633. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11634. if (vk_instance.debug_utils_support) {
  11635. vk::DebugUtilsLabelEXT dul = {};
  11636. dul.pLabelName = "ggml_backend_vk_graph_compute";
  11637. dul.color = std::array<float,4>{1.0f, 1.0f, 1.0f, 1.0f};
  11638. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(ctx->device->compute_queue.queue, reinterpret_cast<VkDebugUtilsLabelEXT*>(&dul));
  11639. }
  11640. ctx->prealloc_size_add_rms_partials_offset = 0;
  11641. ctx->do_add_rms_partials = false;
  11642. ctx->do_add_rms_partials_offset_calculation = false;
  11643. int last_node = cgraph->n_nodes - 1;
  11644. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  11645. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  11646. last_node -= 1;
  11647. }
  11648. // Reserve tensor context space for all nodes
  11649. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  11650. bool first_node_in_batch = true; // true if next node will be first node in a batch
  11651. int submit_node_idx = 0; // index to first node in a batch
  11652. vk_context compute_ctx;
  11653. if (vk_perf_logger_enabled) {
  11654. // allocate/resize the query pool
  11655. if (ctx->num_queries < cgraph->n_nodes + 1) {
  11656. if (ctx->query_pool) {
  11657. ctx->device->device.destroyQueryPool(ctx->query_pool);
  11658. }
  11659. vk::QueryPoolCreateInfo query_create_info;
  11660. query_create_info.queryType = vk::QueryType::eTimestamp;
  11661. query_create_info.queryCount = cgraph->n_nodes + 100;
  11662. ctx->query_pool = ctx->device->device.createQueryPool(query_create_info);
  11663. ctx->num_queries = query_create_info.queryCount;
  11664. ctx->query_fusion_names.resize(ctx->num_queries);
  11665. ctx->query_fusion_node_count.resize(ctx->num_queries);
  11666. ctx->query_nodes.resize(ctx->num_queries);
  11667. ctx->query_node_idx.resize(ctx->num_queries);
  11668. }
  11669. ctx->device->device.resetQueryPool(ctx->query_pool, 0, cgraph->n_nodes+1);
  11670. std::fill(ctx->query_fusion_names.begin(), ctx->query_fusion_names.end(), nullptr);
  11671. std::fill(ctx->query_fusion_node_count.begin(), ctx->query_fusion_node_count.end(), 0);
  11672. std::fill(ctx->query_nodes.begin(), ctx->query_nodes.end(), nullptr);
  11673. std::fill(ctx->query_node_idx.begin(), ctx->query_node_idx.end(), 0);
  11674. GGML_ASSERT(ctx->compute_ctx.expired());
  11675. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11676. ctx->compute_ctx = compute_ctx;
  11677. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11678. ctx->query_idx = 0;
  11679. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  11680. }
  11681. ctx->prealloc_y_last_pipeline_used = nullptr;
  11682. ctx->prealloc_y_last_tensor_used = nullptr;
  11683. if (ctx->prealloc_size_add_rms_partials) {
  11684. ggml_vk_preallocate_buffers(ctx, nullptr);
  11685. if (ctx->compute_ctx.expired()) {
  11686. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11687. ctx->compute_ctx = compute_ctx;
  11688. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11689. } else {
  11690. compute_ctx = ctx->compute_ctx.lock();
  11691. }
  11692. // initialize partial sums to zero.
  11693. ggml_vk_buffer_memset_async(compute_ctx, ctx->prealloc_add_rms_partials, 0, 0, ctx->prealloc_size_add_rms_partials);
  11694. ggml_vk_sync_buffers(ctx, compute_ctx);
  11695. }
  11696. // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution.
  11697. // Estimate the amount of matmul work by looking at the weight matrix size, and submit every 100MB
  11698. // (and scaled down based on model size, so smaller models submit earlier).
  11699. // Also submit at least every 100 nodes, in case there are workloads without as much matmul.
  11700. int nodes_per_submit = 100;
  11701. int submitted_nodes = 0;
  11702. int submit_count = 0;
  11703. uint64_t mul_mat_bytes = 0;
  11704. uint64_t total_mul_mat_bytes = 0;
  11705. uint64_t mul_mat_bytes_per_submit = std::min(uint64_t(100*1000*1000), ctx->last_total_mul_mat_bytes / 40u);
  11706. for (int i = 0; i < cgraph->n_nodes; i++) {
  11707. if (first_node_in_batch) {
  11708. submit_node_idx = i;
  11709. }
  11710. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  11711. auto bytes = ggml_nbytes(cgraph->nodes[i]->src[0]);
  11712. mul_mat_bytes += bytes;
  11713. total_mul_mat_bytes += bytes;
  11714. }
  11715. ctx->fused_topk_moe_mode = TOPK_MOE_COUNT;
  11716. ctx->fused_topk_moe_scale = false;
  11717. const char *fusion_string {};
  11718. if (!ctx->device->disable_fusion) {
  11719. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  11720. if (num_adds) {
  11721. ctx->num_additional_fused_ops = num_adds - 1;
  11722. fusion_string = "MULTI_ADD";
  11723. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_ADD })) {
  11724. ctx->num_additional_fused_ops = 2;
  11725. fusion_string = "MUL_MAT_ADD_ADD";
  11726. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD })) {
  11727. ctx->num_additional_fused_ops = 1;
  11728. fusion_string = "MUL_MAT_ADD";
  11729. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_MUL })) {
  11730. ctx->num_additional_fused_ops = 2;
  11731. fusion_string = "MUL_MAT_ID_ADD_ID_MUL";
  11732. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID })) {
  11733. ctx->num_additional_fused_ops = 1;
  11734. fusion_string = "MUL_MAT_ID_ADD_ID";
  11735. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_MUL })) {
  11736. ctx->num_additional_fused_ops = 1;
  11737. fusion_string = "MUL_MAT_ID_MUL";
  11738. } 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 }) &&
  11739. ggml_check_edges(cgraph, i, rms_norm_mul_rope_view_set_rows_edges) &&
  11740. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i) &&
  11741. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i + 2)) {
  11742. ctx->num_additional_fused_ops = 4;
  11743. fusion_string = "RMS_NORM_MUL_ROPE_VIEW_SET_ROWS";
  11744. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE })&&
  11745. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i)) {
  11746. ctx->num_additional_fused_ops = 2;
  11747. fusion_string = "RMS_NORM_MUL_ROPE";
  11748. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  11749. ctx->num_additional_fused_ops = 1;
  11750. fusion_string = "RMS_NORM_MUL";
  11751. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 2 }) &&
  11752. ggml_check_edges(cgraph, i, rope_view_set_rows_edges) &&
  11753. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i)) {
  11754. ctx->num_additional_fused_ops = 2;
  11755. fusion_string = "ROPE_VIEW_SET_ROWS";
  11756. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax_norm, { i + 3, i + 9 }) &&
  11757. ggml_check_edges(cgraph, i, topk_moe_early_softmax_norm_edges) &&
  11758. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX_NORM)) {
  11759. ctx->num_additional_fused_ops = topk_moe_early_softmax_norm.size() - 1;
  11760. // view of argsort writes to memory
  11761. ctx->fused_ops_write_mask |= 1 << 3;
  11762. ctx->fused_topk_moe_mode = TOPK_MOE_EARLY_SOFTMAX_NORM;
  11763. fusion_string = "TOPK_MOE_EARLY_SOFTMAX_NORM";
  11764. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_sigmoid_norm_bias, { i + 4, i + 10 }) &&
  11765. ggml_check_edges(cgraph, i, topk_moe_sigmoid_norm_bias_edges) &&
  11766. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_SIGMOID_NORM_BIAS)) {
  11767. ctx->num_additional_fused_ops = topk_moe_sigmoid_norm_bias.size() - 1;
  11768. // view of argsort writes to memory
  11769. ctx->fused_ops_write_mask |= 1 << 4;
  11770. ctx->fused_topk_moe_mode = TOPK_MOE_SIGMOID_NORM_BIAS;
  11771. fusion_string = "TOPK_MOE_SIGMOID_NORM_BIAS";
  11772. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax, { i + 3, i + 4 }) &&
  11773. ggml_check_edges(cgraph, i, topk_moe_early_softmax_edges) &&
  11774. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX)) {
  11775. ctx->num_additional_fused_ops = topk_moe_early_softmax.size() - 1;
  11776. // view of argsort writes to memory
  11777. ctx->fused_ops_write_mask |= 1 << 3;
  11778. ctx->fused_topk_moe_mode = TOPK_MOE_EARLY_SOFTMAX;
  11779. fusion_string = "TOPK_MOE_EARLY_SOFTMAX";
  11780. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_late_softmax, { i + 1, i + 5 }) &&
  11781. ggml_check_edges(cgraph, i, topk_moe_late_softmax_edges) &&
  11782. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_LATE_SOFTMAX)) {
  11783. ctx->num_additional_fused_ops = topk_moe_late_softmax.size() - 1;
  11784. // view of argsort writes to memory
  11785. ctx->fused_ops_write_mask |= 1 << 1;
  11786. ctx->fused_topk_moe_mode = TOPK_MOE_LATE_SOFTMAX;
  11787. fusion_string = "TOPK_MOE_LATE_SOFTMAX";
  11788. }
  11789. if (ctx->fused_topk_moe_mode != TOPK_MOE_COUNT) {
  11790. // Look for an additional scale op to fuse - occurs in deepseek2 and nemotron3 nano.
  11791. if (ggml_can_fuse_subgraph(cgraph, i + ctx->num_additional_fused_ops - 1, { GGML_OP_DIV, GGML_OP_RESHAPE, GGML_OP_SCALE }, { i + ctx->num_additional_fused_ops + 1 }) ||
  11792. ggml_can_fuse_subgraph(cgraph, i + ctx->num_additional_fused_ops, { GGML_OP_GET_ROWS, GGML_OP_SCALE }, { i + ctx->num_additional_fused_ops + 1 })) {
  11793. ctx->fused_topk_moe_scale = true;
  11794. ctx->num_additional_fused_ops++;
  11795. }
  11796. }
  11797. }
  11798. ctx->fused_ops_write_mask |= 1 << ctx->num_additional_fused_ops;
  11799. // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining)
  11800. bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5;
  11801. bool submit = (submitted_nodes >= nodes_per_submit) ||
  11802. (mul_mat_bytes_per_submit != 0 && mul_mat_bytes >= mul_mat_bytes_per_submit) ||
  11803. (i + ctx->num_additional_fused_ops >= last_node) ||
  11804. (almost_ready && !ctx->almost_ready_fence_pending);
  11805. 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);
  11806. if (vk_perf_logger_enabled && enqueued) {
  11807. if (ctx->compute_ctx.expired()) {
  11808. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11809. ctx->compute_ctx = compute_ctx;
  11810. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11811. } else {
  11812. compute_ctx = ctx->compute_ctx.lock();
  11813. }
  11814. if (!vk_perf_logger_concurrent) {
  11815. // track a single node/fusion for the current query
  11816. ctx->query_nodes[ctx->query_idx] = cgraph->nodes[i];
  11817. ctx->query_fusion_names[ctx->query_idx] = fusion_string;
  11818. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  11819. } else {
  11820. // track a fusion string and number of fused ops for the current node_idx
  11821. ctx->query_fusion_names[i] = fusion_string;
  11822. ctx->query_fusion_node_count[i] = ctx->num_additional_fused_ops;
  11823. }
  11824. }
  11825. if (enqueued) {
  11826. ++submitted_nodes;
  11827. #ifndef GGML_VULKAN_CHECK_RESULTS
  11828. if (first_node_in_batch) {
  11829. first_node_in_batch = false;
  11830. }
  11831. #endif
  11832. }
  11833. if (submit && enqueued) {
  11834. first_node_in_batch = true;
  11835. submitted_nodes = 0;
  11836. mul_mat_bytes = 0;
  11837. if (submit_count < 3) {
  11838. mul_mat_bytes_per_submit *= 2;
  11839. }
  11840. submit_count++;
  11841. }
  11842. i += ctx->num_additional_fused_ops;
  11843. ctx->num_additional_fused_ops = 0;
  11844. ctx->fused_ops_write_mask = 0;
  11845. }
  11846. ctx->last_total_mul_mat_bytes = total_mul_mat_bytes;
  11847. if (vk_perf_logger_enabled) {
  11848. // End the command buffer and submit/wait
  11849. GGML_ASSERT(!ctx->compute_ctx.expired());
  11850. compute_ctx = ctx->compute_ctx.lock();
  11851. ggml_vk_ctx_end(compute_ctx);
  11852. ggml_vk_submit(compute_ctx, ctx->device->fence);
  11853. VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences");
  11854. ctx->device->device.resetFences({ ctx->device->fence });
  11855. // Get the results and pass them to the logger
  11856. std::vector<uint64_t> timestamps(cgraph->n_nodes + 1);
  11857. 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");
  11858. if (!vk_perf_logger_concurrent) {
  11859. // Log each op separately
  11860. for (int i = 1; i < ctx->query_idx; i++) {
  11861. auto node = ctx->query_nodes[i];
  11862. auto name = ctx->query_fusion_names[i];
  11863. ctx->perf_logger->log_timing(node, name, uint64_t((timestamps[i] - timestamps[i-1]) * ctx->device->properties.limits.timestampPeriod));
  11864. }
  11865. } else {
  11866. // Log each group of nodes
  11867. int prev_node_idx = 0;
  11868. for (int i = 1; i < ctx->query_idx; i++) {
  11869. auto cur_node_idx = ctx->query_node_idx[i];
  11870. std::vector<ggml_tensor *> nodes;
  11871. std::vector<const char *> names;
  11872. for (int node_idx = prev_node_idx; node_idx < cur_node_idx; ++node_idx) {
  11873. if (ggml_op_is_empty(cgraph->nodes[node_idx]->op)) {
  11874. continue;
  11875. }
  11876. nodes.push_back(cgraph->nodes[node_idx]);
  11877. names.push_back(ctx->query_fusion_names[node_idx]);
  11878. node_idx += ctx->query_fusion_node_count[node_idx];
  11879. }
  11880. prev_node_idx = cur_node_idx;
  11881. ctx->perf_logger->log_timing(nodes, names, uint64_t((timestamps[i] - timestamps[i-1]) * ctx->device->properties.limits.timestampPeriod));
  11882. }
  11883. }
  11884. ctx->perf_logger->print_timings();
  11885. }
  11886. if (!ctx->device->support_async) {
  11887. ggml_vk_synchronize(ctx);
  11888. }
  11889. return GGML_STATUS_SUCCESS;
  11890. UNUSED(backend);
  11891. }
  11892. // Sort the graph for improved parallelism.
  11893. static void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph)
  11894. {
  11895. VK_LOG_DEBUG("ggml_vk_graph_optimize(" << graph->n_nodes << " nodes)");
  11896. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11897. if (ctx->device->disable_graph_optimize) {
  11898. return;
  11899. }
  11900. auto const &is_empty = [](ggml_tensor * node) -> bool {
  11901. 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;
  11902. };
  11903. auto const &is_src_of = [](const ggml_tensor *dst, const ggml_tensor *src) -> bool {
  11904. for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) {
  11905. if (dst->src[s] == src) {
  11906. return true;
  11907. }
  11908. }
  11909. // implicit dependency if they view the same tensor
  11910. const ggml_tensor *dst2 = dst->view_src ? dst->view_src : dst;
  11911. const ggml_tensor *src2 = src->view_src ? src->view_src : src;
  11912. if (dst2 == src2) {
  11913. return true;
  11914. }
  11915. return false;
  11916. };
  11917. std::vector<ggml_tensor *> new_order;
  11918. std::vector<bool> used(graph->n_nodes, false);
  11919. std::set<ggml_tensor *> used_node_set;
  11920. int first_unused = 0;
  11921. while (first_unused < graph->n_nodes) {
  11922. std::vector<int> current_set;
  11923. // Check for fusion patterns and avoid reordering them
  11924. auto const &match_pattern = [&](const std::initializer_list<ggml_op> &pattern, int start) -> bool {
  11925. if (start + (int)pattern.size() <= graph->n_nodes) {
  11926. bool is_pattern = true;
  11927. for (size_t j = 0; j < pattern.size(); ++j) {
  11928. if (graph->nodes[start + j]->op != pattern.begin()[j] || used[start + j]) {
  11929. is_pattern = false;
  11930. }
  11931. }
  11932. return is_pattern;
  11933. }
  11934. return false;
  11935. };
  11936. auto const &keep_pattern = [&](const std::initializer_list<ggml_op> &pattern) -> bool {
  11937. if (match_pattern(pattern, first_unused)) {
  11938. for (size_t j = 0; j < pattern.size(); ++j) {
  11939. new_order.push_back(graph->nodes[first_unused + j]);
  11940. used_node_set.insert(graph->nodes[first_unused + j]);
  11941. used[first_unused + j] = true;
  11942. }
  11943. while (first_unused < graph->n_nodes && used[first_unused]) {
  11944. first_unused++;
  11945. }
  11946. return true;
  11947. }
  11948. return false;
  11949. };
  11950. if (keep_pattern(topk_moe_early_softmax_norm)) {
  11951. continue;
  11952. }
  11953. if (keep_pattern(topk_moe_sigmoid_norm_bias)) {
  11954. continue;
  11955. }
  11956. if (keep_pattern(topk_moe_early_softmax)) {
  11957. continue;
  11958. }
  11959. if (keep_pattern(topk_moe_late_softmax)) {
  11960. continue;
  11961. }
  11962. // First, grab the next unused node.
  11963. current_set.push_back(first_unused);
  11964. // Loop through the next N nodes. Grab any that don't depend on other nodes that
  11965. // haven't already been run. Nodes that have already been run have used[i] set
  11966. // to true. Allow nodes that depend on the previous node if it's a fusion pattern
  11967. // that we support (e.g. RMS_NORM + MUL).
  11968. // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes.
  11969. // The goal is to not interleave real and view nodes in a way that breaks fusion.
  11970. const int NUM_TO_CHECK = 20;
  11971. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11972. if (used[j]) {
  11973. continue;
  11974. }
  11975. if (is_empty(graph->nodes[j])) {
  11976. continue;
  11977. }
  11978. // Don't pull forward nodes from fusion patterns
  11979. if (match_pattern(topk_moe_early_softmax_norm, j) ||
  11980. match_pattern(topk_moe_sigmoid_norm_bias, j) ||
  11981. match_pattern(topk_moe_early_softmax, j) ||
  11982. match_pattern(topk_moe_late_softmax, j)) {
  11983. continue;
  11984. }
  11985. bool ok = true;
  11986. for (int c = first_unused; c < j; ++c) {
  11987. if (!used[c] &&
  11988. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11989. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL) &&
  11990. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT && graph->nodes[j]->op == GGML_OP_ADD) &&
  11991. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_ADD_ID) &&
  11992. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_MUL) &&
  11993. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_ADD && graph->nodes[j]->op == GGML_OP_ADD)) {
  11994. ok = false;
  11995. break;
  11996. }
  11997. }
  11998. if (ok) {
  11999. current_set.push_back(j);
  12000. int rope_idx = j;
  12001. // When we've found RMS_NORM + MUL, try to find a ROPE that uses it
  12002. if (j > 0 &&
  12003. graph->nodes[j]->op == GGML_OP_MUL &&
  12004. graph->nodes[j-1]->op == GGML_OP_RMS_NORM) {
  12005. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  12006. if (graph->nodes[k]->op == GGML_OP_ROPE &&
  12007. graph->nodes[k]->src[0] == graph->nodes[j] &&
  12008. // Check that other srcs are already valid
  12009. graph->nodes[k]->src[1]->op == GGML_OP_NONE &&
  12010. (graph->nodes[k]->src[2] == nullptr || graph->nodes[k]->src[2]->op == GGML_OP_NONE)) {
  12011. rope_idx = k;
  12012. current_set.push_back(rope_idx);
  12013. used[rope_idx] = true;
  12014. break;
  12015. }
  12016. }
  12017. }
  12018. // Look for ROPE + VIEW + SET_ROWS and make them consecutive
  12019. if (graph->nodes[rope_idx]->op == GGML_OP_ROPE) {
  12020. int view_idx = -1;
  12021. int set_rows_idx = -1;
  12022. for (int k = rope_idx+1; k < std::min(rope_idx + 10, graph->n_nodes); ++k) {
  12023. if (view_idx == -1 &&
  12024. graph->nodes[k]->op == GGML_OP_VIEW &&
  12025. graph->nodes[k]->src[0] == graph->nodes[rope_idx]) {
  12026. view_idx = k;
  12027. continue;
  12028. }
  12029. if (view_idx != -1 &&
  12030. set_rows_idx == -1 &&
  12031. graph->nodes[k]->op == GGML_OP_SET_ROWS &&
  12032. graph->nodes[k]->src[0] == graph->nodes[view_idx]) {
  12033. set_rows_idx = k;
  12034. break;
  12035. }
  12036. }
  12037. if (set_rows_idx != -1) {
  12038. current_set.push_back(view_idx);
  12039. current_set.push_back(set_rows_idx);
  12040. used[view_idx] = true;
  12041. used[set_rows_idx] = true;
  12042. }
  12043. }
  12044. // Look for MUL_MAT_ID + ADD_ID + MUL
  12045. if (j > 0 &&
  12046. graph->nodes[j]->op == GGML_OP_ADD_ID &&
  12047. graph->nodes[j-1]->op == GGML_OP_MUL_MAT_ID) {
  12048. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  12049. if (graph->nodes[k]->op == GGML_OP_MUL &&
  12050. graph->nodes[k]->src[0] == graph->nodes[j] &&
  12051. // src1 must either be weights or already processed
  12052. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  12053. current_set.push_back(k);
  12054. used[k] = true;
  12055. break;
  12056. }
  12057. }
  12058. }
  12059. // Look for MUL_MAT + ADD + ADD
  12060. if (j > 0 &&
  12061. graph->nodes[j]->op == GGML_OP_ADD &&
  12062. graph->nodes[j-1]->op == GGML_OP_MUL_MAT) {
  12063. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  12064. if (graph->nodes[k]->op == GGML_OP_ADD &&
  12065. graph->nodes[k]->src[0] == graph->nodes[j] &&
  12066. // src1 must either be weights or already processed
  12067. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  12068. current_set.push_back(k);
  12069. used[k] = true;
  12070. break;
  12071. }
  12072. }
  12073. }
  12074. }
  12075. }
  12076. // Second pass grabs view nodes.
  12077. // Skip this if it would break a fusion optimization (don't split up add->rms_norm or add->add).
  12078. if (graph->nodes[current_set.back()]->op != GGML_OP_ADD) {
  12079. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  12080. if (used[j]) {
  12081. continue;
  12082. }
  12083. if (!is_empty(graph->nodes[j])) {
  12084. continue;
  12085. }
  12086. bool ok = true;
  12087. for (int c = first_unused; c < j; ++c) {
  12088. bool c_in_current_set = std::find(current_set.begin(), current_set.end(), c) != current_set.end();
  12089. // skip views whose srcs haven't been processed.
  12090. if (!used[c] &&
  12091. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  12092. !c_in_current_set) {
  12093. ok = false;
  12094. break;
  12095. }
  12096. }
  12097. if (ok) {
  12098. current_set.push_back(j);
  12099. }
  12100. }
  12101. }
  12102. // Push the current set into new_order
  12103. for (auto c : current_set) {
  12104. new_order.push_back(graph->nodes[c]);
  12105. used_node_set.insert(graph->nodes[c]);
  12106. used[c] = true;
  12107. }
  12108. while (first_unused < graph->n_nodes && used[first_unused]) {
  12109. first_unused++;
  12110. }
  12111. }
  12112. // Replace the graph with the new order.
  12113. for (int i = 0; i < graph->n_nodes; ++i) {
  12114. graph->nodes[i] = new_order[i];
  12115. }
  12116. }
  12117. static void ggml_backend_vk_event_record(ggml_backend_t backend, ggml_backend_event_t event) {
  12118. VK_LOG_DEBUG("ggml_backend_vk_event_record(backend=" << backend << ", event=" << event << ")");
  12119. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  12120. vk_event *vkev = (vk_event *)event->context;
  12121. vk_context transfer_ctx;
  12122. if (ctx->transfer_ctx.expired()) {
  12123. // Initialize new transfer context
  12124. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  12125. ctx->transfer_ctx = transfer_ctx;
  12126. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  12127. } else {
  12128. transfer_ctx = ctx->transfer_ctx.lock();
  12129. }
  12130. // the backend interface doesn't have an explicit reset, so reset it here
  12131. // before we record the command to set it
  12132. ctx->device->device.resetEvent(vkev->event);
  12133. ctx->device->device.resetFences({ vkev->fence });
  12134. ggml_vk_set_event(transfer_ctx, vkev->event);
  12135. ggml_vk_ctx_end(transfer_ctx);
  12136. ggml_vk_submit(transfer_ctx, {vkev->fence});
  12137. ctx->submit_pending = true;
  12138. ctx->transfer_ctx.reset();
  12139. }
  12140. static void ggml_backend_vk_event_wait(ggml_backend_t backend, ggml_backend_event_t event) {
  12141. VK_LOG_DEBUG("ggml_backend_vk_event_wait(backend=" << backend << ", event=" << event << ")");
  12142. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  12143. vk_event *vkev = (vk_event *)event->context;
  12144. vk_context transfer_ctx;
  12145. if (ctx->transfer_ctx.expired()) {
  12146. // Initialize new transfer context
  12147. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  12148. ctx->transfer_ctx = transfer_ctx;
  12149. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  12150. } else {
  12151. transfer_ctx = ctx->transfer_ctx.lock();
  12152. }
  12153. ggml_vk_wait_events(transfer_ctx, {vkev->event});
  12154. ggml_vk_ctx_end(transfer_ctx);
  12155. ctx->transfer_ctx.reset();
  12156. }
  12157. // TODO: enable async and synchronize
  12158. static ggml_backend_i ggml_backend_vk_interface = {
  12159. /* .get_name = */ ggml_backend_vk_name,
  12160. /* .free = */ ggml_backend_vk_free,
  12161. /* .set_tensor_async = */ ggml_backend_vk_set_tensor_async,
  12162. /* .get_tensor_async = */ ggml_backend_vk_get_tensor_async,
  12163. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  12164. /* .synchronize = */ ggml_backend_vk_synchronize,
  12165. /* .graph_plan_create = */ NULL,
  12166. /* .graph_plan_free = */ NULL,
  12167. /* .graph_plan_update = */ NULL,
  12168. /* .graph_plan_compute = */ NULL,
  12169. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  12170. /* .event_record = */ ggml_backend_vk_event_record,
  12171. /* .event_wait = */ ggml_backend_vk_event_wait,
  12172. /* .graph_optimize = */ ggml_vk_graph_optimize,
  12173. };
  12174. static ggml_guid_t ggml_backend_vk_guid() {
  12175. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  12176. return &guid;
  12177. }
  12178. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  12179. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  12180. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  12181. ggml_vk_init(ctx, dev_num);
  12182. ggml_backend_t vk_backend = new ggml_backend {
  12183. /* .guid = */ ggml_backend_vk_guid(),
  12184. /* .iface = */ ggml_backend_vk_interface,
  12185. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  12186. /* .context = */ ctx,
  12187. };
  12188. if (!ctx->device->support_async) {
  12189. vk_backend->iface.get_tensor_async = nullptr;
  12190. }
  12191. return vk_backend;
  12192. }
  12193. bool ggml_backend_is_vk(ggml_backend_t backend) {
  12194. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  12195. }
  12196. int ggml_backend_vk_get_device_count() {
  12197. return ggml_vk_get_device_count();
  12198. }
  12199. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  12200. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  12201. int dev_idx = vk_instance.device_indices[device];
  12202. ggml_vk_get_device_description(dev_idx, description, description_size);
  12203. }
  12204. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  12205. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  12206. GGML_ASSERT(device < (int) vk_instance.device_supports_membudget.size());
  12207. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  12208. vk::PhysicalDeviceMemoryBudgetPropertiesEXT budgetprops;
  12209. vk::PhysicalDeviceMemoryProperties2 memprops = {};
  12210. const bool membudget_supported = vk_instance.device_supports_membudget[device];
  12211. const bool is_integrated_gpu = vkdev.getProperties().deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  12212. if (membudget_supported) {
  12213. memprops.pNext = &budgetprops;
  12214. }
  12215. vkdev.getMemoryProperties2(&memprops);
  12216. *total = 0;
  12217. *free = 0;
  12218. for (uint32_t i = 0; i < memprops.memoryProperties.memoryHeapCount; ++i) {
  12219. const vk::MemoryHeap & heap = memprops.memoryProperties.memoryHeaps[i];
  12220. if (is_integrated_gpu || (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal)) {
  12221. *total += heap.size;
  12222. if (membudget_supported && i < budgetprops.heapUsage.size()) {
  12223. *free += budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
  12224. } else {
  12225. *free += heap.size;
  12226. }
  12227. }
  12228. }
  12229. }
  12230. static vk::PhysicalDeviceType ggml_backend_vk_get_device_type(int device_idx) {
  12231. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  12232. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  12233. vk::PhysicalDeviceProperties2 props = {};
  12234. device.getProperties2(&props);
  12235. return props.properties.deviceType;
  12236. }
  12237. static std::string ggml_backend_vk_get_device_pci_id(int device_idx) {
  12238. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  12239. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  12240. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  12241. bool ext_support = false;
  12242. for (const auto& properties : ext_props) {
  12243. if (strcmp("VK_EXT_pci_bus_info", properties.extensionName) == 0) {
  12244. ext_support = true;
  12245. break;
  12246. }
  12247. }
  12248. if (!ext_support) {
  12249. return "";
  12250. }
  12251. vk::PhysicalDeviceProperties2 props = {};
  12252. vk::PhysicalDevicePCIBusInfoPropertiesEXT pci_bus_info = {};
  12253. props.pNext = &pci_bus_info;
  12254. device.getProperties2(&props);
  12255. const uint32_t pci_domain = pci_bus_info.pciDomain;
  12256. const uint32_t pci_bus = pci_bus_info.pciBus;
  12257. const uint32_t pci_device = pci_bus_info.pciDevice;
  12258. const uint8_t pci_function = (uint8_t) pci_bus_info.pciFunction; // pci function is between 0 and 7, prevent printf overflow warning
  12259. char pci_bus_id[16] = {};
  12260. snprintf(pci_bus_id, sizeof(pci_bus_id), "%04x:%02x:%02x.%x", pci_domain, pci_bus, pci_device, pci_function);
  12261. return std::string(pci_bus_id);
  12262. }
  12263. //////////////////////////
  12264. struct ggml_backend_vk_device_context {
  12265. size_t device;
  12266. std::string name;
  12267. std::string description;
  12268. bool is_integrated_gpu;
  12269. std::string pci_bus_id;
  12270. int op_offload_min_batch_size;
  12271. };
  12272. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  12273. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12274. return ctx->name.c_str();
  12275. }
  12276. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  12277. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12278. return ctx->description.c_str();
  12279. }
  12280. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  12281. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  12282. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  12283. }
  12284. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  12285. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12286. return ggml_backend_vk_buffer_type(ctx->device);
  12287. }
  12288. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  12289. UNUSED(dev);
  12290. return ggml_backend_vk_host_buffer_type();
  12291. }
  12292. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  12293. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12294. return ctx->is_integrated_gpu ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
  12295. }
  12296. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  12297. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12298. props->name = ggml_backend_vk_device_get_name(dev);
  12299. props->description = ggml_backend_vk_device_get_description(dev);
  12300. props->type = ggml_backend_vk_device_get_type(dev);
  12301. props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str();
  12302. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  12303. props->caps = {
  12304. /* .async = */ true,
  12305. /* .host_buffer = */ true,
  12306. /* .buffer_from_host_ptr = */ false,
  12307. /* .events = */ true,
  12308. };
  12309. }
  12310. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  12311. UNUSED(params);
  12312. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12313. return ggml_backend_vk_init(ctx->device);
  12314. }
  12315. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  12316. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12317. const vk_device& device = ggml_vk_get_device(ctx->device);
  12318. const bool uses_bda = (op->op == GGML_OP_IM2COL || op->op == GGML_OP_IM2COL_3D) &&
  12319. device->shader_int64 && device->buffer_device_address;
  12320. auto const & tensor_size_supported = [&](size_t tensor_size) {
  12321. if (tensor_size > device->max_buffer_size) {
  12322. return false;
  12323. }
  12324. // For im2col shaders using BDA, maxStorageBufferRange limit doesn't apply.
  12325. // If shader64BitIndexing is enabled, maxStorageBufferRange limit doesn't apply.
  12326. if (!uses_bda && !device->shader_64b_indexing) {
  12327. if (tensor_size > device->properties.limits.maxStorageBufferRange) {
  12328. return false;
  12329. }
  12330. }
  12331. return true;
  12332. };
  12333. // reject any tensors larger than the max buffer size
  12334. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12335. if (op->src[i] && !tensor_size_supported(ggml_nbytes(op->src[i]))) {
  12336. return false;
  12337. }
  12338. }
  12339. if (!tensor_size_supported(ggml_nbytes(op))) {
  12340. return false;
  12341. }
  12342. switch (op->op) {
  12343. case GGML_OP_UNARY:
  12344. switch (ggml_get_unary_op(op)) {
  12345. case GGML_UNARY_OP_EXP:
  12346. case GGML_UNARY_OP_GELU:
  12347. case GGML_UNARY_OP_GELU_ERF:
  12348. case GGML_UNARY_OP_GELU_QUICK:
  12349. case GGML_UNARY_OP_SILU:
  12350. case GGML_UNARY_OP_RELU:
  12351. case GGML_UNARY_OP_XIELU:
  12352. case GGML_UNARY_OP_NEG:
  12353. case GGML_UNARY_OP_TANH:
  12354. case GGML_UNARY_OP_SIGMOID:
  12355. case GGML_UNARY_OP_HARDSIGMOID:
  12356. case GGML_UNARY_OP_HARDSWISH:
  12357. case GGML_UNARY_OP_ABS:
  12358. case GGML_UNARY_OP_SOFTPLUS:
  12359. case GGML_UNARY_OP_STEP:
  12360. case GGML_UNARY_OP_ROUND:
  12361. case GGML_UNARY_OP_CEIL:
  12362. case GGML_UNARY_OP_FLOOR:
  12363. case GGML_UNARY_OP_TRUNC:
  12364. return ggml_is_contiguous(op->src[0]) &&
  12365. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12366. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  12367. (op->src[0]->type == op->type);
  12368. default:
  12369. return false;
  12370. }
  12371. case GGML_OP_GLU:
  12372. switch (ggml_get_glu_op(op)) {
  12373. case GGML_GLU_OP_GEGLU:
  12374. case GGML_GLU_OP_REGLU:
  12375. case GGML_GLU_OP_SWIGLU:
  12376. case GGML_GLU_OP_SWIGLU_OAI:
  12377. case GGML_GLU_OP_GEGLU_ERF:
  12378. case GGML_GLU_OP_GEGLU_QUICK:
  12379. return ggml_is_contiguous(op->src[0]) &&
  12380. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12381. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  12382. (op->src[0]->type == op->type);
  12383. default:
  12384. return false;
  12385. }
  12386. case GGML_OP_MUL_MAT:
  12387. case GGML_OP_MUL_MAT_ID:
  12388. {
  12389. ggml_type src0_type = op->src[0]->type;
  12390. if (op->op == GGML_OP_MUL_MAT_ID) {
  12391. if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) {
  12392. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  12393. return false;
  12394. }
  12395. }
  12396. switch (src0_type) {
  12397. case GGML_TYPE_F32:
  12398. case GGML_TYPE_F16:
  12399. case GGML_TYPE_BF16:
  12400. case GGML_TYPE_Q4_0:
  12401. case GGML_TYPE_Q4_1:
  12402. case GGML_TYPE_Q5_0:
  12403. case GGML_TYPE_Q5_1:
  12404. case GGML_TYPE_Q8_0:
  12405. case GGML_TYPE_Q2_K:
  12406. case GGML_TYPE_Q3_K:
  12407. case GGML_TYPE_Q4_K:
  12408. case GGML_TYPE_Q5_K:
  12409. case GGML_TYPE_Q6_K:
  12410. case GGML_TYPE_IQ1_S:
  12411. case GGML_TYPE_IQ1_M:
  12412. case GGML_TYPE_IQ2_XXS:
  12413. case GGML_TYPE_IQ2_XS:
  12414. case GGML_TYPE_IQ2_S:
  12415. case GGML_TYPE_IQ3_XXS:
  12416. case GGML_TYPE_IQ3_S:
  12417. case GGML_TYPE_IQ4_XS:
  12418. case GGML_TYPE_IQ4_NL:
  12419. case GGML_TYPE_MXFP4:
  12420. break;
  12421. default:
  12422. return false;
  12423. }
  12424. struct ggml_tensor * a;
  12425. struct ggml_tensor * b;
  12426. if (op->op == GGML_OP_MUL_MAT) {
  12427. a = op->src[0];
  12428. b = op->src[1];
  12429. } else {
  12430. a = op->src[2];
  12431. b = op->src[1];
  12432. }
  12433. if (a->ne[3] != b->ne[3]) {
  12434. return false;
  12435. }
  12436. 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) ||
  12437. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  12438. return false;
  12439. }
  12440. if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) {
  12441. // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader.
  12442. // So don't support this combination for now.
  12443. return false;
  12444. }
  12445. return true;
  12446. }
  12447. case GGML_OP_FLASH_ATTN_EXT:
  12448. {
  12449. bool coopmat2 = device->coopmat2;
  12450. uint32_t HSK = op->src[1]->ne[0];
  12451. uint32_t HSV = op->src[2]->ne[0];
  12452. if ((HSK % 8) != 0 || (HSV % 8) != 0) {
  12453. return false;
  12454. }
  12455. if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) {
  12456. return false;
  12457. }
  12458. if (op->src[0]->type != GGML_TYPE_F32) {
  12459. return false;
  12460. }
  12461. if (op->type != GGML_TYPE_F32) {
  12462. return false;
  12463. }
  12464. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  12465. return false;
  12466. }
  12467. // It's straightforward to support different K/V dequant, but would
  12468. // significantly increase the number of pipelines
  12469. if (op->src[1]->type != op->src[2]->type) {
  12470. return false;
  12471. }
  12472. switch (op->src[1]->type) {
  12473. case GGML_TYPE_F16:
  12474. case GGML_TYPE_F32:
  12475. case GGML_TYPE_Q4_0:
  12476. case GGML_TYPE_Q8_0:
  12477. // supported in scalar and coopmat2 paths
  12478. break;
  12479. case GGML_TYPE_Q4_1:
  12480. case GGML_TYPE_Q5_0:
  12481. case GGML_TYPE_Q5_1:
  12482. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  12483. //case GGML_TYPE_Q2_K:
  12484. //case GGML_TYPE_Q3_K:
  12485. //case GGML_TYPE_Q4_K:
  12486. //case GGML_TYPE_Q5_K:
  12487. //case GGML_TYPE_Q6_K:
  12488. //case GGML_TYPE_IQ1_S:
  12489. //case GGML_TYPE_IQ1_M:
  12490. //case GGML_TYPE_IQ2_XXS:
  12491. //case GGML_TYPE_IQ2_XS:
  12492. //case GGML_TYPE_IQ2_S:
  12493. //case GGML_TYPE_IQ3_XXS:
  12494. //case GGML_TYPE_IQ3_S:
  12495. //case GGML_TYPE_IQ4_XS:
  12496. case GGML_TYPE_IQ4_NL:
  12497. // currently supported only in coopmat2 path
  12498. if (!coopmat2) {
  12499. return false;
  12500. }
  12501. break;
  12502. default:
  12503. return false;
  12504. }
  12505. if (!coopmat2 && !(device->subgroup_shuffle && device->subgroup_vote)) {
  12506. // scalar/coopmat1 FA uses subgroupShuffle/subgroupAll
  12507. return false;
  12508. }
  12509. return true;
  12510. }
  12511. case GGML_OP_GET_ROWS:
  12512. {
  12513. switch (op->src[0]->type) {
  12514. case GGML_TYPE_F32:
  12515. case GGML_TYPE_F16:
  12516. case GGML_TYPE_BF16:
  12517. case GGML_TYPE_Q4_0:
  12518. case GGML_TYPE_Q4_1:
  12519. case GGML_TYPE_Q5_0:
  12520. case GGML_TYPE_Q5_1:
  12521. case GGML_TYPE_Q8_0:
  12522. case GGML_TYPE_Q2_K:
  12523. case GGML_TYPE_Q3_K:
  12524. case GGML_TYPE_Q4_K:
  12525. case GGML_TYPE_Q5_K:
  12526. case GGML_TYPE_Q6_K:
  12527. case GGML_TYPE_IQ1_S:
  12528. case GGML_TYPE_IQ1_M:
  12529. case GGML_TYPE_IQ2_XXS:
  12530. case GGML_TYPE_IQ2_XS:
  12531. case GGML_TYPE_IQ2_S:
  12532. case GGML_TYPE_IQ3_XXS:
  12533. case GGML_TYPE_IQ3_S:
  12534. case GGML_TYPE_IQ4_XS:
  12535. case GGML_TYPE_IQ4_NL:
  12536. case GGML_TYPE_MXFP4:
  12537. case GGML_TYPE_I32:
  12538. return true;
  12539. default:
  12540. return false;
  12541. }
  12542. }
  12543. case GGML_OP_SET_ROWS:
  12544. {
  12545. switch (op->type) {
  12546. case GGML_TYPE_F32:
  12547. case GGML_TYPE_F16:
  12548. case GGML_TYPE_BF16:
  12549. case GGML_TYPE_Q4_0:
  12550. case GGML_TYPE_Q4_1:
  12551. case GGML_TYPE_Q5_0:
  12552. case GGML_TYPE_Q5_1:
  12553. case GGML_TYPE_Q8_0:
  12554. case GGML_TYPE_IQ4_NL:
  12555. return true;
  12556. default:
  12557. return false;
  12558. }
  12559. }
  12560. case GGML_OP_CONT:
  12561. case GGML_OP_CPY:
  12562. case GGML_OP_DUP:
  12563. {
  12564. ggml_type src0_type = op->src[0]->type;
  12565. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  12566. if (src0_type == GGML_TYPE_F32) {
  12567. switch (src1_type) {
  12568. case GGML_TYPE_F32:
  12569. case GGML_TYPE_F16:
  12570. case GGML_TYPE_BF16:
  12571. case GGML_TYPE_Q4_0:
  12572. case GGML_TYPE_Q4_1:
  12573. case GGML_TYPE_Q5_0:
  12574. case GGML_TYPE_Q5_1:
  12575. case GGML_TYPE_Q8_0:
  12576. case GGML_TYPE_IQ4_NL:
  12577. return true;
  12578. default:
  12579. break;
  12580. }
  12581. }
  12582. if (src1_type == GGML_TYPE_F32) {
  12583. switch (src0_type) {
  12584. case GGML_TYPE_F16:
  12585. case GGML_TYPE_Q4_0:
  12586. case GGML_TYPE_Q4_1:
  12587. case GGML_TYPE_Q5_0:
  12588. case GGML_TYPE_Q5_1:
  12589. case GGML_TYPE_Q8_0:
  12590. case GGML_TYPE_IQ4_NL:
  12591. return true;
  12592. default:
  12593. break;
  12594. }
  12595. }
  12596. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  12597. return true;
  12598. }
  12599. if (
  12600. (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) ||
  12601. (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32)
  12602. ) {
  12603. return true;
  12604. }
  12605. // We can handle copying from a type to the same type if it's
  12606. // either not quantized or is quantized and contiguous.
  12607. // We use f16 or f32 shaders to do the copy,
  12608. // so the type/block size must be a multiple of 4.
  12609. if (src0_type == src1_type &&
  12610. (!ggml_is_quantized(src0_type) || (ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op))) &&
  12611. (ggml_type_size(src0_type) % 2) == 0) {
  12612. return true;
  12613. }
  12614. return false;
  12615. }
  12616. case GGML_OP_REPEAT:
  12617. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  12618. case GGML_OP_REPEAT_BACK:
  12619. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32;
  12620. case GGML_OP_ROPE:
  12621. case GGML_OP_ROPE_BACK:
  12622. case GGML_OP_NONE:
  12623. case GGML_OP_RESHAPE:
  12624. case GGML_OP_VIEW:
  12625. case GGML_OP_PERMUTE:
  12626. case GGML_OP_TRANSPOSE:
  12627. case GGML_OP_RMS_NORM:
  12628. return true;
  12629. case GGML_OP_NORM:
  12630. case GGML_OP_GROUP_NORM:
  12631. case GGML_OP_L2_NORM:
  12632. return ggml_is_contiguous(op->src[0]);
  12633. case GGML_OP_ADD:
  12634. case GGML_OP_SUB:
  12635. case GGML_OP_MUL:
  12636. case GGML_OP_DIV:
  12637. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12638. (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
  12639. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12640. case GGML_OP_ADD_ID:
  12641. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 &&
  12642. op->type == GGML_TYPE_F32;
  12643. case GGML_OP_SILU_BACK:
  12644. case GGML_OP_RMS_NORM_BACK:
  12645. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12646. case GGML_OP_SQR:
  12647. case GGML_OP_SQRT:
  12648. case GGML_OP_SIN:
  12649. case GGML_OP_COS:
  12650. case GGML_OP_CLAMP:
  12651. return op->src[0]->type == GGML_TYPE_F32;
  12652. case GGML_OP_LEAKY_RELU:
  12653. case GGML_OP_OPT_STEP_ADAMW:
  12654. case GGML_OP_OPT_STEP_SGD:
  12655. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12656. case GGML_OP_LOG:
  12657. case GGML_OP_TRI:
  12658. case GGML_OP_DIAG:
  12659. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12660. op->type == op->src[0]->type;
  12661. case GGML_OP_ARGSORT:
  12662. {
  12663. if (!ggml_is_contiguous(op) || !ggml_is_contiguous(op->src[0])) {
  12664. return false;
  12665. }
  12666. // pipeline_argsort_large_f32 requires vulkan memory model.
  12667. if (device->vulkan_memory_model) {
  12668. return true;
  12669. } else {
  12670. return op->ne[0] <= (1 << device->max_workgroup_size_log2);
  12671. }
  12672. }
  12673. case GGML_OP_TOP_K:
  12674. {
  12675. if (!ggml_is_contiguous(op) || !ggml_is_contiguous(op->src[0])) {
  12676. return false;
  12677. }
  12678. // We could potentially support larger, using argsort to sort the
  12679. // whole thing. Not clear if this is needed.
  12680. uint32_t min_pipeline = (uint32_t)log2f(float(op->ne[0])) + 1;
  12681. if (min_pipeline >= num_topk_pipelines ||
  12682. !device->pipeline_topk_f32[min_pipeline]) {
  12683. return false;
  12684. }
  12685. }
  12686. return true;
  12687. case GGML_OP_UPSCALE:
  12688. if (op->op_params[0] & GGML_SCALE_FLAG_ANTIALIAS) {
  12689. if ((op->op_params[0] & 0xFF) != GGML_SCALE_MODE_BILINEAR) {
  12690. return false;
  12691. }
  12692. }
  12693. return op->src[0]->type == GGML_TYPE_F32;
  12694. case GGML_OP_ACC:
  12695. return op->src[0]->type == GGML_TYPE_F32;
  12696. case GGML_OP_CONCAT:
  12697. return ggml_type_size(op->src[0]->type) == ggml_type_size(GGML_TYPE_F32);
  12698. case GGML_OP_ADD1:
  12699. return (op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32)
  12700. || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F32)
  12701. || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F16);
  12702. case GGML_OP_ARANGE:
  12703. case GGML_OP_FILL:
  12704. return op->type == GGML_TYPE_F32;
  12705. case GGML_OP_SCALE:
  12706. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12707. case GGML_OP_PAD:
  12708. case GGML_OP_ROLL:
  12709. return op->src[0]->type == GGML_TYPE_F32;
  12710. case GGML_OP_DIAG_MASK_INF:
  12711. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12712. case GGML_OP_SOFT_MAX:
  12713. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32
  12714. && (!op->src[1] || (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16));
  12715. case GGML_OP_SOFT_MAX_BACK:
  12716. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32
  12717. && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32;
  12718. case GGML_OP_SUM:
  12719. case GGML_OP_SUM_ROWS:
  12720. case GGML_OP_MEAN:
  12721. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  12722. case GGML_OP_CUMSUM:
  12723. {
  12724. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  12725. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  12726. }
  12727. return false;
  12728. }
  12729. case GGML_OP_SOLVE_TRI:
  12730. {
  12731. if (op->type != GGML_TYPE_F32 || op->src[0]->type != GGML_TYPE_F32) {
  12732. return false;
  12733. }
  12734. const uint32_t N = op->src[0]->ne[0];
  12735. const uint32_t K = op->src[1]->ne[0];
  12736. // K dimension limited to workgroup size
  12737. if (K > 1u << device->max_workgroup_size_log2) {
  12738. return false;
  12739. }
  12740. const uint32_t batch_N = device->properties.limits.maxComputeSharedMemorySize / ((N + K) * sizeof(float));
  12741. if (batch_N == 0) {
  12742. return false;
  12743. }
  12744. return true;
  12745. }
  12746. case GGML_OP_ARGMAX:
  12747. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12748. case GGML_OP_COUNT_EQUAL:
  12749. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_I32
  12750. && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_I32;
  12751. case GGML_OP_IM2COL:
  12752. return ggml_is_contiguous(op->src[1])
  12753. && op->src[1]->type == GGML_TYPE_F32
  12754. && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12755. case GGML_OP_IM2COL_3D:
  12756. return op->src[1]->type == GGML_TYPE_F32
  12757. && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12758. case GGML_OP_TIMESTEP_EMBEDDING:
  12759. return op->src[0]->type == GGML_TYPE_F32;
  12760. case GGML_OP_CONV_2D_DW:
  12761. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16)
  12762. && op->src[1]->type == GGML_TYPE_F32;
  12763. case GGML_OP_POOL_2D:
  12764. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12765. case GGML_OP_RWKV_WKV6:
  12766. case GGML_OP_RWKV_WKV7:
  12767. return true; // all inputs are contiguous, see ggml.c
  12768. case GGML_OP_SSM_SCAN:
  12769. {
  12770. for (int i = 0; i < 6; i++) {
  12771. if (op->src[i] && ggml_is_quantized(op->src[i]->type)) {
  12772. return false;
  12773. }
  12774. }
  12775. if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) {
  12776. return false;
  12777. }
  12778. if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
  12779. return false;
  12780. }
  12781. const uint32_t d_state = op->src[0]->ne[0];
  12782. const uint32_t head_dim = op->src[0]->ne[1];
  12783. bool is_mamba2 = (op->src[3] && op->src[3]->nb[1] == sizeof(float));
  12784. if (!is_mamba2) {
  12785. return false;
  12786. }
  12787. if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
  12788. return false;
  12789. }
  12790. size_t shmem_size = d_state * sizeof(float);
  12791. if (shmem_size > device->properties.limits.maxComputeSharedMemorySize) {
  12792. return false;
  12793. }
  12794. if (!device->subgroup_basic) {
  12795. return false;
  12796. }
  12797. return true;
  12798. }
  12799. case GGML_OP_SSM_CONV:
  12800. return op->src[0]->type == GGML_TYPE_F32;
  12801. case GGML_OP_CONV_TRANSPOSE_1D:
  12802. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  12803. case GGML_OP_CONV_2D:
  12804. case GGML_OP_CONV_TRANSPOSE_2D:
  12805. {
  12806. // Channel-contiguous format is not supported yet.
  12807. return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12808. op->src[1]->type == GGML_TYPE_F32 &&
  12809. op->type == GGML_TYPE_F32 &&
  12810. ggml_is_contiguous(op->src[0]) &&
  12811. ggml_is_contiguous(op->src[1]) &&
  12812. ggml_is_contiguous(op));
  12813. }
  12814. default:
  12815. return false;
  12816. }
  12817. UNUSED(dev);
  12818. }
  12819. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  12820. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  12821. return false;
  12822. }
  12823. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12824. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  12825. return buft_ctx->device->idx == ctx->device;
  12826. }
  12827. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  12828. ggml_backend_vk_device_context * dev_ctx = (ggml_backend_vk_device_context *)dev->context;
  12829. return (op->ne[1] >= dev_ctx->op_offload_min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  12830. (op->ne[2] >= dev_ctx->op_offload_min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  12831. }
  12832. static ggml_backend_event_t ggml_backend_vk_device_event_new(ggml_backend_dev_t dev) {
  12833. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12834. auto device = ggml_vk_get_device(ctx->device);
  12835. vk_event *vkev = new vk_event;
  12836. if (!vkev) {
  12837. return nullptr;
  12838. }
  12839. // The event/fence is expected to initially be in the signaled state.
  12840. vkev->event = device->device.createEvent({});
  12841. vkev->fence = device->device.createFence({vk::FenceCreateFlagBits::eSignaled});
  12842. device->device.setEvent(vkev->event);
  12843. return new ggml_backend_event {
  12844. /* .device = */ dev,
  12845. /* .context = */ vkev,
  12846. };
  12847. }
  12848. static void ggml_backend_vk_device_event_free(ggml_backend_dev_t dev, ggml_backend_event_t event) {
  12849. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12850. auto device = ggml_vk_get_device(ctx->device);
  12851. vk_event *vkev = (vk_event *)event->context;
  12852. device->device.destroyFence(vkev->fence);
  12853. device->device.destroyEvent(vkev->event);
  12854. delete vkev;
  12855. delete event;
  12856. }
  12857. static void ggml_backend_vk_device_event_synchronize(ggml_backend_dev_t dev, ggml_backend_event_t event) {
  12858. VK_LOG_DEBUG("ggml_backend_vk_device_event_synchronize(backend=" << dev << ", event=" << event << ")");
  12859. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12860. auto device = ggml_vk_get_device(ctx->device);
  12861. vk_event *vkev = (vk_event *)event->context;
  12862. VK_CHECK(device->device.waitForFences({ vkev->fence }, true, UINT64_MAX), "event_synchronize");
  12863. }
  12864. static vk_buffer ggml_vk_buffer_from_host_ptr(vk_device & device, void * ptr, size_t size) {
  12865. if (!device->external_memory_host) {
  12866. return {};
  12867. }
  12868. uintptr_t uptr = reinterpret_cast<uintptr_t>(ptr);
  12869. if (uptr & (device->min_imported_host_pointer_alignment - 1)) {
  12870. return {};
  12871. }
  12872. if (size & (device->min_imported_host_pointer_alignment - 1)) {
  12873. return {};
  12874. }
  12875. const vk::MemoryPropertyFlags property_flags = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached;
  12876. vk_buffer buf {};
  12877. try {
  12878. buf = ggml_vk_create_buffer(device, size, { property_flags }, ptr);
  12879. } catch (vk::SystemError& e) {
  12880. GGML_LOG_WARN("ggml_vulkan: Failed ggml_vk_create_buffer (%s)\n", e.what());
  12881. }
  12882. return buf;
  12883. }
  12884. static ggml_backend_buffer_t ggml_backend_vk_device_buffer_from_host_ptr(ggml_backend_dev_t dev, void * ptr, size_t size, size_t max_tensor_size) {
  12885. VK_LOG_DEBUG("ggml_backend_vk_device_buffer_from_host_ptr(backend=" << dev << ", ptr=" << ptr << ", size=" << size << ")");
  12886. GGML_UNUSED(max_tensor_size);
  12887. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12888. auto device = ggml_vk_get_device(ctx->device);
  12889. vk_buffer buf = ggml_vk_buffer_from_host_ptr(device, ptr, size);
  12890. if (!buf) {
  12891. return {};
  12892. }
  12893. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(device, std::move(buf), device->name);
  12894. ggml_backend_buffer_t ret = ggml_backend_buffer_init(ggml_backend_vk_device_get_buffer_type(dev), ggml_backend_vk_buffer_interface, bufctx, size);
  12895. return ret;
  12896. }
  12897. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  12898. /* .get_name = */ ggml_backend_vk_device_get_name,
  12899. /* .get_description = */ ggml_backend_vk_device_get_description,
  12900. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  12901. /* .get_type = */ ggml_backend_vk_device_get_type,
  12902. /* .get_props = */ ggml_backend_vk_device_get_props,
  12903. /* .init_backend = */ ggml_backend_vk_device_init,
  12904. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  12905. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  12906. /* .buffer_from_host_ptr = */ ggml_backend_vk_device_buffer_from_host_ptr,
  12907. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  12908. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  12909. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  12910. /* .event_new = */ ggml_backend_vk_device_event_new,
  12911. /* .event_free = */ ggml_backend_vk_device_event_free,
  12912. /* .event_synchronize = */ ggml_backend_vk_device_event_synchronize,
  12913. };
  12914. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  12915. UNUSED(reg);
  12916. return GGML_VK_NAME;
  12917. }
  12918. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  12919. UNUSED(reg);
  12920. return ggml_backend_vk_get_device_count();
  12921. }
  12922. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  12923. static std::vector<ggml_backend_dev_t> devices;
  12924. static bool initialized = false;
  12925. {
  12926. static std::mutex mutex;
  12927. std::lock_guard<std::mutex> lock(mutex);
  12928. if (!initialized) {
  12929. const int min_batch_size = getenv("GGML_OP_OFFLOAD_MIN_BATCH") ? atoi(getenv("GGML_OP_OFFLOAD_MIN_BATCH")) : 32;
  12930. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  12931. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  12932. char desc[256];
  12933. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  12934. ctx->device = i;
  12935. ctx->name = GGML_VK_NAME + std::to_string(i);
  12936. ctx->description = desc;
  12937. ctx->is_integrated_gpu = ggml_backend_vk_get_device_type(i) == vk::PhysicalDeviceType::eIntegratedGpu;
  12938. ctx->pci_bus_id = ggml_backend_vk_get_device_pci_id(i);
  12939. ctx->op_offload_min_batch_size = min_batch_size;
  12940. devices.push_back(new ggml_backend_device {
  12941. /* .iface = */ ggml_backend_vk_device_i,
  12942. /* .reg = */ reg,
  12943. /* .context = */ ctx,
  12944. });
  12945. }
  12946. initialized = true;
  12947. }
  12948. }
  12949. GGML_ASSERT(device < devices.size());
  12950. return devices[device];
  12951. }
  12952. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  12953. /* .get_name = */ ggml_backend_vk_reg_get_name,
  12954. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  12955. /* .get_device = */ ggml_backend_vk_reg_get_device,
  12956. /* .get_proc_address = */ NULL,
  12957. };
  12958. ggml_backend_reg_t ggml_backend_vk_reg() {
  12959. static ggml_backend_reg reg = {
  12960. /* .api_version = */ GGML_BACKEND_API_VERSION,
  12961. /* .iface = */ ggml_backend_vk_reg_i,
  12962. /* .context = */ nullptr,
  12963. };
  12964. try {
  12965. ggml_vk_instance_init();
  12966. return &reg;
  12967. } catch (const vk::SystemError& e) {
  12968. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what());
  12969. return nullptr;
  12970. } catch (const std::exception &e) {
  12971. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: " << e.what());
  12972. return nullptr;
  12973. } catch (...) {
  12974. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: unknown exception during Vulkan init");
  12975. return nullptr;
  12976. }
  12977. }
  12978. // Extension availability
  12979. static bool ggml_vk_instance_layer_settings_available() {
  12980. #ifdef GGML_VULKAN_VALIDATE
  12981. // Check if validation layer provides the extension
  12982. const std::string layer_name = "VK_LAYER_KHRONOS_validation";
  12983. for (const auto& layer : vk::enumerateInstanceLayerProperties()) {
  12984. if (layer_name == layer.layerName.data()) {
  12985. for (const auto& ext : vk::enumerateInstanceExtensionProperties(layer_name)) {
  12986. if (strcmp("VK_EXT_layer_settings", ext.extensionName.data()) == 0) {
  12987. return true;
  12988. }
  12989. }
  12990. }
  12991. }
  12992. std::cerr << "ggml_vulkan: WARNING: Validation layer or layer extension VK_EXT_layer_settings not found." << std::endl;
  12993. #endif
  12994. return false;
  12995. }
  12996. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  12997. #ifdef __APPLE__
  12998. // Check for portability enumeration extension for MoltenVK support
  12999. for (const auto& properties : instance_extensions) {
  13000. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  13001. return true;
  13002. }
  13003. }
  13004. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  13005. #endif
  13006. return false;
  13007. UNUSED(instance_extensions);
  13008. }
  13009. // Extension availability
  13010. static bool ggml_vk_instance_debug_utils_ext_available(
  13011. const std::vector<vk::ExtensionProperties> & instance_extensions) {
  13012. // Check for portability enumeration extension for MoltenVK support
  13013. for (const auto & properties : instance_extensions) {
  13014. if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) {
  13015. return true;
  13016. }
  13017. }
  13018. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl;
  13019. return false;
  13020. UNUSED(instance_extensions);
  13021. }
  13022. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev) {
  13023. VkPhysicalDeviceFeatures2 device_features2;
  13024. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  13025. VkPhysicalDeviceVulkan11Features vk11_features;
  13026. vk11_features.pNext = nullptr;
  13027. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  13028. device_features2.pNext = &vk11_features;
  13029. vkGetPhysicalDeviceFeatures2(vkdev, &device_features2);
  13030. return vk11_features.storageBuffer16BitAccess;
  13031. }
  13032. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) {
  13033. switch (props.vendorID) {
  13034. case VK_VENDOR_ID_INTEL:
  13035. // Only allowing Xe2 GPU at the moment since Xe2 GPU can gain significant performance boost,
  13036. // while some older hardware (ex. Arc A770) has performance regressions
  13037. return arch == vk_device_architecture::INTEL_XE2;
  13038. case VK_VENDOR_ID_AMD:
  13039. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  13040. // Workaround for AMD proprietary driver reporting support on all GPUs
  13041. return arch == vk_device_architecture::AMD_RDNA3;
  13042. }
  13043. return true;
  13044. default:
  13045. return true;
  13046. }
  13047. }
  13048. // checks
  13049. #ifdef GGML_VULKAN_CHECK_RESULTS
  13050. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  13051. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  13052. return;
  13053. }
  13054. for (int j = 0; j < level; j++) {
  13055. std::cerr << " ";
  13056. }
  13057. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  13058. done.push_back(tensor);
  13059. for (int i = 0; i < GGML_MAX_SRC; i++) {
  13060. if (tensor->src[i] != nullptr) {
  13061. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  13062. }
  13063. }
  13064. }
  13065. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  13066. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  13067. return;
  13068. }
  13069. i0 = std::max(i0, 5);
  13070. i1 = std::max(i1, 5);
  13071. i2 = std::max(i2, 0);
  13072. i3 = std::max(i3, 0);
  13073. fprintf(stderr, " ");
  13074. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  13075. fprintf(stderr, "%7d ", idx1);
  13076. }
  13077. fprintf(stderr, "\n");
  13078. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  13079. fprintf(stderr, "%7d: ", idx0);
  13080. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  13081. 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]) {
  13082. float val;
  13083. if (tensor->type == GGML_TYPE_F32) {
  13084. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  13085. } else if (tensor->type == GGML_TYPE_F16) {
  13086. 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]));
  13087. } else if (tensor->type == GGML_TYPE_I32) {
  13088. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  13089. } else {
  13090. GGML_ABORT("fatal error");
  13091. }
  13092. fprintf(stderr, "% 7.2f ", val);
  13093. } else {
  13094. fprintf(stderr, " ");
  13095. }
  13096. }
  13097. fprintf(stderr, "\n");
  13098. }
  13099. }
  13100. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  13101. void * tensor_data = tensor->data;
  13102. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  13103. if (is_gpu) {
  13104. const size_t tensor_size = ggml_nbytes(tensor);
  13105. tensor_data = malloc(tensor_size);
  13106. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  13107. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  13108. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  13109. }
  13110. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  13111. 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;
  13112. if (tensor->src[0] != nullptr) {
  13113. 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;
  13114. }
  13115. if (tensor->src[1] != nullptr) {
  13116. 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;
  13117. }
  13118. std::cerr << std::endl << "Result:" << std::endl;
  13119. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  13120. std::cerr << std::endl;
  13121. std::vector<const ggml_tensor *> done;
  13122. ggml_vk_print_graph_origin(tensor, done);
  13123. if (is_gpu) {
  13124. free(tensor_data);
  13125. }
  13126. }
  13127. void * comp_result;
  13128. size_t comp_size;
  13129. size_t comp_nb[GGML_MAX_DIMS];
  13130. size_t check_counter = 0;
  13131. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  13132. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  13133. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  13134. return;
  13135. }
  13136. check_counter++;
  13137. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  13138. return;
  13139. }
  13140. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  13141. struct ggml_init_params iparams = {
  13142. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  13143. /*.mem_buffer =*/ NULL,
  13144. /*.no_alloc =*/ false,
  13145. };
  13146. struct ggml_context * ggml_ctx = ggml_init(iparams);
  13147. std::array<struct ggml_tensor *, GGML_MAX_SRC> src_clone = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  13148. const char * srci_name[GGML_MAX_SRC] = {"src0", "src1", "src2", "src3", "src4", "src5", "src6", "src7", "src8", "src9"};
  13149. std::map<ggml_tensor *, ggml_tensor *> cloned_tensors;
  13150. std::vector<void *> cloned_mallocs;
  13151. struct ggml_tensor * tensor_clone = nullptr;
  13152. for (int f = 0; f < ctx->num_additional_fused_ops + 1; ++f) {
  13153. tensor = cgraph->nodes[tensor_idx + f];
  13154. for (int i = 0; i < GGML_MAX_SRC; i++) {
  13155. ggml_tensor * srci = tensor->src[i];
  13156. if (srci == nullptr) {
  13157. continue;
  13158. }
  13159. // If a src tensor has been cloned, use that one
  13160. auto it = cloned_tensors.find(srci);
  13161. if (it != cloned_tensors.end()) {
  13162. src_clone[i] = it->second;
  13163. continue;
  13164. }
  13165. ggml_tensor * srci_clone = ggml_dup_tensor(ggml_ctx, srci);
  13166. size_t srci_size = ggml_nbytes(srci);
  13167. src_clone[i] = srci_clone;
  13168. void *src_buffer = malloc(srci_size);
  13169. cloned_mallocs.push_back(src_buffer);
  13170. srci_clone->data = src_buffer;
  13171. if (ggml_backend_buffer_is_host(srci->buffer)) {
  13172. memcpy(srci_clone->data, srci->data, srci_size);
  13173. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  13174. } else if (ggml_backend_buffer_is_vk(srci->buffer)) {
  13175. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)srci->buffer->context;
  13176. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  13177. uint64_t offset = vk_tensor_offset(srci) + srci->view_offs;
  13178. if (!ggml_is_contiguous(srci) && ggml_vk_dim01_contiguous(srci)) {
  13179. for (int i3 = 0; i3 < srci->ne[3]; i3++) {
  13180. for (int i2 = 0; i2 < srci->ne[2]; i2++) {
  13181. const int idx = i3*srci->ne[2] + i2;
  13182. 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]);
  13183. }
  13184. }
  13185. srci_clone->nb[0] = srci->nb[0];
  13186. srci_clone->nb[1] = srci->nb[1];
  13187. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  13188. srci_clone->nb[i] = srci_clone->nb[i - 1]*srci_clone->ne[i - 1];
  13189. }
  13190. } else {
  13191. if (offset + srci_size >= buffer_gpu->size) {
  13192. srci_size = buffer_gpu->size - offset;
  13193. }
  13194. ggml_vk_buffer_read(buffer_gpu, offset, srci_clone->data, srci_size);
  13195. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  13196. }
  13197. } else {
  13198. GGML_ABORT("fatal error");
  13199. }
  13200. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  13201. ggml_vk_print_tensor(srci, srci_name[i]);
  13202. }
  13203. }
  13204. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  13205. const float * params = (const float *)tensor->op_params;
  13206. 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]);
  13207. if (src_clone[4]) {
  13208. ggml_flash_attn_ext_add_sinks(tensor_clone, src_clone[4]);
  13209. }
  13210. } else if (tensor->op == GGML_OP_MUL_MAT) {
  13211. tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
  13212. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  13213. tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  13214. } else if (tensor->op == GGML_OP_SUB) {
  13215. tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
  13216. } else if (tensor->op == GGML_OP_MUL) {
  13217. tensor_clone = ggml_mul(ggml_ctx, src_clone[0], src_clone[1]);
  13218. } else if (tensor->op == GGML_OP_DIV) {
  13219. tensor_clone = ggml_div(ggml_ctx, src_clone[0], src_clone[1]);
  13220. } else if (tensor->op == GGML_OP_CONCAT) {
  13221. tensor_clone = ggml_concat(ggml_ctx, src_clone[0], src_clone[1], *(int *)tensor->op_params);
  13222. } else if (tensor->op == GGML_OP_UPSCALE) {
  13223. 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]);
  13224. } else if (tensor->op == GGML_OP_SCALE) {
  13225. const float * params = (const float *)tensor->op_params;
  13226. tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]);
  13227. } else if (tensor->op == GGML_OP_ADD1) {
  13228. tensor_clone = ggml_add1(ggml_ctx, src_clone[0], src_clone[1]);
  13229. } else if (tensor->op == GGML_OP_ARANGE) {
  13230. const float start = ggml_get_op_params_f32(tensor, 0);
  13231. const float stop = ggml_get_op_params_f32(tensor, 1);
  13232. const float step = ggml_get_op_params_f32(tensor, 2);
  13233. tensor_clone = ggml_arange(ggml_ctx, start, stop, step);
  13234. } else if (tensor->op == GGML_OP_FILL) {
  13235. const float value = ggml_get_op_params_f32(tensor, 0);
  13236. tensor_clone = ggml_fill(ggml_ctx, tensor_clone, value);
  13237. } else if (tensor->op == GGML_OP_SQR) {
  13238. tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]);
  13239. } else if (tensor->op == GGML_OP_SQRT) {
  13240. tensor_clone = ggml_sqrt(ggml_ctx, src_clone[0]);
  13241. } else if (tensor->op == GGML_OP_SIN) {
  13242. tensor_clone = ggml_sin(ggml_ctx, src_clone[0]);
  13243. } else if (tensor->op == GGML_OP_COS) {
  13244. tensor_clone = ggml_cos(ggml_ctx, src_clone[0]);
  13245. } else if (tensor->op == GGML_OP_LOG) {
  13246. tensor_clone = ggml_log(ggml_ctx, src_clone[0]);
  13247. } else if (tensor->op == GGML_OP_TRI) {
  13248. tensor_clone = ggml_tri(ggml_ctx, src_clone[0], (ggml_tri_type)ggml_get_op_params_i32(tensor, 0));
  13249. } else if (tensor->op == GGML_OP_DIAG) {
  13250. tensor_clone = ggml_diag(ggml_ctx, src_clone[0]);
  13251. } else if (tensor->op == GGML_OP_CLAMP) {
  13252. const float * params = (const float *)tensor->op_params;
  13253. tensor_clone = ggml_clamp(ggml_ctx, src_clone[0], params[0], params[1]);
  13254. } else if (tensor->op == GGML_OP_PAD) {
  13255. 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],
  13256. tensor->op_params[4], tensor->op_params[5], tensor->op_params[6], tensor->op_params[7]);
  13257. } else if (tensor->op == GGML_OP_REPEAT) {
  13258. tensor_clone = ggml_repeat(ggml_ctx, src_clone[0], tensor);
  13259. } else if (tensor->op == GGML_OP_REPEAT_BACK) {
  13260. tensor_clone = ggml_repeat_back(ggml_ctx, src_clone[0], tensor);
  13261. } else if (tensor->op == GGML_OP_ADD) {
  13262. tensor_clone = ggml_add(ggml_ctx, src_clone[0], src_clone[1]);
  13263. } else if (tensor->op == GGML_OP_ACC) {
  13264. 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]);
  13265. } else if (tensor->op == GGML_OP_NORM) {
  13266. tensor_clone = ggml_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  13267. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  13268. const float * float_params = (const float *)tensor->op_params;
  13269. tensor_clone = ggml_group_norm(ggml_ctx, src_clone[0], tensor->op_params[0], float_params[1]);
  13270. } else if (tensor->op == GGML_OP_RMS_NORM) {
  13271. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  13272. } else if (tensor->op == GGML_OP_RMS_NORM_BACK) {
  13273. const float eps = ((float *) tensor->op_params)[0];
  13274. tensor_clone = ggml_rms_norm_back(ggml_ctx, src_clone[0], src_clone[1], eps);
  13275. } else if (tensor->op == GGML_OP_SILU_BACK) {
  13276. tensor_clone = ggml_silu_back(ggml_ctx, src_clone[0], src_clone[1]);
  13277. } else if (tensor->op == GGML_OP_L2_NORM) {
  13278. const float eps = ((float *) tensor->op_params)[0];
  13279. tensor_clone = ggml_l2_norm(ggml_ctx, src_clone[0], eps);
  13280. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  13281. if (tensor->src[1] != nullptr) {
  13282. const float * params = (const float *)tensor->op_params;
  13283. tensor_clone = ggml_soft_max_ext(ggml_ctx, src_clone[0], src_clone[1], params[0], params[1]);
  13284. } else {
  13285. tensor_clone = ggml_soft_max(ggml_ctx, src_clone[0]);
  13286. }
  13287. } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) {
  13288. 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]);
  13289. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  13290. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]);
  13291. } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) {
  13292. const int n_dims = ((int32_t *) tensor->op_params)[1];
  13293. const int mode = ((int32_t *) tensor->op_params)[2];
  13294. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  13295. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  13296. const float freq_base = ((float *) tensor->op_params)[5];
  13297. const float freq_scale = ((float *) tensor->op_params)[6];
  13298. const float ext_factor = ((float *) tensor->op_params)[7];
  13299. const float attn_factor = ((float *) tensor->op_params)[8];
  13300. const float beta_fast = ((float *) tensor->op_params)[9];
  13301. const float beta_slow = ((float *) tensor->op_params)[10];
  13302. if (mode & GGML_ROPE_TYPE_MROPE) {
  13303. int32_t *sections = ((int32_t *) tensor->op_params) + 11;
  13304. if (tensor->op == GGML_OP_ROPE) {
  13305. 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);
  13306. } else {
  13307. 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);
  13308. }
  13309. } else {
  13310. if (tensor->op == GGML_OP_ROPE) {
  13311. 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);
  13312. } else {
  13313. 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);
  13314. }
  13315. }
  13316. } else if (tensor->op == GGML_OP_UNARY) {
  13317. switch (ggml_get_unary_op(tensor)) {
  13318. case GGML_UNARY_OP_EXP:
  13319. tensor_clone = ggml_exp(ggml_ctx, src_clone[0]);
  13320. break;
  13321. case GGML_UNARY_OP_SILU:
  13322. tensor_clone = ggml_silu(ggml_ctx, src_clone[0]);
  13323. break;
  13324. case GGML_UNARY_OP_GELU:
  13325. tensor_clone = ggml_gelu(ggml_ctx, src_clone[0]);
  13326. break;
  13327. case GGML_UNARY_OP_GELU_ERF:
  13328. tensor_clone = ggml_gelu_erf(ggml_ctx, src_clone[0]);
  13329. break;
  13330. case GGML_UNARY_OP_GELU_QUICK:
  13331. tensor_clone = ggml_gelu_quick(ggml_ctx, src_clone[0]);
  13332. break;
  13333. case GGML_UNARY_OP_RELU:
  13334. tensor_clone = ggml_relu(ggml_ctx, src_clone[0]);
  13335. break;
  13336. case GGML_UNARY_OP_XIELU:
  13337. tensor_clone = ggml_xielu(ggml_ctx, src_clone[0], 0, 0, 0, 0);
  13338. ggml_set_op_params_f32(tensor_clone, 1, ggml_get_op_params_f32(tensor, 1));
  13339. ggml_set_op_params_f32(tensor_clone, 2, ggml_get_op_params_f32(tensor, 2));
  13340. ggml_set_op_params_f32(tensor_clone, 3, ggml_get_op_params_f32(tensor, 3));
  13341. ggml_set_op_params_f32(tensor_clone, 4, ggml_get_op_params_f32(tensor, 4));
  13342. break;
  13343. case GGML_UNARY_OP_NEG:
  13344. tensor_clone = ggml_neg(ggml_ctx, src_clone[0]);
  13345. break;
  13346. case GGML_UNARY_OP_TANH:
  13347. tensor_clone = ggml_tanh(ggml_ctx, src_clone[0]);
  13348. break;
  13349. case GGML_UNARY_OP_SIGMOID:
  13350. tensor_clone = ggml_sigmoid(ggml_ctx, src_clone[0]);
  13351. break;
  13352. case GGML_UNARY_OP_HARDSIGMOID:
  13353. tensor_clone = ggml_hardsigmoid(ggml_ctx, src_clone[0]);
  13354. break;
  13355. case GGML_UNARY_OP_HARDSWISH:
  13356. tensor_clone = ggml_hardswish(ggml_ctx, src_clone[0]);
  13357. break;
  13358. case GGML_UNARY_OP_ABS:
  13359. tensor_clone = ggml_abs(ggml_ctx, src_clone[0]);
  13360. break;
  13361. case GGML_UNARY_OP_SOFTPLUS:
  13362. tensor_clone = ggml_softplus(ggml_ctx, src_clone[0]);
  13363. break;
  13364. case GGML_UNARY_OP_STEP:
  13365. tensor_clone = ggml_step(ggml_ctx, src_clone[0]);
  13366. break;
  13367. case GGML_UNARY_OP_ROUND:
  13368. tensor_clone = ggml_round(ggml_ctx, src_clone[0]);
  13369. break;
  13370. case GGML_UNARY_OP_CEIL:
  13371. tensor_clone = ggml_ceil(ggml_ctx, src_clone[0]);
  13372. break;
  13373. case GGML_UNARY_OP_FLOOR:
  13374. tensor_clone = ggml_floor(ggml_ctx, src_clone[0]);
  13375. break;
  13376. case GGML_UNARY_OP_TRUNC:
  13377. tensor_clone = ggml_trunc(ggml_ctx, src_clone[0]);
  13378. break;
  13379. default:
  13380. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  13381. GGML_ABORT("fatal error");
  13382. }
  13383. } else if (tensor->op == GGML_OP_GLU) {
  13384. if (src_clone[1] == nullptr) {
  13385. tensor_clone = ggml_glu(ggml_ctx, src_clone[0], (ggml_glu_op) tensor->op_params[0], tensor->op_params[1]);
  13386. } else {
  13387. tensor_clone = ggml_glu_split(ggml_ctx, src_clone[0], src_clone[1], (ggml_glu_op) tensor->op_params[0]);
  13388. }
  13389. ggml_set_op_params_i32(tensor_clone, 2, ggml_get_op_params_i32(tensor, 2));
  13390. ggml_set_op_params_i32(tensor_clone, 3, ggml_get_op_params_i32(tensor, 3));
  13391. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  13392. if (tensor->src[1] == nullptr) {
  13393. tensor_clone = ggml_dup(ggml_ctx, src_clone[0]);
  13394. tensor_clone->type = tensor->type;
  13395. } else {
  13396. tensor_clone = ggml_cpy(ggml_ctx, src_clone[0], src_clone[1]);
  13397. }
  13398. } else if (tensor->op == GGML_OP_CONT) {
  13399. tensor_clone = ggml_cont_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  13400. } else if (tensor->op == GGML_OP_RESHAPE) {
  13401. tensor_clone = ggml_reshape_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  13402. } else if (tensor->op == GGML_OP_VIEW) {
  13403. 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]);
  13404. } else if (tensor->op == GGML_OP_PERMUTE) {
  13405. int32_t * params = (int32_t *)tensor->op_params;
  13406. tensor_clone = ggml_permute(ggml_ctx, src_clone[0], params[0], params[1], params[2], params[3]);
  13407. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  13408. tensor_clone = ggml_transpose(ggml_ctx, src_clone[0]);
  13409. } else if (tensor->op == GGML_OP_GET_ROWS) {
  13410. tensor_clone = ggml_get_rows(ggml_ctx, src_clone[0], src_clone[1]);
  13411. } else if (tensor->op == GGML_OP_ARGSORT) {
  13412. tensor_clone = ggml_argsort(ggml_ctx, src_clone[0], (ggml_sort_order) *(int *)tensor->op_params);
  13413. } else if (tensor->op == GGML_OP_TOP_K) {
  13414. tensor_clone = ggml_top_k(ggml_ctx, src_clone[0], tensor->ne[0]);
  13415. } else if (tensor->op == GGML_OP_SUM) {
  13416. tensor_clone = ggml_sum(ggml_ctx, src_clone[0]);
  13417. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  13418. tensor_clone = ggml_sum_rows(ggml_ctx, src_clone[0]);
  13419. } else if (tensor->op == GGML_OP_CUMSUM) {
  13420. tensor_clone = ggml_cumsum(ggml_ctx, src_clone[0]);
  13421. } else if (tensor->op == GGML_OP_MEAN) {
  13422. tensor_clone = ggml_mean(ggml_ctx, src_clone[0]);
  13423. } else if (tensor->op == GGML_OP_ARGMAX) {
  13424. tensor_clone = ggml_argmax(ggml_ctx, src_clone[0]);
  13425. } else if (tensor->op == GGML_OP_COUNT_EQUAL) {
  13426. tensor_clone = ggml_count_equal(ggml_ctx, src_clone[0], src_clone[1]);
  13427. } else if (tensor->op == GGML_OP_SOLVE_TRI) {
  13428. tensor_clone = ggml_solve_tri(ggml_ctx, src_clone[0], src_clone[1], true, true, false);
  13429. } else if (tensor->op == GGML_OP_IM2COL) {
  13430. const int32_t s0 = tensor->op_params[0];
  13431. const int32_t s1 = tensor->op_params[1];
  13432. const int32_t p0 = tensor->op_params[2];
  13433. const int32_t p1 = tensor->op_params[3];
  13434. const int32_t d0 = tensor->op_params[4];
  13435. const int32_t d1 = tensor->op_params[5];
  13436. const bool is_2D = tensor->op_params[6] == 1;
  13437. tensor_clone = ggml_im2col(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  13438. } else if (tensor->op == GGML_OP_IM2COL_3D) {
  13439. const int32_t s0 = tensor->op_params[0];
  13440. const int32_t s1 = tensor->op_params[1];
  13441. const int32_t s2 = tensor->op_params[2];
  13442. const int32_t p0 = tensor->op_params[3];
  13443. const int32_t p1 = tensor->op_params[4];
  13444. const int32_t p2 = tensor->op_params[5];
  13445. const int32_t d0 = tensor->op_params[6];
  13446. const int32_t d1 = tensor->op_params[7];
  13447. const int32_t d2 = tensor->op_params[8];
  13448. const int32_t IC = tensor->op_params[9];
  13449. 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);
  13450. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  13451. const int32_t dim = tensor->op_params[0];
  13452. const int32_t max_period = tensor->op_params[1];
  13453. tensor_clone = ggml_timestep_embedding(ggml_ctx, src_clone[0], dim, max_period);
  13454. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_1D){
  13455. const int32_t s0 = tensor->op_params[0];
  13456. const int32_t p0 = tensor->op_params[1];
  13457. const int32_t d0 = tensor->op_params[2];
  13458. tensor_clone = ggml_conv_transpose_1d(ggml_ctx, src_clone[0], src_clone[1], s0, p0, d0);
  13459. } else if (tensor->op == GGML_OP_POOL_2D) {
  13460. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  13461. const int32_t k0 = tensor->op_params[1];
  13462. const int32_t k1 = tensor->op_params[2];
  13463. const int32_t s0 = tensor->op_params[3];
  13464. const int32_t s1 = tensor->op_params[4];
  13465. const int32_t p0 = tensor->op_params[5];
  13466. const int32_t p1 = tensor->op_params[6];
  13467. tensor_clone = ggml_pool_2d(ggml_ctx, src_clone[0], op, k0, k1, s0, s1, p0, p1);
  13468. } else if (tensor->op == GGML_OP_CONV_2D) {
  13469. const int32_t s0 = tensor->op_params[0];
  13470. const int32_t s1 = tensor->op_params[1];
  13471. const int32_t p0 = tensor->op_params[2];
  13472. const int32_t p1 = tensor->op_params[3];
  13473. const int32_t d0 = tensor->op_params[4];
  13474. const int32_t d1 = tensor->op_params[5];
  13475. tensor_clone = ggml_conv_2d(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  13476. } else if (tensor->op == GGML_OP_CONV_2D_DW) {
  13477. const int32_t s0 = tensor->op_params[0];
  13478. const int32_t s1 = tensor->op_params[1];
  13479. const int32_t p0 = tensor->op_params[2];
  13480. const int32_t p1 = tensor->op_params[3];
  13481. const int32_t d0 = tensor->op_params[4];
  13482. const int32_t d1 = tensor->op_params[5];
  13483. tensor_clone = ggml_conv_2d_dw_direct(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  13484. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_2D) {
  13485. const int32_t s = tensor->op_params[0];
  13486. tensor_clone = ggml_conv_transpose_2d_p0(ggml_ctx, src_clone[0], src_clone[1], s);
  13487. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  13488. const float * op_params = (const float *)tensor->op_params;
  13489. tensor_clone = ggml_leaky_relu(ggml_ctx, src_clone[0], op_params[0], false);
  13490. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  13491. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, src_clone[0], src_clone[1],
  13492. src_clone[2], src_clone[3], src_clone[4], src_clone[5]);
  13493. } else if (tensor->op == GGML_OP_RWKV_WKV7) {
  13494. tensor_clone = ggml_rwkv_wkv7(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3],
  13495. src_clone[4], src_clone[5], src_clone[6]);
  13496. } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
  13497. src_clone[0]->flags = tensor->src[0]->flags;
  13498. tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
  13499. src_clone[2], src_clone[3], src_clone[4]);
  13500. } else if (tensor->op == GGML_OP_OPT_STEP_SGD) {
  13501. src_clone[0]->flags = tensor->src[0]->flags;
  13502. tensor_clone = ggml_opt_step_sgd(ggml_ctx, src_clone[0], src_clone[1],
  13503. src_clone[2]);
  13504. } else if (tensor->op == GGML_OP_ADD_ID) {
  13505. tensor_clone = ggml_add_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  13506. } else if (tensor->op == GGML_OP_SSM_SCAN) {
  13507. tensor_clone = ggml_ssm_scan(ggml_ctx, src_clone[0], src_clone[1], src_clone[2],
  13508. src_clone[3], src_clone[4], src_clone[5], src_clone[6]);
  13509. } else if (tensor->op == GGML_OP_SSM_CONV) {
  13510. tensor_clone = ggml_ssm_conv(ggml_ctx, src_clone[0], src_clone[1]);
  13511. } else if (tensor->op == GGML_OP_ROLL) {
  13512. const int32_t s0 = tensor->op_params[0];
  13513. const int32_t s1 = tensor->op_params[1];
  13514. const int32_t s2 = tensor->op_params[2];
  13515. const int32_t s3 = tensor->op_params[3];
  13516. tensor_clone = ggml_roll(ggml_ctx, src_clone[0], s0, s1, s2, s3);
  13517. }
  13518. else {
  13519. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  13520. GGML_ABORT("fatal error");
  13521. }
  13522. cloned_tensors[tensor] = tensor_clone;
  13523. }
  13524. ggml_cgraph * cgraph_cpu = ggml_new_graph(ggml_ctx);
  13525. ggml_build_forward_expand(cgraph_cpu, tensor_clone);
  13526. ggml_graph_compute_with_ctx(ggml_ctx, cgraph_cpu, 8);
  13527. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  13528. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  13529. }
  13530. comp_size = ggml_nbytes(tensor_clone);
  13531. comp_result = malloc(comp_size);
  13532. memcpy(comp_result, tensor_clone->data, comp_size);
  13533. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  13534. for (auto m : cloned_mallocs) {
  13535. free(m);
  13536. }
  13537. ggml_free(ggml_ctx);
  13538. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  13539. }
  13540. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  13541. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  13542. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  13543. return;
  13544. }
  13545. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  13546. return;
  13547. }
  13548. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  13549. ggml_tensor * src0 = tensor->src[0];
  13550. ggml_tensor * src1 = tensor->src[1];
  13551. ggml_tensor * src2 = tensor->src[2];
  13552. ggml_tensor * src3 = tensor->src[3];
  13553. void * tensor_data = tensor->data;
  13554. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  13555. size_t tensor_size = ggml_nbytes(tensor);
  13556. tensor_data = malloc(tensor_size);
  13557. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  13558. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  13559. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  13560. if (offset + tensor_size >= buffer_gpu->size) {
  13561. tensor_size = buffer_gpu->size - offset;
  13562. }
  13563. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  13564. }
  13565. float first_error_result = -1.0f;
  13566. float first_error_correct = -1.0f;
  13567. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  13568. double avg_err = 0.0;
  13569. size_t counter = 0;
  13570. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  13571. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  13572. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  13573. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  13574. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  13575. float correct = 0.0f;
  13576. float result = 0.0f;
  13577. if (buffer_size_fit) {
  13578. if (tensor->type == GGML_TYPE_F32) {
  13579. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  13580. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  13581. } else if (tensor->type == GGML_TYPE_F16) {
  13582. 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]));
  13583. 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]));
  13584. } else if (tensor->type == GGML_TYPE_BF16) {
  13585. 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]));
  13586. 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]));
  13587. } else if (tensor->type == GGML_TYPE_I32) {
  13588. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  13589. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  13590. } else if (tensor->type == GGML_TYPE_I64) {
  13591. correct = *(int64_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  13592. result = *(int64_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  13593. } else {
  13594. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  13595. }
  13596. } else {
  13597. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  13598. GGML_ABORT("fatal error");
  13599. }
  13600. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  13601. 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;
  13602. 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;
  13603. if (src0 != nullptr) {
  13604. 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;
  13605. }
  13606. if (src1 != nullptr) {
  13607. 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;
  13608. }
  13609. if (src2 != nullptr) {
  13610. 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;
  13611. }
  13612. if (src3 != nullptr) {
  13613. 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;
  13614. }
  13615. 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;
  13616. std::cerr << std::endl << "Result:" << std::endl;
  13617. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  13618. std::cerr << std::endl << "Correct:" << std::endl;
  13619. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  13620. std::cerr << std::endl;
  13621. std::vector<const ggml_tensor *> done;
  13622. ggml_vk_print_graph_origin(tensor, done);
  13623. GGML_ABORT("fatal error");
  13624. }
  13625. const double denom = std::fabs(correct) > 1.0f ? (std::fabs(correct) > 1e-8 ? std::fabs(correct) : 1e-8) : 1.0f;
  13626. if (first_error[0] == -1 && std::fabs(correct - result) / denom > 0.5) {
  13627. first_error[0] = i0;
  13628. first_error[1] = i1;
  13629. first_error[2] = i2;
  13630. first_error[3] = i3;
  13631. first_error_result = result;
  13632. first_error_correct = correct;
  13633. }
  13634. // Special case, value is infinite, avoid NaN result in avg_err
  13635. // NaN also appears in results, if both are nan error is 0
  13636. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  13637. avg_err += std::fabs(correct - result) / denom;
  13638. }
  13639. counter++;
  13640. }
  13641. }
  13642. }
  13643. }
  13644. avg_err /= counter;
  13645. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  13646. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  13647. 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;
  13648. if (src0 != nullptr) {
  13649. 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;
  13650. }
  13651. if (src1 != nullptr) {
  13652. 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;
  13653. }
  13654. if (src2 != nullptr) {
  13655. 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;
  13656. }
  13657. if (src3 != nullptr) {
  13658. 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;
  13659. }
  13660. 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;
  13661. std::cerr << std::endl << "Result:" << std::endl;
  13662. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  13663. std::cerr << std::endl << "Correct:" << std::endl;
  13664. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  13665. std::cerr << std::endl;
  13666. std::vector<const ggml_tensor *> done;
  13667. ggml_vk_print_graph_origin(tensor, done);
  13668. }
  13669. if (avg_err > 0.5 || std::isnan(avg_err)) {
  13670. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  13671. 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;
  13672. if (src0 != nullptr) {
  13673. 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;
  13674. }
  13675. if (src1 != nullptr) {
  13676. 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;
  13677. }
  13678. if (src2 != nullptr) {
  13679. 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;
  13680. }
  13681. if (src3 != nullptr) {
  13682. 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;
  13683. }
  13684. 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;
  13685. std::cerr << std::endl << "Result:" << std::endl;
  13686. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  13687. std::cerr << std::endl << "Correct:" << std::endl;
  13688. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  13689. std::cerr << std::endl;
  13690. std::vector<const ggml_tensor *> done;
  13691. ggml_vk_print_graph_origin(tensor, done);
  13692. GGML_ABORT("fatal error");
  13693. } else {
  13694. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  13695. }
  13696. free(comp_result);
  13697. comp_result = nullptr;
  13698. comp_size = 0;
  13699. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  13700. free(tensor_data);
  13701. }
  13702. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  13703. }
  13704. #endif
  13705. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)