ggml-vulkan.cpp 766 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163
  1. #include "ggml-vulkan.h"
  2. #include <vulkan/vulkan_core.h>
  3. #if defined(GGML_VULKAN_RUN_TESTS) || defined(GGML_VULKAN_CHECK_RESULTS)
  4. #include <chrono>
  5. #include "ggml-cpu.h"
  6. #endif
  7. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  8. #define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
  9. // We use VULKAN_HPP_DEFAULT_DISPATCHER, but not VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
  10. // to avoid conflicts with applications or other libraries who might use it.
  11. #if VK_HEADER_VERSION >= 301
  12. namespace vk::detail { class DispatchLoaderDynamic; }
  13. using vk::detail::DispatchLoaderDynamic;
  14. #else
  15. namespace vk { class DispatchLoaderDynamic; }
  16. using vk::DispatchLoaderDynamic;
  17. #endif
  18. DispatchLoaderDynamic & ggml_vk_default_dispatcher();
  19. #define VULKAN_HPP_DEFAULT_DISPATCHER ggml_vk_default_dispatcher()
  20. #include <vulkan/vulkan.hpp>
  21. #include <algorithm>
  22. #include <cmath>
  23. #include <iomanip>
  24. #include <iostream>
  25. #include <tuple>
  26. #include <vector>
  27. #include <sstream>
  28. #include <utility>
  29. #include <memory>
  30. #include <limits>
  31. #include <map>
  32. #include <set>
  33. #include <unordered_map>
  34. #include <memory>
  35. #include <mutex>
  36. #include <future>
  37. #include <thread>
  38. #if defined(_MSC_VER)
  39. # define NOMINMAX 1
  40. # include <windows.h>
  41. # define YIELD() YieldProcessor()
  42. #elif defined(__clang__) || defined(__GNUC__)
  43. # if defined(__x86_64__) ||defined(__i386__)
  44. # include <immintrin.h>
  45. # define YIELD() _mm_pause()
  46. # elif defined(__arm__) || defined(__aarch64__)
  47. # if defined(__clang__)
  48. # include <arm_acle.h>
  49. # define YIELD() __yield()
  50. # else
  51. # define YIELD() asm volatile("yield")
  52. # endif
  53. # endif
  54. #endif
  55. #if !defined(YIELD)
  56. #define YIELD()
  57. #endif
  58. #include "ggml-impl.h"
  59. #include "ggml-backend-impl.h"
  60. #include "ggml-vulkan-shaders.hpp"
  61. // remove this once it's more widely available in the SDK
  62. #if !defined(VK_KHR_shader_bfloat16)
  63. #define VK_KHR_shader_bfloat16 1
  64. #define VK_KHR_SHADER_BFLOAT16_SPEC_VERSION 1
  65. #define VK_KHR_SHADER_BFLOAT16_EXTENSION_NAME "VK_KHR_shader_bfloat16"
  66. #define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR ((VkStructureType)1000141000)
  67. #define VK_COMPONENT_TYPE_BFLOAT16_KHR ((VkComponentTypeKHR)1000141000)
  68. typedef struct VkPhysicalDeviceShaderBfloat16FeaturesKHR {
  69. VkStructureType sType;
  70. void* pNext;
  71. VkBool32 shaderBFloat16Type;
  72. VkBool32 shaderBFloat16DotProduct;
  73. VkBool32 shaderBFloat16CooperativeMatrix;
  74. } VkPhysicalDeviceShaderBfloat16FeaturesKHR;
  75. #endif
  76. #define ROUNDUP_POW2(M, N) (((M) + (N) - 1) & ~((N) - 1))
  77. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  78. static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; }
  79. #define VK_VENDOR_ID_AMD 0x1002
  80. #define VK_VENDOR_ID_APPLE 0x106b
  81. #define VK_VENDOR_ID_INTEL 0x8086
  82. #define VK_VENDOR_ID_NVIDIA 0x10de
  83. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 256
  84. #define GGML_VK_MAX_NODES 8192
  85. #define VK_CHECK(err, msg) \
  86. do { \
  87. vk::Result err_ = (err); \
  88. if (err_ != vk::Result::eSuccess) { \
  89. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  90. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  91. exit(1); \
  92. } \
  93. } while (0)
  94. #ifdef GGML_VULKAN_DEBUG
  95. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  96. #else
  97. #define VK_LOG_DEBUG(msg) ((void) 0)
  98. #endif // GGML_VULKAN_DEBUG
  99. struct ggml_backend_vk_context;
  100. #define MAX_PARAMETER_COUNT 12
  101. // Max number of adds that can be fused without exceeding MAX_PARAMETER_COUNT.
  102. #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3)
  103. struct vk_pipeline_struct {
  104. std::string name;
  105. vk::ShaderModule shader_module;
  106. vk::PipelineLayout layout;
  107. vk::Pipeline pipeline;
  108. uint32_t push_constant_size;
  109. uint32_t parameter_count;
  110. std::array<uint32_t, 3> wg_denoms;
  111. uint32_t align;
  112. // true if fields have been set by ggml_vk_create_pipeline
  113. bool initialized {};
  114. // set to true to request the pipeline is compiled
  115. std::atomic<bool> needed {};
  116. // set to true when the shader has been compiled
  117. std::atomic<bool> compiled {};
  118. // number of registers used, extracted from pipeline executable properties
  119. uint32_t register_count {};
  120. };
  121. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  122. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  123. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  124. struct vk_matmul_pipeline_struct {
  125. vk_pipeline l, m, s;
  126. vk_pipeline a_l, a_m, a_s;
  127. // Returns true when all unaligned pipelines are null.
  128. // We only check for unaligned variants since one of the unaligned pipelines must exist
  129. // while aligned pipelines are optional
  130. bool is_empty() const {
  131. return l == nullptr && m == nullptr && s == nullptr;
  132. }
  133. };
  134. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  135. struct vk_matmul_pipeline2 {
  136. vk_matmul_pipeline2() {
  137. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  138. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  139. }
  140. vk_matmul_pipeline f32acc;
  141. vk_matmul_pipeline f16acc;
  142. };
  143. struct vk_device_struct;
  144. typedef std::shared_ptr<vk_device_struct> vk_device;
  145. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  146. struct vk_buffer_struct;
  147. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  148. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  149. struct ggml_backend_vk_buffer_type_context {
  150. std::string name;
  151. vk_device device;
  152. };
  153. struct vk_queue;
  154. // Stores command pool/buffers. There's an instance of this
  155. // for each (context,queue) pair and for each (device,queue) pair.
  156. struct vk_command_pool {
  157. void init(vk_device& device, vk_queue *q_);
  158. void destroy(vk::Device& device);
  159. vk::CommandPool pool;
  160. uint32_t cmd_buffer_idx;
  161. std::vector<vk::CommandBuffer> cmd_buffers;
  162. vk_queue *q;
  163. };
  164. // Prevent simultaneous submissions to the same queue.
  165. // This could be per vk_queue if we stopped having two vk_queue structures
  166. // sharing the same vk::Queue.
  167. static std::mutex queue_mutex;
  168. struct vk_queue {
  169. uint32_t queue_family_index;
  170. vk::Queue queue;
  171. vk_command_pool cmd_pool;
  172. vk::PipelineStageFlags stage_flags;
  173. bool transfer_only;
  174. // copy everything except the cmd_pool
  175. void copyFrom(vk_queue &other) {
  176. queue_family_index = other.queue_family_index;
  177. queue = other.queue;
  178. stage_flags = other.stage_flags;
  179. transfer_only = other.transfer_only;
  180. }
  181. };
  182. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  183. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  184. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  185. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  186. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  187. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  188. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  189. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  190. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  191. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  192. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  193. /* .is_host = */ NULL,
  194. };
  195. #ifdef GGML_VULKAN_MEMORY_DEBUG
  196. class vk_memory_logger;
  197. #endif
  198. class vk_perf_logger;
  199. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  200. static void ggml_vk_synchronize(ggml_backend_vk_context * ctx);
  201. static constexpr uint32_t mul_mat_vec_max_cols = 8;
  202. static constexpr uint32_t p021_max_gqa_ratio = 8;
  203. enum vk_device_architecture {
  204. OTHER,
  205. AMD_GCN,
  206. AMD_RDNA1,
  207. AMD_RDNA2,
  208. AMD_RDNA3,
  209. INTEL_XE2,
  210. NVIDIA_PRE_TURING,
  211. };
  212. static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) {
  213. vk::PhysicalDeviceProperties props = device.getProperties();
  214. if (props.vendorID == VK_VENDOR_ID_AMD) {
  215. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  216. bool amd_shader_core_properties = false;
  217. bool integer_dot_product = false;
  218. bool subgroup_size_control = false;
  219. for (const auto& properties : ext_props) {
  220. if (strcmp("VK_AMD_shader_core_properties", properties.extensionName) == 0) {
  221. amd_shader_core_properties = true;
  222. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0) {
  223. integer_dot_product = true;
  224. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  225. subgroup_size_control = true;
  226. }
  227. }
  228. if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) {
  229. return vk_device_architecture::OTHER;
  230. }
  231. vk::PhysicalDeviceProperties2 props2;
  232. vk::PhysicalDeviceShaderCorePropertiesAMD shader_core_props_amd;
  233. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR integer_dot_props;
  234. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  235. props2.pNext = &shader_core_props_amd;
  236. shader_core_props_amd.pNext = &integer_dot_props;
  237. integer_dot_props.pNext = &subgroup_size_control_props;
  238. device.getProperties2(&props2);
  239. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 64) {
  240. return vk_device_architecture::AMD_GCN;
  241. }
  242. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 32) {
  243. // RDNA
  244. if (shader_core_props_amd.wavefrontsPerSimd == 20) {
  245. return vk_device_architecture::AMD_RDNA1;
  246. }
  247. if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
  248. return vk_device_architecture::AMD_RDNA3;
  249. }
  250. return vk_device_architecture::AMD_RDNA2;
  251. }
  252. } else if (props.vendorID == VK_VENDOR_ID_INTEL) {
  253. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  254. bool subgroup_size_control = false;
  255. for (const auto& properties : ext_props) {
  256. if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  257. subgroup_size_control = true;
  258. }
  259. }
  260. if (!subgroup_size_control) {
  261. return vk_device_architecture::OTHER;
  262. }
  263. vk::PhysicalDeviceProperties2 props2;
  264. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  265. props2.pNext = &subgroup_size_control_props;
  266. device.getProperties2(&props2);
  267. if (subgroup_size_control_props.minSubgroupSize == 16) {
  268. // Xe2 architecture uses SIMD16 while previous Xe and Gen architecture uses SIMD8.
  269. // Minimum subgroup size matches the SIMD width so we distinguish architecture by checking this value.
  270. // https://www.intel.com/content/www/us/en/content-details/824434/2024-intel-tech-tour-xe2-and-lunar-lake-s-gpu.html
  271. // https://www.intel.com/content/www/us/en/docs/oneapi/optimization-guide-gpu/2025-0/intel-xe-gpu-architecture.html
  272. return vk_device_architecture::INTEL_XE2;
  273. }
  274. } else if (props.vendorID == VK_VENDOR_ID_NVIDIA) {
  275. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  276. bool cooperative_matrix = false;
  277. // Detect "pre-turing" based on lack of coopmat support.
  278. for (const auto& properties : ext_props) {
  279. if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0) {
  280. cooperative_matrix = true;
  281. break;
  282. }
  283. }
  284. if (!cooperative_matrix) {
  285. return vk_device_architecture::NVIDIA_PRE_TURING;
  286. }
  287. }
  288. return vk_device_architecture::OTHER;
  289. }
  290. enum vk_conv_shapes {
  291. CONV_SHAPE_128x128,
  292. CONV_SHAPE_64x32,
  293. CONV_SHAPE_32x256,
  294. CONV_SHAPE_COUNT,
  295. };
  296. struct vk_conv_block_size {
  297. uint32_t K;
  298. uint32_t NPQ;
  299. uint32_t CRS;
  300. };
  301. vk_conv_block_size vk_conv_block_sizes[CONV_SHAPE_COUNT] = {
  302. // K NPQ CRS
  303. { 128, 128, 16 }, // CONV_SHAPE_128x128
  304. { 64, 32, 32 }, // CONV_SHAPE_64x32
  305. { 32, 256, 16 }, // CONV_SHAPE_32x256
  306. };
  307. enum dmmv_wg_sizes {
  308. DMMV_WG_SIZE_SUBGROUP,
  309. DMMV_WG_SIZE_LARGE,
  310. DMMV_WG_SIZE_COUNT,
  311. };
  312. enum FaCodePath {
  313. FA_SCALAR,
  314. FA_COOPMAT1,
  315. FA_COOPMAT2,
  316. };
  317. struct vk_fa_pipeline_state {
  318. vk_fa_pipeline_state(uint32_t HSK, uint32_t HSV, bool small_rows, FaCodePath path, bool aligned, bool f32acc)
  319. : HSK(HSK), HSV(HSV), small_rows(small_rows), path(path), aligned(aligned), f32acc(f32acc) {}
  320. uint32_t HSK, HSV;
  321. bool small_rows;
  322. FaCodePath path;
  323. bool aligned;
  324. bool f32acc;
  325. bool operator<(const vk_fa_pipeline_state &b) const {
  326. return std::tie(HSK, HSV, small_rows, path, aligned, f32acc) <
  327. std::tie(b.HSK, b.HSV, b.small_rows, b.path, b.aligned, b.f32acc);
  328. }
  329. };
  330. struct vk_conv2d_pipeline_state {
  331. vk_conv2d_pipeline_state(uint32_t s0, uint32_t s1, uint32_t p0, uint32_t p1, uint32_t d0, uint32_t d1, uint32_t KW, uint32_t KH)
  332. : s0(s0), s1(s1), p0(p0), p1(p1), d0(d0), d1(d1), KW(KW), KH(KH) {}
  333. uint32_t s0, s1, p0, p1, d0, d1, KW, KH;
  334. bool operator<(const vk_conv2d_pipeline_state &b) const {
  335. return std::tie(s0, s1, p0, p1, d0, d1, KW, KH) <
  336. std::tie(b.s0, b.s1, b.p0, b.p1, b.d0, b.d1, b.KW, b.KH);
  337. }
  338. };
  339. struct vk_solve_tri_pipeline_state {
  340. vk_solve_tri_pipeline_state(uint32_t N, uint32_t K)
  341. : N(N), K(K) {}
  342. uint32_t N, K;
  343. bool operator<(const vk_solve_tri_pipeline_state &b) const {
  344. return std::tie(N, K) <
  345. std::tie(b.N, b.K);
  346. }
  347. };
  348. enum shader_reduction_mode {
  349. SHADER_REDUCTION_MODE_SHMEM,
  350. SHADER_REDUCTION_MODE_HYBRID,
  351. SHADER_REDUCTION_MODE_SUBGROUP,
  352. SHADER_REDUCTION_MODE_COUNT,
  353. };
  354. // argsort pipelines for up to 1<<10 invocations per workgroup
  355. static constexpr uint32_t num_argsort_pipelines = 11;
  356. static constexpr uint32_t num_topk_moe_pipelines = 10;
  357. static constexpr uint32_t num_topk_pipelines = 11;
  358. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax_norm{ GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  359. GGML_OP_VIEW, GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  360. GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV,
  361. GGML_OP_RESHAPE };
  362. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax { GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  363. GGML_OP_VIEW, GGML_OP_GET_ROWS };
  364. static constexpr std::initializer_list<ggml_op> topk_moe_late_softmax { GGML_OP_ARGSORT, GGML_OP_VIEW,
  365. GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  366. GGML_OP_SOFT_MAX, GGML_OP_RESHAPE };
  367. //node #978 ( SOFT_MAX): ffn_moe_probs-15 ( 0K) [Vulka ] use=2: ffn_moe_logits-15 ( 0K) [Vulka ]
  368. //node #979 ( RESHAPE): ffn_moe_probs-15 (re ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  369. //node #980 ( ARGSORT): ffn_moe_argsort-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  370. //node #981 ( VIEW): ffn_moe_topk-15 ( 0K) [Vulka ] use=4: ffn_moe_argsort-15 ( 0K) [Vulka ]
  371. //node #982 ( GET_ROWS): ffn_moe_weights-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 (re ( 0K) [Vulka ] ffn_moe_topk-15 ( 0K) [Vulka ]
  372. //node #983 ( RESHAPE): ffn_moe_weights-15 ( ( 0K) [Vulka ] use=2: ffn_moe_weights-15 ( 0K) [Vulka ]
  373. //node #984 ( SUM_ROWS): ffn_moe_weights_sum- ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ]
  374. //node #985 ( CLAMP): ffn_moe_weights_sum_ ( 0K) [Vulka ] use=1: ffn_moe_weights_sum- ( 0K) [Vulka ]
  375. //node #986 ( DIV): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ] ffn_moe_weights_sum_ ( 0K) [Vulka ]
  376. //node #987 ( RESHAPE): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights_norm ( 0K) [Vulka ]
  377. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_norm_edges {
  378. { 1, 0, 0 }, // reshape->src[0] == softmax
  379. { 2, 0, 0 }, // argsort->src[0] == softmax
  380. { 3, 0, 2 }, // view->src[0] == argsort
  381. { 4, 0, 1 }, // get_rows->src[0] == reshape
  382. { 4, 1, 3 }, // get_rows->src[1] == view
  383. { 5, 0, 4 }, // reshape->src[0] == get_rows
  384. { 6, 0, 5 }, // sum_rows->src[0] == reshape
  385. { 7, 0, 6 }, // clamp->src[0] == sum_rows
  386. { 8, 0, 5 }, // div->src[0] == reshape
  387. { 8, 1, 7 }, // div->src[1] == clamp
  388. { 9, 0, 8 }, // reshape->src[0] == div
  389. };
  390. // same as early_softmax_norm but ending after the get_rows
  391. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_edges {
  392. { 1, 0, 0 }, // reshape->src[0] == softmax
  393. { 2, 0, 0 }, // argsort->src[0] == softmax
  394. { 3, 0, 2 }, // view->src[0] == argsort
  395. { 4, 0, 1 }, // get_rows->src[0] == reshape
  396. { 4, 1, 3 }, // get_rows->src[1] == view
  397. };
  398. //node #652 ( ARGSORT): ffn_moe_argsort-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 ( 0K) [Vulka ]
  399. //node #653 ( VIEW): ffn_moe_topk-11 ( 0K) [Vulka ] use=7: ffn_moe_argsort-11 ( 0K) [Vulka ]
  400. //node #654 ( GET_ROWS): ffn_moe_weights-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 (re ( 0K) [Vulka ] ffn_moe_topk-11 ( 0K) [Vulka ]
  401. //node #655 ( RESHAPE): ffn_moe_weights-11 ( ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( 0K) [Vulka ]
  402. //node #656 ( SOFT_MAX): node_656 ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( ( 0K) [Vulka ]
  403. //node #657 ( RESHAPE): ffn_moe_weights_soft ( 0K) [Vulka ] use=1: node_656 ( 0K) [Vulka ]
  404. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_late_softmax_edges {
  405. { 1, 0, 0 }, // view->src[0] == argsort
  406. { 2, 1, 1 }, // get_rows->src[1] == view
  407. { 3, 0, 2 }, // reshape->src[0] == get_rows
  408. { 4, 0, 3 }, // soft_max->src[0] == reshape
  409. { 5, 0, 4 }, // reshape->src[0] == soft_max
  410. };
  411. enum topk_moe_mode {
  412. TOPK_MOE_EARLY_SOFTMAX,
  413. TOPK_MOE_EARLY_SOFTMAX_NORM,
  414. TOPK_MOE_LATE_SOFTMAX,
  415. TOPK_MOE_COUNT,
  416. };
  417. static topk_moe_mode ggml_vk_num_additional_ops_to_topk_moe_mode(uint32_t num) {
  418. topk_moe_mode mode = num == topk_moe_early_softmax_norm.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX_NORM :
  419. num == topk_moe_early_softmax.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX :
  420. TOPK_MOE_LATE_SOFTMAX;
  421. return mode;
  422. }
  423. static constexpr std::initializer_list<std::array<int, 3>> rope_view_set_rows_edges {
  424. { 1, 0, 0 }, // view->src[0] == rope
  425. { 2, 0, 1 }, // set_rows->src[0] == view
  426. };
  427. static constexpr std::initializer_list<std::array<int, 3>> rms_norm_mul_rope_view_set_rows_edges {
  428. { 1, 0, 0 }, // mul->src[0] == rms
  429. { 2, 0, 1 }, // rope->src[0] == mul
  430. { 3, 0, 2 }, // view->src[0] == rope
  431. { 4, 0, 3 }, // set_rows->src[0] == view
  432. };
  433. struct vk_device_struct {
  434. std::recursive_mutex mutex;
  435. vk::PhysicalDevice physical_device;
  436. vk::PhysicalDeviceProperties properties;
  437. std::string name;
  438. uint64_t max_memory_allocation_size;
  439. uint64_t max_buffer_size;
  440. uint64_t suballocation_block_size;
  441. bool fp16;
  442. bool bf16;
  443. bool pipeline_robustness;
  444. bool memory_priority;
  445. vk::Device device;
  446. uint32_t vendor_id;
  447. vk::DriverId driver_id;
  448. vk_device_architecture architecture;
  449. vk_queue compute_queue;
  450. vk_queue transfer_queue;
  451. bool single_queue;
  452. bool support_async;
  453. uint32_t subgroup_size;
  454. uint32_t subgroup_size_log2;
  455. uint32_t shader_core_count;
  456. bool uma;
  457. bool prefer_host_memory;
  458. bool float_controls_rte_fp16;
  459. bool subgroup_arithmetic;
  460. bool subgroup_shuffle;
  461. bool subgroup_ballot;
  462. bool subgroup_clustered;
  463. bool subgroup_vote;
  464. bool multi_add;
  465. bool shader_int64;
  466. bool buffer_device_address;
  467. bool vulkan_memory_model;
  468. bool add_rms_fusion;
  469. uint32_t partials_binding_alignment;
  470. bool integer_dot_product;
  471. // 0: default, 1: force mmvq, -1: disable mmvq
  472. int32_t mmvq_mode;
  473. bool subgroup_size_control;
  474. uint32_t subgroup_min_size;
  475. uint32_t subgroup_max_size;
  476. bool subgroup_require_full_support;
  477. // floor(log2(maxComputeWorkGroupInvocations))
  478. uint32_t max_workgroup_size_log2 {};
  479. bool coopmat_support;
  480. bool coopmat_acc_f32_support {};
  481. bool coopmat_acc_f16_support {};
  482. bool coopmat_bf16_support {};
  483. bool coopmat_support_16x16x16_f16acc {};
  484. bool coopmat_support_16x16x16_f32acc {};
  485. bool coopmat1_fa_support {};
  486. uint32_t coopmat_m;
  487. uint32_t coopmat_n;
  488. uint32_t coopmat_k;
  489. bool coopmat_int_support;
  490. uint32_t coopmat_int_m;
  491. uint32_t coopmat_int_n;
  492. uint32_t coopmat_int_k;
  493. bool coopmat2;
  494. bool pipeline_executable_properties_support {};
  495. size_t idx;
  496. bool mul_mat_l[GGML_TYPE_COUNT];
  497. bool mul_mat_m[GGML_TYPE_COUNT];
  498. bool mul_mat_s[GGML_TYPE_COUNT];
  499. bool mul_mat_id_l[GGML_TYPE_COUNT];
  500. bool mul_mat_id_m[GGML_TYPE_COUNT];
  501. bool mul_mat_id_s[GGML_TYPE_COUNT];
  502. vk::DescriptorSetLayout dsl;
  503. vk_matmul_pipeline pipeline_matmul_f32 {};
  504. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  505. vk_matmul_pipeline pipeline_matmul_bf16 {};
  506. vk_matmul_pipeline2 pipeline_matmul_f16;
  507. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  508. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  509. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  510. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_COUNT];
  511. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  512. vk_matmul_pipeline pipeline_matmul_id_bf16 {};
  513. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  514. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  515. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  516. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_COUNT];
  517. vk_pipeline pipeline_matmul_split_k_reduce;
  518. vk_pipeline pipeline_quantize_q8_1_x4;
  519. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  520. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  521. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  522. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT];
  523. vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  524. vk_pipeline pipeline_dequant_mul_mat_vec_id_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT];
  525. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio];
  526. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  527. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  528. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  529. vk_pipeline pipeline_acc_f32;
  530. // [src0 0=fp32,1=fp16][src1 0=fp32,1=fp16][dst 0=fp32,1=fp16]
  531. vk_pipeline pipeline_add[2][2][2];
  532. vk_pipeline pipeline_add_norepeat[2][2][2];
  533. vk_pipeline pipeline_sub[2][2][2];
  534. vk_pipeline pipeline_sub_norepeat[2][2][2];
  535. vk_pipeline pipeline_mul[2][2][2];
  536. vk_pipeline pipeline_mul_norepeat[2][2][2];
  537. vk_pipeline pipeline_div[2][2][2];
  538. vk_pipeline pipeline_div_norepeat[2][2][2];
  539. vk_pipeline pipeline_add_rms[2][2][2];
  540. vk_pipeline pipeline_add_rms_norepeat[2][2][2];
  541. // indexed by num_additional_fused_ops == num_adds - 1
  542. vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS];
  543. vk_pipeline pipeline_multi_add_rms[MAX_FUSED_ADDS];
  544. vk_pipeline pipeline_add_id_f32;
  545. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  546. vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32, pipeline_upscale_bicubic_f32;
  547. vk_pipeline pipeline_scale_f32;
  548. vk_pipeline pipeline_sqr_f32;
  549. vk_pipeline pipeline_sqrt_f32;
  550. vk_pipeline pipeline_sin_f32;
  551. vk_pipeline pipeline_cos_f32;
  552. vk_pipeline pipeline_log[2];
  553. vk_pipeline pipeline_tri[2];
  554. vk_pipeline pipeline_diag[2];
  555. vk_pipeline pipeline_clamp_f32;
  556. vk_pipeline pipeline_pad_f32;
  557. vk_pipeline pipeline_roll_f32;
  558. vk_pipeline pipeline_repeat_f32, pipeline_repeat_back_f32;
  559. vk_pipeline pipeline_cpy_f32_f32, pipeline_cpy_f32_f16, pipeline_cpy_f16_f16, pipeline_cpy_f16_f32, pipeline_cpy_f32_bf16, pipeline_cpy_f32_i32, pipeline_cpy_i32_f32;
  560. vk_pipeline pipeline_contig_cpy_f32_f32, pipeline_contig_cpy_f32_f16, pipeline_contig_cpy_f16_f16, pipeline_contig_cpy_f16_f32, pipeline_contig_cpy_f32_bf16, pipeline_contig_cpy_f32_i32, pipeline_contig_cpy_i32_f32;
  561. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  562. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  563. vk_pipeline pipeline_cpy_transpose_16, pipeline_cpy_transpose_32;
  564. vk_pipeline pipeline_set_rows_i32[GGML_TYPE_COUNT];
  565. vk_pipeline pipeline_set_rows_i64[GGML_TYPE_COUNT];
  566. vk_pipeline pipeline_norm_f32;
  567. vk_pipeline pipeline_group_norm_f32;
  568. vk_pipeline pipeline_rms_norm_f32;
  569. vk_pipeline pipeline_rms_norm_mul_f32;
  570. vk_pipeline pipeline_rms_norm_partials_f32;
  571. vk_pipeline pipeline_rms_norm_mul_partials_f32;
  572. vk_pipeline pipeline_rms_norm_mul_rope_f32_f32;
  573. vk_pipeline pipeline_rms_norm_mul_rope_f32_f16;
  574. vk_pipeline pipeline_rms_norm_back_f32;
  575. vk_pipeline pipeline_l2_norm_f32;
  576. // [src/dst 0=fp32,1=fp16]
  577. vk_pipeline pipeline_exp[2];
  578. vk_pipeline pipeline_gelu[2];
  579. vk_pipeline pipeline_gelu_erf[2];
  580. vk_pipeline pipeline_gelu_quick[2];
  581. vk_pipeline pipeline_silu[2];
  582. vk_pipeline pipeline_relu[2];
  583. vk_pipeline pipeline_neg[2];
  584. vk_pipeline pipeline_tanh[2];
  585. vk_pipeline pipeline_sigmoid[2];
  586. vk_pipeline pipeline_hardsigmoid[2];
  587. vk_pipeline pipeline_hardswish[2];
  588. vk_pipeline pipeline_abs[2];
  589. vk_pipeline pipeline_softplus[2];
  590. vk_pipeline pipeline_step[2];
  591. vk_pipeline pipeline_round[2];
  592. vk_pipeline pipeline_ceil[2];
  593. vk_pipeline pipeline_floor[2];
  594. vk_pipeline pipeline_trunc[2];
  595. vk_pipeline pipeline_add1_f16_f16;
  596. vk_pipeline pipeline_add1_f16_f32;
  597. vk_pipeline pipeline_add1_f32_f32;
  598. vk_pipeline pipeline_arange_f32;
  599. vk_pipeline pipeline_fill_f32;
  600. vk_pipeline pipeline_geglu[2];
  601. vk_pipeline pipeline_reglu[2];
  602. vk_pipeline pipeline_swiglu[2];
  603. vk_pipeline pipeline_swiglu_oai[2];
  604. vk_pipeline pipeline_geglu_erf[2];
  605. vk_pipeline pipeline_geglu_quick[2];
  606. vk_pipeline pipeline_leaky_relu_f32;
  607. vk_pipeline pipeline_silu_back_f32;
  608. vk_pipeline pipeline_diag_mask_inf_f32;
  609. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  610. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  611. vk_pipeline pipeline_soft_max_back_f32;
  612. vk_pipeline pipeline_soft_max_large1_f32, pipeline_soft_max_large1_f32_f16;
  613. vk_pipeline pipeline_soft_max_large2_f32, pipeline_soft_max_large2_f32_f16;
  614. vk_pipeline pipeline_soft_max_large3_f32, pipeline_soft_max_large3_f32_f16;
  615. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16, pipeline_rope_norm_f32_f16;
  616. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16, pipeline_rope_neox_f32_f16;
  617. vk_pipeline pipeline_rope_multi_f32, pipeline_rope_multi_f16;
  618. vk_pipeline pipeline_rope_vision_f32, pipeline_rope_vision_f16;
  619. vk_pipeline pipeline_argsort_f32[num_argsort_pipelines];
  620. vk_pipeline pipeline_argsort_large_f32[num_argsort_pipelines];
  621. vk_pipeline pipeline_topk_f32[num_topk_pipelines];
  622. vk_pipeline pipeline_sum_rows_f32;
  623. vk_pipeline pipeline_cumsum_f32;
  624. vk_pipeline pipeline_argmax_f32;
  625. vk_pipeline pipeline_count_equal_i32;
  626. std::map<vk_solve_tri_pipeline_state, vk_pipeline> pipeline_solve_tri_f32;
  627. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  628. vk_pipeline pipeline_im2col_3d_f32, pipeline_im2col_3d_f32_f16;
  629. vk_pipeline pipeline_timestep_embedding_f32;
  630. vk_pipeline pipeline_conv_transpose_1d_f32;
  631. vk_pipeline pipeline_pool2d_f32;
  632. vk_pipeline pipeline_rwkv_wkv6_f32;
  633. vk_pipeline pipeline_rwkv_wkv7_f32;
  634. vk_pipeline pipeline_ssm_scan_f32_d128;
  635. vk_pipeline pipeline_ssm_scan_f32_d256;
  636. vk_pipeline pipeline_ssm_conv_f32;
  637. vk_pipeline pipeline_opt_step_adamw_f32;
  638. vk_pipeline pipeline_opt_step_sgd_f32;
  639. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f32[CONV_SHAPE_COUNT];
  640. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f16_f32[CONV_SHAPE_COUNT];
  641. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f32[CONV_SHAPE_COUNT];
  642. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f16_f32[CONV_SHAPE_COUNT];
  643. vk_pipeline pipeline_conv2d_dw_whcn_f32, pipeline_conv2d_dw_whcn_f16_f32;
  644. vk_pipeline pipeline_conv2d_dw_cwhn_f32, pipeline_conv2d_dw_cwhn_f16_f32;
  645. std::map<vk_fa_pipeline_state, vk_pipeline> pipeline_flash_attn_f32_f16[GGML_TYPE_COUNT];
  646. vk_pipeline pipeline_flash_attn_split_k_reduce;
  647. // [2] is for whether to take n_experts from spec constant (0) or push constant (1)
  648. vk_pipeline pipeline_topk_moe[num_topk_moe_pipelines][TOPK_MOE_COUNT][2];
  649. std::vector<vk_pipeline_ref> all_pipelines;
  650. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  651. vk::Fence fence;
  652. vk_buffer sync_staging;
  653. ggml_backend_buffer_type buffer_type;
  654. bool disable_fusion;
  655. bool disable_host_visible_vidmem;
  656. bool allow_sysmem_fallback;
  657. bool disable_graph_optimize;
  658. #ifdef GGML_VULKAN_MEMORY_DEBUG
  659. std::unique_ptr<vk_memory_logger> memory_logger;
  660. #endif
  661. ~vk_device_struct() {
  662. VK_LOG_DEBUG("destroy device " << name);
  663. device.destroyFence(fence);
  664. ggml_vk_destroy_buffer(sync_staging);
  665. compute_queue.cmd_pool.destroy(device);
  666. transfer_queue.cmd_pool.destroy(device);
  667. for (auto& pipeline : all_pipelines) {
  668. if (pipeline.expired()) {
  669. continue;
  670. }
  671. vk_pipeline pl = pipeline.lock();
  672. ggml_vk_destroy_pipeline(device, pl);
  673. }
  674. all_pipelines.clear();
  675. device.destroyDescriptorSetLayout(dsl);
  676. device.destroy();
  677. }
  678. };
  679. void vk_command_pool::init(vk_device& device, vk_queue *q_) {
  680. cmd_buffer_idx = 0;
  681. q = q_;
  682. vk::CommandPoolCreateInfo command_pool_create_info(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), q->queue_family_index);
  683. pool = device->device.createCommandPool(command_pool_create_info);
  684. }
  685. void vk_command_pool::destroy(vk::Device& device) {
  686. device.destroyCommandPool(pool);
  687. pool = nullptr;
  688. cmd_buffers.clear();
  689. }
  690. struct vk_buffer_struct {
  691. vk::Buffer buffer = VK_NULL_HANDLE;
  692. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  693. vk::MemoryPropertyFlags memory_property_flags;
  694. void * ptr;
  695. size_t size = 0;
  696. vk::DeviceAddress bda_addr {};
  697. vk_device device;
  698. ~vk_buffer_struct() {
  699. if (size == 0) {
  700. return;
  701. }
  702. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  703. device->device.freeMemory(device_memory);
  704. device->device.destroyBuffer(buffer);
  705. }
  706. };
  707. struct vk_subbuffer {
  708. vk_buffer buffer;
  709. uint64_t offset;
  710. uint64_t size;
  711. operator vk::DescriptorBufferInfo() const {
  712. return { buffer->buffer, offset, size };
  713. }
  714. };
  715. struct vk_semaphore {
  716. vk::Semaphore s;
  717. uint64_t value;
  718. };
  719. struct vk_submission {
  720. vk::CommandBuffer buffer;
  721. std::vector<vk_semaphore> wait_semaphores;
  722. std::vector<vk_semaphore> signal_semaphores;
  723. };
  724. typedef std::vector<vk_submission> vk_sequence;
  725. struct vk_mat_mat_push_constants {
  726. uint32_t M; uint32_t N; uint32_t K;
  727. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  728. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  729. uint32_t k_split;
  730. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  731. uint32_t padded_N;
  732. };
  733. #define MAT_VEC_FUSION_FLAGS_BIAS0 0x1
  734. #define MAT_VEC_FUSION_FLAGS_BIAS1 0x2
  735. #define MAT_VEC_FUSION_FLAGS_SCALE0 0x4
  736. #define MAT_VEC_FUSION_FLAGS_SCALE1 0x8
  737. struct vk_mat_vec_push_constants {
  738. uint32_t ncols;
  739. uint32_t stride_a;
  740. uint32_t stride_b;
  741. uint32_t stride_d;
  742. uint32_t batch_stride_a;
  743. uint32_t batch_stride_b;
  744. uint32_t batch_stride_d;
  745. uint32_t fusion_flags;
  746. uint32_t ne02;
  747. uint32_t ne12;
  748. uint32_t broadcast2;
  749. uint32_t broadcast3;
  750. };
  751. struct vk_mat_vec_p021_push_constants {
  752. uint32_t ncols_x;
  753. uint32_t nrows_x;
  754. uint32_t nchannels_x;
  755. uint32_t nchannels_y;
  756. uint32_t b_offset;
  757. uint32_t d_offset;
  758. uint32_t fusion_flags;
  759. };
  760. struct vk_mat_vec_nc_push_constants {
  761. uint32_t ncols_x;
  762. uint32_t nrows_x;
  763. uint32_t row_stride_x;
  764. uint32_t channel_stride_x;
  765. uint32_t channel_stride_y;
  766. uint32_t channel_x_divisor;
  767. uint32_t ne12;
  768. uint32_t b_offset;
  769. uint32_t d_offset;
  770. uint32_t nb03;
  771. uint32_t nb13;
  772. uint32_t nb23;
  773. uint32_t fusion_flags;
  774. };
  775. struct vk_mat_mat_id_push_constants {
  776. uint32_t M; uint32_t N; uint32_t K;
  777. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  778. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  779. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  780. uint32_t padded_N;
  781. };
  782. struct vk_mat_vec_id_push_constants {
  783. uint32_t ncols;
  784. uint32_t stride_a;
  785. uint32_t stride_b;
  786. uint32_t stride_d;
  787. uint32_t batch_stride_a;
  788. uint32_t batch_stride_b;
  789. uint32_t batch_stride_d;
  790. uint32_t fusion_flags;
  791. uint32_t nei0;
  792. uint32_t ne11;
  793. };
  794. struct vk_flash_attn_push_constants {
  795. uint32_t N;
  796. uint32_t KV;
  797. uint32_t ne1;
  798. uint32_t ne2;
  799. uint32_t ne3;
  800. uint32_t neq2;
  801. uint32_t neq3;
  802. uint32_t nek2;
  803. uint32_t nek3;
  804. uint32_t nev2;
  805. uint32_t nev3;
  806. uint32_t nem1;
  807. uint32_t nem2;
  808. uint32_t nem3;
  809. uint32_t nb01;
  810. uint32_t nb02;
  811. uint32_t nb03;
  812. uint32_t nb11;
  813. uint32_t nb12;
  814. uint32_t nb13;
  815. uint32_t nb21;
  816. uint32_t nb22;
  817. uint32_t nb23;
  818. float scale;
  819. float max_bias;
  820. float logit_softcap;
  821. uint32_t mask_n_head_log2;
  822. float m0;
  823. float m1;
  824. uint32_t gqa_ratio;
  825. uint32_t split_kv;
  826. uint32_t k_num;
  827. };
  828. static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128");
  829. struct vk_op_push_constants {
  830. uint32_t KX;
  831. uint32_t KY;
  832. float param1;
  833. float param2;
  834. };
  835. struct vk_op_glu_push_constants {
  836. uint32_t N;
  837. uint32_t ne00;
  838. uint32_t ne20;
  839. uint32_t mode; // 0: default, 1: swapped, 2: split
  840. float alpha; // for swiglu_oai
  841. float limit;
  842. };
  843. struct vk_op_unary_push_constants {
  844. uint32_t ne;
  845. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  846. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  847. uint32_t misalign_offsets;
  848. float param1; float param2;
  849. uint32_t ne0_012mp; uint32_t ne0_012L;
  850. uint32_t ne0_01mp; uint32_t ne0_01L;
  851. uint32_t ne0_0mp; uint32_t ne0_0L;
  852. uint32_t ne1_012mp; uint32_t ne1_012L;
  853. uint32_t ne1_01mp; uint32_t ne1_01L;
  854. uint32_t ne1_0mp; uint32_t ne1_0L;
  855. };
  856. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  857. static vk_op_unary_push_constants vk_op_unary_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst, int64_t ne = 0) {
  858. GGML_ASSERT(ne != 0 || (ggml_nelements(src0) == ggml_nelements(dst)));
  859. ne = ne != 0 ? ne : ggml_nelements(dst);
  860. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  861. vk_op_unary_push_constants p{};
  862. p.ne = (uint32_t)ne;
  863. size_t src0_tsize = ggml_type_size(src0->type);
  864. p.ne00 = (uint32_t)src0->ne[0];
  865. p.ne01 = (uint32_t)src0->ne[1];
  866. p.ne02 = (uint32_t)src0->ne[2];
  867. p.ne03 = (uint32_t)src0->ne[3];
  868. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  869. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  870. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  871. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  872. size_t dst_tsize = ggml_type_size(dst->type);
  873. p.ne10 = (uint32_t)dst->ne[0];
  874. p.ne11 = (uint32_t)dst->ne[1];
  875. p.ne12 = (uint32_t)dst->ne[2];
  876. p.ne13 = (uint32_t)dst->ne[3];
  877. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  878. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  879. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  880. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  881. return p; // offsets are initialized later in ggml_vk_op
  882. }
  883. struct vk_op_pad_push_constants {
  884. uint32_t ne;
  885. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  886. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  887. uint32_t misalign_offsets;
  888. uint32_t circular;
  889. uint32_t lp0; uint32_t rp0;
  890. uint32_t lp1; uint32_t rp1;
  891. uint32_t lp2; uint32_t rp2;
  892. uint32_t lp3; uint32_t rp3;
  893. };
  894. static vk_op_pad_push_constants vk_op_pad_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst) {
  895. int64_t ne = ggml_nelements(dst);
  896. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  897. vk_op_pad_push_constants p{};
  898. p.ne = (uint32_t)ne;
  899. size_t src0_tsize = ggml_type_size(src0->type);
  900. p.ne00 = (uint32_t)src0->ne[0];
  901. p.ne01 = (uint32_t)src0->ne[1];
  902. p.ne02 = (uint32_t)src0->ne[2];
  903. p.ne03 = (uint32_t)src0->ne[3];
  904. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  905. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  906. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  907. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  908. size_t dst_tsize = ggml_type_size(dst->type);
  909. p.ne10 = (uint32_t)dst->ne[0];
  910. p.ne11 = (uint32_t)dst->ne[1];
  911. p.ne12 = (uint32_t)dst->ne[2];
  912. p.ne13 = (uint32_t)dst->ne[3];
  913. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  914. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  915. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  916. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  917. p.lp0 = dst->op_params[0];
  918. p.rp0 = dst->op_params[1];
  919. p.lp1 = dst->op_params[2];
  920. p.rp1 = dst->op_params[3];
  921. p.lp2 = dst->op_params[4];
  922. p.rp2 = dst->op_params[5];
  923. p.lp3 = dst->op_params[6];
  924. p.rp3 = dst->op_params[7];
  925. p.circular = dst->op_params[8];
  926. return p; // fastdiv values and offsets are initialized later in ggml_vk_op
  927. }
  928. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  929. // Precompute mp (m' in the paper) and L such that division
  930. // can be computed using a multiply (high 32b of 64b result)
  931. // and a shift:
  932. //
  933. // n/d = (mulhi(n, mp) + n) >> L;
  934. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  935. {
  936. // compute L = ceil(log2(d));
  937. L = 0;
  938. while (L < 32 && (uint32_t{1} << L) < d) {
  939. L++;
  940. }
  941. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  942. }
  943. template <typename T> void init_pushconst_fastdiv(T &p) {
  944. GGML_UNUSED(p);
  945. static_assert(!std::is_const<T>::value, "unexpected type");
  946. }
  947. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  948. // Compute magic values to divide by these six numbers.
  949. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  950. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  951. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  952. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  953. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  954. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  955. }
  956. struct vk_op_binary_push_constants {
  957. uint32_t ne;
  958. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  959. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  960. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  961. uint32_t misalign_offsets;
  962. float param1; float param2; int32_t param3;
  963. };
  964. struct vk_op_multi_add_push_constants {
  965. // shape for dst
  966. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23;
  967. // strides for srcs+dst
  968. uint32_t nb[MAX_PARAMETER_COUNT][4];
  969. uint32_t rms_partials;
  970. };
  971. // update multi_add.comp if this changes
  972. static_assert(MAX_PARAMETER_COUNT == 12);
  973. static_assert(sizeof(vk_op_multi_add_push_constants) <= 256);
  974. struct vk_op_topk_moe_push_constants {
  975. uint32_t n_rows;
  976. uint32_t n_experts_push;
  977. uint32_t n_expert_used;
  978. float clamp_min;
  979. float clamp_max;
  980. };
  981. struct vk_op_add_id_push_constants {
  982. uint32_t ne0;
  983. uint32_t ne1;
  984. uint32_t s01;
  985. uint32_t s02;
  986. uint32_t s11;
  987. uint32_t s21;
  988. };
  989. struct vk_op_diag_mask_push_constants {
  990. uint32_t ncols;
  991. uint32_t rows_per_channel;
  992. int32_t n_past;
  993. };
  994. struct vk_op_rope_push_constants {
  995. uint32_t rope_mode;
  996. uint32_t ncols;
  997. uint32_t n_dims;
  998. float freq_scale;
  999. uint32_t p_delta_rows;
  1000. float freq_base;
  1001. float ext_factor;
  1002. float attn_factor;
  1003. float corr_dims[2];
  1004. float theta_scale;
  1005. uint32_t has_ff;
  1006. uint32_t ne02;
  1007. uint32_t s1;
  1008. uint32_t s2;
  1009. int32_t sections[4];
  1010. uint32_t is_imrope;
  1011. uint32_t is_back;
  1012. uint32_t set_rows_stride;
  1013. };
  1014. // For fused rms_norm+mul+rope(+view+set_rows)
  1015. struct vk_op_rms_norm_mul_rope_push_constants {
  1016. vk_op_binary_push_constants bin;
  1017. vk_op_rope_push_constants rope;
  1018. };
  1019. struct vk_op_soft_max_push_constants {
  1020. uint32_t KX;
  1021. uint32_t KY;
  1022. uint32_t ne00;
  1023. uint32_t ne01;
  1024. uint32_t ne02;
  1025. uint32_t ne12;
  1026. uint32_t ne13;
  1027. uint32_t nb11;
  1028. uint32_t nb12;
  1029. uint32_t nb13;
  1030. float scale;
  1031. float max_bias;
  1032. float m0;
  1033. float m1;
  1034. uint32_t n_head_log2;
  1035. uint32_t nrows_x;
  1036. uint32_t has_sinks;
  1037. };
  1038. struct vk_op_argsort_push_constants {
  1039. uint32_t ncols;
  1040. uint32_t ncols_padded;
  1041. uint32_t ncols_padded_log2;
  1042. uint32_t nrows;
  1043. uint32_t order;
  1044. uint32_t outer_start;
  1045. uint32_t outer_end;
  1046. uint32_t inner_start;
  1047. uint32_t inner_end;
  1048. };
  1049. struct vk_op_topk_push_constants {
  1050. uint32_t orig_ncols;
  1051. uint32_t ncols_input;
  1052. uint32_t ncols_output;
  1053. uint32_t k;
  1054. uint32_t nrows;
  1055. uint32_t first_pass;
  1056. uint32_t last_pass;
  1057. };
  1058. struct vk_op_im2col_push_constants {
  1059. uint64_t dst_addr;
  1060. uint32_t batch_offset; uint32_t offset_delta;
  1061. uint32_t IC;
  1062. uint32_t IW; uint32_t IH;
  1063. uint32_t OW; uint32_t OH;
  1064. uint32_t KW; uint32_t KH;
  1065. uint32_t pelements;
  1066. uint32_t CHW;
  1067. int32_t s0; int32_t s1;
  1068. int32_t p0; int32_t p1;
  1069. int32_t d0; int32_t d1;
  1070. };
  1071. struct vk_op_im2col_3d_push_constants {
  1072. uint64_t dst_addr;
  1073. uint32_t nb10;
  1074. uint32_t nb11;
  1075. uint32_t nb12;
  1076. uint32_t nb13;
  1077. uint32_t s0;
  1078. uint32_t s1;
  1079. uint32_t s2;
  1080. uint32_t p0;
  1081. uint32_t p1;
  1082. uint32_t p2;
  1083. uint32_t d0;
  1084. uint32_t d1;
  1085. uint32_t d2;
  1086. uint32_t IW;
  1087. uint32_t IH;
  1088. uint32_t ID;
  1089. uint32_t IC;
  1090. uint32_t KW;
  1091. uint32_t OH;
  1092. uint32_t KD_KH_KW;
  1093. uint32_t KH_KW;
  1094. uint32_t IC_KD_KH_KW;
  1095. uint32_t N_OD_OH;
  1096. uint32_t OD_OH;
  1097. uint32_t OD_OH_OW_IC_KD_KH_KW;
  1098. uint32_t OH_OW_IC_KD_KH_KW;
  1099. uint32_t OW_IC_KD_KH_KW;
  1100. uint32_t misalign_offsets;
  1101. };
  1102. struct vk_op_timestep_embedding_push_constants {
  1103. uint32_t nb1;
  1104. uint32_t dim;
  1105. uint32_t max_period;
  1106. };
  1107. struct vk_op_conv_transpose_1d_push_constants {
  1108. uint32_t Cout;
  1109. uint32_t Cin;
  1110. uint32_t K;
  1111. uint32_t L;
  1112. uint32_t KL;
  1113. uint32_t nb01;
  1114. uint32_t nb02;
  1115. uint32_t nb11;
  1116. uint32_t nb1;
  1117. int32_t s0;
  1118. };
  1119. struct vk_op_pool2d_push_constants {
  1120. uint32_t IW; uint32_t IH;
  1121. uint32_t OW; uint32_t OH;
  1122. uint32_t OC;
  1123. uint32_t pelements;
  1124. uint32_t op;
  1125. int32_t k0; int32_t k1;
  1126. int32_t s0; int32_t s1;
  1127. int32_t p0; int32_t p1;
  1128. };
  1129. struct vk_op_rwkv_wkv6_push_constants {
  1130. uint32_t B;
  1131. uint32_t T;
  1132. uint32_t C;
  1133. uint32_t H;
  1134. };
  1135. struct vk_op_rwkv_wkv7_push_constants {
  1136. uint32_t B;
  1137. uint32_t T;
  1138. uint32_t C;
  1139. uint32_t H;
  1140. };
  1141. struct vk_op_ssm_scan_push_constants {
  1142. uint32_t nb02, nb03, nb12, nb13;
  1143. uint32_t nb21, nb22, nb31;
  1144. uint32_t nb42, nb43, nb52, nb53;
  1145. uint32_t s_off;
  1146. uint32_t n_head, d_head, n_group, n_tok;
  1147. };
  1148. struct vk_op_ssm_conv_push_constants {
  1149. uint32_t nb01, nb02;
  1150. uint32_t nb11;
  1151. uint32_t dst_nb0, dst_nb1, dst_nb2;
  1152. uint32_t nc, ncs, nr, n_t, n_s;
  1153. };
  1154. struct vk_op_conv2d_push_constants {
  1155. uint32_t Cout;
  1156. uint32_t Cin;
  1157. uint32_t N;
  1158. uint32_t W;
  1159. uint32_t H;
  1160. uint32_t OW;
  1161. uint32_t OH;
  1162. uint32_t nb01;
  1163. uint32_t nb02;
  1164. uint32_t nb03;
  1165. uint32_t nb11;
  1166. uint32_t nb12;
  1167. uint32_t nb13;
  1168. uint32_t nb1;
  1169. uint32_t nb2;
  1170. uint32_t nb3;
  1171. // init_fastdiv_values constants for dividing by OW, OW*OH
  1172. uint32_t OWmp; uint32_t OWL;
  1173. uint32_t OWOHmp; uint32_t OWOHL;
  1174. };
  1175. template <> void init_pushconst_fastdiv(vk_op_conv2d_push_constants &p) {
  1176. // Compute magic values to divide by OW, OW*OH
  1177. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1178. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1179. }
  1180. struct vk_op_conv2d_dw_push_constants {
  1181. uint32_t ne;
  1182. uint32_t batches;
  1183. uint32_t channels;
  1184. uint32_t dst_w;
  1185. uint32_t dst_h;
  1186. uint32_t src_w;
  1187. uint32_t src_h;
  1188. uint32_t knl_w;
  1189. uint32_t knl_h;
  1190. int32_t stride_x;
  1191. int32_t stride_y;
  1192. int32_t pad_x;
  1193. int32_t pad_y;
  1194. int32_t dilation_x;
  1195. int32_t dilation_y;
  1196. };
  1197. struct vk_op_upscale_push_constants {
  1198. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  1199. uint32_t ne00; uint32_t ne01;
  1200. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1201. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  1202. float sf0; float sf1; float sf2; float sf3;
  1203. float pixel_offset;
  1204. };
  1205. struct vk_op_sum_rows_push_constants
  1206. {
  1207. uint32_t n_cols;
  1208. uint32_t ne01, ne02;
  1209. uint32_t nb01, nb02, nb03;
  1210. uint32_t nb11, nb12, nb13;
  1211. float weight;
  1212. uint32_t misalign_offsets;
  1213. uint32_t ne0_12mp, ne0_12L;
  1214. uint32_t ne0_1mp, ne0_1L;
  1215. };
  1216. static vk_op_sum_rows_push_constants vk_op_sum_rows_push_constants_init(const ggml_tensor * src, const ggml_tensor * dst, int64_t n_cols) {
  1217. uint32_t type_size = (uint32_t)ggml_type_size(src->type);
  1218. vk_op_sum_rows_push_constants p = {};
  1219. p.n_cols = (uint32_t)n_cols;
  1220. p.ne01 = (uint32_t)src->ne[1];
  1221. p.ne02 = (uint32_t)src->ne[2];
  1222. p.nb01 = (uint32_t)src->nb[1] / type_size;
  1223. p.nb02 = (uint32_t)src->nb[2] / type_size;
  1224. p.nb03 = (uint32_t)src->nb[3] / type_size;
  1225. p.nb11 = (uint32_t)dst->nb[1] / type_size;
  1226. p.nb12 = (uint32_t)dst->nb[2] / type_size;
  1227. p.nb13 = (uint32_t)dst->nb[3] / type_size;
  1228. p.weight = 1.0f;
  1229. return p;
  1230. }
  1231. template <> void init_pushconst_fastdiv(vk_op_sum_rows_push_constants &p) {
  1232. init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L);
  1233. init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L);
  1234. }
  1235. // Allow pre-recording command buffers
  1236. struct vk_staging_memcpy {
  1237. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  1238. void * dst;
  1239. const void * src;
  1240. size_t n;
  1241. };
  1242. struct vk_staging_memset {
  1243. vk_staging_memset(void * _dst, uint32_t _val, size_t _n) : dst(_dst), val(_val), n(_n) {}
  1244. void * dst;
  1245. uint32_t val;
  1246. size_t n;
  1247. };
  1248. struct vk_context_struct {
  1249. vk_submission * s;
  1250. std::vector<vk_sequence> seqs;
  1251. int exit_tensor_idx;
  1252. std::vector<vk_staging_memcpy> in_memcpys;
  1253. std::vector<vk_staging_memcpy> out_memcpys;
  1254. std::vector<vk_staging_memset> memsets;
  1255. vk_command_pool * p {};
  1256. };
  1257. typedef std::shared_ptr<vk_context_struct> vk_context;
  1258. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  1259. struct ggml_vk_garbage_collector {
  1260. std::vector<vk_semaphore> tl_semaphores;
  1261. std::vector<vk_semaphore> semaphores;
  1262. std::vector<vk::Event> events;
  1263. std::vector<vk_context> contexts;
  1264. };
  1265. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx);
  1266. static void ggml_vk_load_shaders(vk_device& device);
  1267. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx);
  1268. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  1269. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  1270. static std::string format_size(size_t size) {
  1271. const size_t kib = 1024;
  1272. const size_t mib = kib * 1024;
  1273. const size_t gib = mib * 1024;
  1274. std::ostringstream oss;
  1275. oss << std::fixed << std::setprecision(2);
  1276. if (size >= gib) {
  1277. oss << static_cast<double>(size) / gib << " GiB";
  1278. } else if (size >= mib) {
  1279. oss << static_cast<double>(size) / mib << " MiB";
  1280. } else if (size >= kib) {
  1281. oss << static_cast<double>(size) / kib << " KiB";
  1282. } else {
  1283. oss << size << " B";
  1284. }
  1285. return oss.str();
  1286. }
  1287. class vk_memory_logger {
  1288. public:
  1289. vk_memory_logger(): total_device(0), total_host(0) {}
  1290. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  1291. void log_deallocation(vk_buffer_ref buf_ref);
  1292. private:
  1293. std::map<vk::Buffer, size_t> allocations; // Track allocations
  1294. size_t total_device;
  1295. size_t total_host;
  1296. };
  1297. #else
  1298. #define VK_LOG_MEMORY(msg) ((void) 0)
  1299. #endif // GGML_VULKAN_MEMORY_DEBUG
  1300. static bool vk_perf_logger_enabled = false;
  1301. // number of calls between perf logger prints
  1302. static uint32_t vk_perf_logger_frequency = 1;
  1303. class vk_perf_logger {
  1304. public:
  1305. void print_timings(bool force = false) {
  1306. if (timings.empty()) {
  1307. return;
  1308. }
  1309. print_count++;
  1310. if ((print_count % vk_perf_logger_frequency) != 0 && !force) {
  1311. return;
  1312. }
  1313. print_count = 0;
  1314. uint64_t total_all_op_times = 0;
  1315. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  1316. for (const auto & t : timings) {
  1317. uint64_t total_op_times = 0;
  1318. for (const auto & time : t.second) {
  1319. total_op_times += time;
  1320. }
  1321. std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0)
  1322. << " us";
  1323. // If we have as many flops entries as timing entries for the op, then compute and log the flops/S.
  1324. auto it = flops.find(t.first);
  1325. if (it != flops.end() && (it->second).size() == t.second.size()) {
  1326. uint64_t total_op_flops = 0;
  1327. for (const auto & elem : it->second) {
  1328. total_op_flops += elem;
  1329. }
  1330. std::cerr << " ("
  1331. << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) /
  1332. (double(total_op_times) / (1000.0 * 1000.0 * 1000.0))
  1333. << " GFLOPS/s)";
  1334. }
  1335. total_all_op_times += total_op_times;
  1336. std::cerr << std::endl;
  1337. }
  1338. if (timings.size() > 0) {
  1339. std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl;
  1340. }
  1341. timings.clear();
  1342. flops.clear();
  1343. }
  1344. void log_timing(const ggml_tensor * node, const char *fusion_name, uint64_t time) {
  1345. std::string fusion_str;
  1346. if (fusion_name) {
  1347. fusion_str = fusion_name + std::string(" ");
  1348. }
  1349. if (node->op == GGML_OP_UNARY) {
  1350. timings[fusion_str + ggml_unary_op_name(ggml_get_unary_op(node))].push_back(time);
  1351. return;
  1352. }
  1353. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  1354. const uint64_t m = node->ne[0];
  1355. const uint64_t n = node->ne[1];
  1356. const uint64_t k = node->src[1]->ne[0];
  1357. const uint64_t batch = node->ne[2] * node->ne[3];
  1358. std::string name = ggml_op_name(node->op);
  1359. if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) ||
  1360. (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) {
  1361. name += "_VEC";
  1362. }
  1363. name += " ";
  1364. name += ggml_type_name(node->src[0]->type);
  1365. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  1366. if (node->op == GGML_OP_MUL_MAT_ID) {
  1367. name += " n_expert=" + std::to_string(node->src[0]->ne[2]);
  1368. }
  1369. if (batch > 1) {
  1370. name += " batch=" + std::to_string(batch);
  1371. }
  1372. name = fusion_str + name;
  1373. timings[name].push_back(time);
  1374. flops[name].push_back(m * n * (k + (k - 1)) * batch);
  1375. return;
  1376. }
  1377. if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) {
  1378. std::string name = ggml_op_name(node->op);
  1379. ggml_tensor * knl = node->src[0];
  1380. uint64_t OW = node->ne[0];
  1381. uint64_t OH = node->ne[1];
  1382. uint64_t N = node->ne[3];
  1383. uint64_t Cout = node->ne[2];
  1384. uint64_t KW = knl->ne[0];
  1385. uint64_t KH = knl->ne[1];
  1386. uint64_t Cin = node->src[1]->ne[2];
  1387. // KxCRS @ CRSxNPQ = KxNPQ -> M=K, K=CRS, N=NPQ
  1388. uint64_t size_M = Cout;
  1389. uint64_t size_K = Cin * KW * KH;
  1390. uint64_t size_N = N * OW * OH;
  1391. uint64_t n_flops = size_M * size_N * (size_K + (size_K - 1));
  1392. name += " M=Cout=" + std::to_string(size_M) + ", K=Cin*KW*KH=" + std::to_string(size_K) +
  1393. ", N=N*OW*OH=" + std::to_string(size_N);
  1394. name = fusion_str + name;
  1395. flops[name].push_back(n_flops);
  1396. timings[name].push_back(time);
  1397. return;
  1398. }
  1399. if (node->op == GGML_OP_RMS_NORM) {
  1400. std::string name = ggml_op_name(node->op);
  1401. name += "(" + std::to_string(node->ne[0]) + "," + std::to_string(node->ne[1]) + "," + std::to_string(node->ne[2]) + "," + std::to_string(node->ne[3]) + ")";
  1402. name = fusion_str + name;
  1403. timings[name].push_back(time);
  1404. return;
  1405. }
  1406. if (node->op == GGML_OP_FLASH_ATTN_EXT) {
  1407. const ggml_tensor * dst = node;
  1408. const ggml_tensor * q = node->src[0];
  1409. const ggml_tensor * k = node->src[1];
  1410. const ggml_tensor * v = node->src[2];
  1411. const ggml_tensor * m = node->src[3];
  1412. std::stringstream name;
  1413. name << fusion_str;
  1414. name << ggml_op_name(node->op) <<
  1415. " dst(" << dst->ne[0] << "," << dst->ne[1] << "," << dst->ne[2] << "," << dst->ne[3] << "), " <<
  1416. " q(" << q->ne[0] << "," << q->ne[1] << "," << q->ne[2] << "," << q->ne[3] << "), " <<
  1417. " k(" << k->ne[0] << "," << k->ne[1] << "," << k->ne[2] << "," << k->ne[3] << "), " <<
  1418. " v(" << v->ne[0] << "," << v->ne[1] << "," << v->ne[2] << "," << v->ne[3] << "), " <<
  1419. " m(" << (m?m->ne[0]:0) << "," << (m?m->ne[1]:0) << "," << (m?m->ne[2]:0) << "," << (m?m->ne[3]:0) << ")";
  1420. timings[name.str()].push_back(time);
  1421. return;
  1422. }
  1423. if (node->op == GGML_OP_TOP_K) {
  1424. std::stringstream name;
  1425. name << fusion_str;
  1426. name << ggml_op_name(node->op) <<
  1427. " K=" << node->ne[0] <<
  1428. " (" << node->src[0]->ne[0] << "," << node->src[0]->ne[1] << "," << node->src[0]->ne[2] << "," << node->src[0]->ne[3] << ")";
  1429. timings[name.str()].push_back(time);
  1430. return;
  1431. }
  1432. timings[fusion_str + ggml_op_name(node->op)].push_back(time);
  1433. }
  1434. private:
  1435. std::map<std::string, std::vector<uint64_t>> timings;
  1436. std::map<std::string, std::vector<uint64_t>> flops;
  1437. uint32_t print_count {};
  1438. };
  1439. struct ggml_backend_vk_context {
  1440. std::string name;
  1441. vk_device device;
  1442. size_t semaphore_idx, event_idx;
  1443. ggml_vk_garbage_collector gc;
  1444. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset;
  1445. vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials, sync_staging;
  1446. vk::Fence fence, almost_ready_fence;
  1447. bool submit_pending {};
  1448. bool almost_ready_fence_pending {};
  1449. // Set before op_add and unset after op_rms_norm to indicate that the add should
  1450. // write partial sums to accumulate the square of the vector components
  1451. bool do_add_rms_partials_offset_calculation;
  1452. bool do_add_rms_partials;
  1453. uint64_t last_total_mul_mat_bytes {};
  1454. // Cache most recent tensor that was converted into prealloc_y, and what pipeline it used to convert.
  1455. vk_pipeline_struct * prealloc_y_last_pipeline_used {};
  1456. const ggml_tensor * prealloc_y_last_tensor_used {};
  1457. // Track which nodes have been used since the last sync, and whether they were written to
  1458. std::vector<const ggml_tensor *> unsynced_nodes_written;
  1459. std::vector<const ggml_tensor *> unsynced_nodes_read;
  1460. // Track which prealloc buffers have pending reads that need to be synchronized.
  1461. // These are checked before writing to the buffer (and call ggml_vk_sync_buffers if set),
  1462. // and set to true after the buffer contents are consumed.
  1463. bool prealloc_x_need_sync, prealloc_y_need_sync, prealloc_split_k_need_sync;
  1464. vk_context_ref compute_ctx;
  1465. vk_context_ref transfer_ctx;
  1466. std::vector<vk_context_ref> tensor_ctxs;
  1467. std::vector<vk::DescriptorPool> descriptor_pools;
  1468. std::vector<vk::DescriptorSet> descriptor_sets;
  1469. uint32_t descriptor_set_idx {};
  1470. uint32_t pipeline_descriptor_set_requirements {};
  1471. vk_command_pool compute_cmd_pool;
  1472. vk_command_pool transfer_cmd_pool;
  1473. // number of additional consecutive nodes that are being fused with the
  1474. // node currently being processed
  1475. int num_additional_fused_ops {};
  1476. // Bitmask of which fused ops need to write an intermediate value to memory.
  1477. // Bit 'i' means nodes[start_of_fusion + i] writes to memory.
  1478. // If there's no fusion, bit 0 is still set.
  1479. int fused_ops_write_mask {};
  1480. // for GGML_VK_PERF_LOGGER
  1481. std::unique_ptr<vk_perf_logger> perf_logger;
  1482. vk::QueryPool query_pool;
  1483. std::vector<const char *> query_fusion_names;
  1484. std::vector<ggml_tensor *> query_nodes;
  1485. int32_t num_queries {};
  1486. int32_t query_idx {};
  1487. };
  1488. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  1489. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  1490. if (tensor->view_src) {
  1491. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  1492. }
  1493. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  1494. }
  1495. static uint32_t get_misalign_bytes(const ggml_backend_vk_context * ctx, const ggml_tensor * t)
  1496. {
  1497. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  1498. }
  1499. template <typename T> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, T &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  1500. GGML_UNUSED(p);
  1501. GGML_UNUSED(src0);
  1502. GGML_UNUSED(src1);
  1503. GGML_UNUSED(src2);
  1504. GGML_UNUSED(src3);
  1505. GGML_UNUSED(dst);
  1506. static_assert(!std::is_const<T>::value, "unexpected type");
  1507. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  1508. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  1509. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  1510. GGML_ASSERT(!src3 || get_misalign_bytes(ctx, src3) == 0);
  1511. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  1512. }
  1513. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_mat_vec_p021_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  1514. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1515. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1516. p.b_offset = b_offset;
  1517. p.d_offset = d_offset;
  1518. GGML_UNUSED(src0);
  1519. GGML_UNUSED(src2);
  1520. GGML_UNUSED(src3);
  1521. }
  1522. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_mat_vec_nc_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  1523. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1524. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1525. p.b_offset = b_offset;
  1526. p.d_offset = d_offset;
  1527. GGML_UNUSED(src0);
  1528. GGML_UNUSED(src2);
  1529. GGML_UNUSED(src3);
  1530. }
  1531. struct ggml_backend_vk_buffer_context {
  1532. vk_device_ref device;
  1533. vk_buffer dev_buffer;
  1534. std::string name;
  1535. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  1536. device(device),
  1537. dev_buffer(dev_buffer),
  1538. name(name) {
  1539. }
  1540. ~ggml_backend_vk_buffer_context() {
  1541. ggml_vk_destroy_buffer(dev_buffer);
  1542. }
  1543. };
  1544. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1545. static std::mutex log_mutex;
  1546. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  1547. std::lock_guard<std::mutex> guard(log_mutex);
  1548. vk_buffer buf = buf_ref.lock();
  1549. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1550. const std::string type = device ? "device" : "host";
  1551. allocations[buf->buffer] = size;
  1552. total_device += device ? size : 0;
  1553. total_host += device ? 0 : size;
  1554. VK_LOG_MEMORY(buf->device->name << ": +" << format_size(size) << " " << type << " at " << buf->buffer << ". Total device: " << format_size(total_device) << ", total host: " << format_size(total_host));
  1555. }
  1556. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  1557. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  1558. return;
  1559. }
  1560. std::lock_guard<std::mutex> guard(log_mutex);
  1561. vk_buffer buf = buf_ref.lock();
  1562. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1563. std::string type = device ? "device" : "host";
  1564. auto it = allocations.find(buf->buffer);
  1565. total_device -= device ? it->second : 0;
  1566. total_host -= device ? 0 : it->second;
  1567. if (it != allocations.end()) {
  1568. VK_LOG_MEMORY(buf->device->name << ": -" << format_size(it->second) << " " << type << " at " << buf->buffer << ". Total device: " << format_size(total_device) << ", total host: " << format_size(total_host));
  1569. allocations.erase(it);
  1570. } else {
  1571. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  1572. }
  1573. }
  1574. #endif // GGML_VULKAN_MEMORY_DEBUG
  1575. struct vk_instance_t {
  1576. vk::Instance instance;
  1577. bool debug_utils_support = false; // VK_EXT_debug_utils enabled
  1578. PFN_vkSetDebugUtilsObjectNameEXT pfn_vkSetDebugUtilsObjectNameEXT = {};
  1579. PFN_vkQueueBeginDebugUtilsLabelEXT pfn_vkQueueBeginDebugUtilsLabelEXT = {};
  1580. PFN_vkQueueEndDebugUtilsLabelEXT pfn_vkQueueEndDebugUtilsLabelEXT = {};
  1581. PFN_vkCmdBeginDebugUtilsLabelEXT pfn_vkCmdBeginDebugUtilsLabelEXT = {};
  1582. PFN_vkCmdEndDebugUtilsLabelEXT pfn_vkCmdEndDebugUtilsLabelEXT = {};
  1583. PFN_vkCmdInsertDebugUtilsLabelEXT pfn_vkCmdInsertDebugUtilsLabelEXT = {};
  1584. std::vector<size_t> device_indices;
  1585. std::vector<bool> device_supports_membudget;
  1586. vk_device devices[GGML_VK_MAX_DEVICES];
  1587. };
  1588. static bool vk_instance_initialized = false;
  1589. static vk_instance_t vk_instance;
  1590. #ifdef GGML_VULKAN_CHECK_RESULTS
  1591. static size_t vk_skip_checks;
  1592. static size_t vk_output_tensor;
  1593. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  1594. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1595. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1596. #endif
  1597. typedef void (*ggml_vk_func_t)(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst);
  1598. static void ggml_backend_vk_free(ggml_backend_t backend);
  1599. static VkDeviceSize ggml_vk_get_max_buffer_range(const ggml_backend_vk_context * ctx, const vk_buffer &buf, const VkDeviceSize offset) {
  1600. const VkDeviceSize range = std::min(VkDeviceSize{buf->size - offset},
  1601. VkDeviceSize{ctx->device->properties.limits.maxStorageBufferRange});
  1602. return range;
  1603. }
  1604. // Wait for ctx->fence to be signaled.
  1605. static void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) {
  1606. // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep
  1607. // during this wait.
  1608. if (ctx->almost_ready_fence_pending) {
  1609. VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence");
  1610. ctx->device->device.resetFences({ ctx->almost_ready_fence });
  1611. ctx->almost_ready_fence_pending = false;
  1612. }
  1613. // Spin (w/pause) waiting for the graph to finish executing.
  1614. vk::Result result;
  1615. while ((result = ctx->device->device.getFenceStatus(ctx->fence)) != vk::Result::eSuccess) {
  1616. if (result != vk::Result::eNotReady) {
  1617. fprintf(stderr, "ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__);
  1618. exit(1);
  1619. }
  1620. for (uint32_t i = 0; i < 100; ++i) {
  1621. YIELD();
  1622. YIELD();
  1623. YIELD();
  1624. YIELD();
  1625. YIELD();
  1626. YIELD();
  1627. YIELD();
  1628. YIELD();
  1629. YIELD();
  1630. YIELD();
  1631. }
  1632. }
  1633. ctx->device->device.resetFences({ ctx->fence });
  1634. }
  1635. // variables to track number of compiles in progress
  1636. static uint32_t compile_count = 0;
  1637. static std::mutex compile_count_mutex;
  1638. static std::condition_variable compile_count_cond;
  1639. static void ggml_vk_create_pipeline_func(vk_device& device, vk_pipeline& pipeline, size_t spv_size, const void* spv_data, const std::string entrypoint,
  1640. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  1641. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  1642. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  1643. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  1644. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  1645. GGML_ASSERT(parameter_count > 0);
  1646. GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT);
  1647. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  1648. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  1649. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  1650. vk::PushConstantRange pcr(
  1651. vk::ShaderStageFlagBits::eCompute,
  1652. 0,
  1653. pipeline->push_constant_size
  1654. );
  1655. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr);
  1656. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  1657. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  1658. for (size_t i = 0; i < specialization_constants.size(); i++) {
  1659. specialization_entries[i].constantID = i;
  1660. specialization_entries[i].offset = i * sizeof(uint32_t);
  1661. specialization_entries[i].size = sizeof(uint32_t);
  1662. }
  1663. vk::SpecializationInfo specialization_info(
  1664. specialization_entries.size(),
  1665. specialization_entries.data(),
  1666. specialization_constants.size() * sizeof(uint32_t),
  1667. specialization_constants.data()
  1668. );
  1669. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  1670. if (device->subgroup_require_full_support && require_full_subgroups) {
  1671. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  1672. }
  1673. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  1674. pipeline_shader_stage_create_flags,
  1675. vk::ShaderStageFlagBits::eCompute,
  1676. pipeline->shader_module,
  1677. entrypoint.c_str(),
  1678. &specialization_info);
  1679. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  1680. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  1681. if (device->subgroup_size_control && required_subgroup_size > 0) {
  1682. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  1683. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  1684. }
  1685. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  1686. device->pipeline_executable_properties_support ?
  1687. vk::PipelineCreateFlagBits::eCaptureStatisticsKHR :
  1688. vk::PipelineCreateFlags{},
  1689. pipeline_shader_create_info,
  1690. pipeline->layout);
  1691. vk::PipelineRobustnessCreateInfoEXT rci;
  1692. if (device->pipeline_robustness && disable_robustness) {
  1693. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1694. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1695. compute_pipeline_create_info.setPNext(&rci);
  1696. }
  1697. try {
  1698. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  1699. } catch (const vk::SystemError& e) {
  1700. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  1701. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1702. throw e;
  1703. }
  1704. pipeline->compiled = true;
  1705. if (vk_instance.debug_utils_support) {
  1706. vk::DebugUtilsObjectNameInfoEXT duoni;
  1707. duoni.objectType = vk::ObjectType::ePipeline;
  1708. duoni.pObjectName = pipeline->name.c_str();
  1709. duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast<VkPipeline>(pipeline->pipeline));
  1710. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast<VkDebugUtilsObjectNameInfoEXT &>(duoni));
  1711. }
  1712. if (device->pipeline_executable_properties_support) {
  1713. vk::PipelineExecutableInfoKHR executableInfo;
  1714. executableInfo.pipeline = pipeline->pipeline;
  1715. auto statistics = device->device.getPipelineExecutableStatisticsKHR(executableInfo);
  1716. for (auto & s : statistics) {
  1717. // "Register Count" is reported by NVIDIA drivers.
  1718. if (strcmp(s.name, "Register Count") == 0) {
  1719. VK_LOG_DEBUG(pipeline->name << " " << s.name << ": " << s.value.u64 << " registers");
  1720. pipeline->register_count = (uint32_t)s.value.u64;
  1721. }
  1722. }
  1723. }
  1724. device->all_pipelines.push_back(pipeline);
  1725. {
  1726. std::lock_guard<std::mutex> guard(compile_count_mutex);
  1727. assert(compile_count > 0);
  1728. compile_count--;
  1729. }
  1730. compile_count_cond.notify_all();
  1731. }
  1732. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  1733. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  1734. device.destroyPipelineLayout(pipeline->layout);
  1735. device.destroyShaderModule(pipeline->shader_module);
  1736. device.destroyPipeline(pipeline->pipeline);
  1737. }
  1738. static void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) {
  1739. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  1740. ctx->pipeline_descriptor_set_requirements += n;
  1741. if (!pipeline->compiled) {
  1742. pipeline->needed = true;
  1743. ggml_vk_load_shaders(ctx->device);
  1744. }
  1745. ggml_pipeline_allocate_descriptor_sets(ctx);
  1746. }
  1747. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
  1748. if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) {
  1749. // Enough descriptors are available
  1750. return;
  1751. }
  1752. vk_device& device = ctx->device;
  1753. // Grow by 50% to avoid frequent allocations
  1754. uint32_t needed = std::max(3 * ctx->descriptor_sets.size() / 2, size_t{ctx->pipeline_descriptor_set_requirements});
  1755. uint32_t to_alloc = needed - ctx->descriptor_sets.size();
  1756. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1757. uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1758. while (to_alloc > 0) {
  1759. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  1760. to_alloc -= alloc_count;
  1761. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1762. if (pool_idx >= ctx->descriptor_pools.size()) {
  1763. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  1764. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  1765. ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  1766. }
  1767. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  1768. for (uint32_t i = 0; i < alloc_count; i++) {
  1769. layouts[i] = device->dsl;
  1770. }
  1771. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
  1772. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  1773. ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
  1774. pool_idx++;
  1775. }
  1776. }
  1777. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) {
  1778. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  1779. if (p.cmd_buffers.size() > p.cmd_buffer_idx) {
  1780. // Reuse command buffer
  1781. return p.cmd_buffers[p.cmd_buffer_idx++];
  1782. }
  1783. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  1784. p.pool,
  1785. vk::CommandBufferLevel::ePrimary,
  1786. 1);
  1787. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  1788. auto buf = cmd_buffers.front();
  1789. p.cmd_buffers.push_back(buf);
  1790. p.cmd_buffer_idx++;
  1791. return buf;
  1792. }
  1793. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  1794. if (ctx->seqs.empty()) {
  1795. if (fence) {
  1796. std::lock_guard<std::mutex> guard(queue_mutex);
  1797. ctx->p->q->queue.submit({}, fence);
  1798. }
  1799. return;
  1800. }
  1801. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  1802. std::vector<std::vector<uint64_t>> tl_wait_vals;
  1803. std::vector<std::vector<uint64_t>> tl_signal_vals;
  1804. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  1805. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  1806. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  1807. std::vector<vk::SubmitInfo> submit_infos;
  1808. int idx = -1;
  1809. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  1810. size_t reserve = 0;
  1811. for (const auto& sequence : ctx->seqs) {
  1812. reserve += sequence.size();
  1813. }
  1814. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  1815. tl_wait_semaphores.reserve(reserve);
  1816. tl_wait_vals.reserve(reserve);
  1817. tl_signal_semaphores.reserve(reserve);
  1818. tl_signal_vals.reserve(reserve);
  1819. tl_submit_infos.reserve(reserve);
  1820. submit_infos.reserve(reserve);
  1821. stage_flags.reserve(reserve);
  1822. for (const auto& sequence : ctx->seqs) {
  1823. for (const auto& submission : sequence) {
  1824. stage_flags.push_back({});
  1825. idx++;
  1826. tl_wait_vals.push_back({});
  1827. tl_wait_semaphores.push_back({});
  1828. tl_signal_vals.push_back({});
  1829. tl_signal_semaphores.push_back({});
  1830. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  1831. stage_flags[idx].push_back(ctx->p->q->stage_flags);
  1832. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  1833. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  1834. }
  1835. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  1836. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  1837. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  1838. }
  1839. tl_submit_infos.push_back({
  1840. (uint32_t) submission.wait_semaphores.size(),
  1841. tl_wait_vals[idx].data(),
  1842. (uint32_t) submission.signal_semaphores.size(),
  1843. tl_signal_vals[idx].data(),
  1844. });
  1845. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  1846. tl_submit_infos[idx].pNext = nullptr;
  1847. vk::SubmitInfo si{
  1848. (uint32_t) submission.wait_semaphores.size(),
  1849. tl_wait_semaphores[idx].data(),
  1850. stage_flags[idx].data(),
  1851. 1,
  1852. &submission.buffer,
  1853. (uint32_t) submission.signal_semaphores.size(),
  1854. tl_signal_semaphores[idx].data(),
  1855. };
  1856. si.setPNext(&tl_submit_infos[idx]);
  1857. submit_infos.push_back(si);
  1858. }
  1859. }
  1860. std::lock_guard<std::mutex> guard(queue_mutex);
  1861. ctx->p->q->queue.submit(submit_infos, fence);
  1862. ctx->seqs.clear();
  1863. }
  1864. static uint32_t ggml_vk_find_queue_family_index(std::vector<vk::QueueFamilyProperties>& queue_family_props, const vk::QueueFlags& required, const vk::QueueFlags& avoid, int32_t compute_index, uint32_t min_num_queues) {
  1865. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  1866. const uint32_t qfsize = queue_family_props.size();
  1867. // Try with avoid preferences first
  1868. for (uint32_t i = 0; i < qfsize; i++) {
  1869. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required && !(queue_family_props[i].queueFlags & avoid)) {
  1870. return i;
  1871. }
  1872. }
  1873. // Fall back to only required
  1874. for (size_t i = 0; i < qfsize; i++) {
  1875. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  1876. return i;
  1877. }
  1878. }
  1879. // Fall back to reusing compute queue
  1880. for (size_t i = 0; i < qfsize; i++) {
  1881. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  1882. return i;
  1883. }
  1884. }
  1885. // Fall back to ignoring min_num_queries
  1886. for (size_t i = 0; i < qfsize; i++) {
  1887. if (queue_family_props[i].queueFlags & required) {
  1888. return i;
  1889. }
  1890. }
  1891. // All commands that are allowed on a queue that supports transfer operations are also allowed on a queue that supports either graphics or compute operations.
  1892. // Thus, if the capabilities of a queue family include VK_QUEUE_GRAPHICS_BIT or VK_QUEUE_COMPUTE_BIT, then reporting the VK_QUEUE_TRANSFER_BIT capability separately for that queue family is optional.
  1893. if (compute_index >= 0) {
  1894. return compute_index;
  1895. }
  1896. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  1897. for(auto &q_family : queue_family_props) {
  1898. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  1899. }
  1900. abort();
  1901. }
  1902. static void ggml_vk_create_queue(vk_device& device, vk_queue& q, uint32_t queue_family_index, uint32_t queue_index, vk::PipelineStageFlags&& stage_flags, bool transfer_only) {
  1903. VK_LOG_DEBUG("ggml_vk_create_queue()");
  1904. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1905. q.queue_family_index = queue_family_index;
  1906. q.transfer_only = transfer_only;
  1907. q.cmd_pool.init(device, &q);
  1908. q.queue = device->device.getQueue(queue_family_index, queue_index);
  1909. q.stage_flags = stage_flags;
  1910. }
  1911. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) {
  1912. vk_context result = std::make_shared<vk_context_struct>();
  1913. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  1914. ctx->gc.contexts.emplace_back(result);
  1915. result->p = &p;
  1916. return result;
  1917. }
  1918. static vk_context ggml_vk_create_temporary_context(vk_command_pool& p) {
  1919. vk_context result = std::make_shared<vk_context_struct>();
  1920. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  1921. result->p = &p;
  1922. return result;
  1923. }
  1924. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  1925. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1926. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  1927. vk::SemaphoreCreateInfo ci{};
  1928. ci.setPNext(&tci);
  1929. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1930. ctx->gc.semaphores.push_back({ semaphore, 0 });
  1931. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  1932. }
  1933. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  1934. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1935. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  1936. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  1937. vk::SemaphoreCreateInfo ci{};
  1938. ci.setPNext(&tci);
  1939. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1940. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  1941. }
  1942. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  1943. }
  1944. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  1945. if (ctx->event_idx >= ctx->gc.events.size()) {
  1946. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  1947. }
  1948. return ctx->gc.events[ctx->event_idx++];
  1949. }
  1950. static void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) {
  1951. VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()");
  1952. // Requires command buffers to be done
  1953. device->device.resetCommandPool(p.pool);
  1954. p.cmd_buffer_idx = 0;
  1955. }
  1956. static void ggml_vk_queue_command_pools_cleanup(vk_device& device) {
  1957. VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()");
  1958. // Arbitrary frequency to cleanup/reuse command buffers
  1959. static constexpr uint32_t cleanup_frequency = 10;
  1960. if (device->compute_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1961. ggml_vk_command_pool_cleanup(device, device->compute_queue.cmd_pool);
  1962. }
  1963. if (device->transfer_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1964. ggml_vk_command_pool_cleanup(device, device->transfer_queue.cmd_pool);
  1965. }
  1966. }
  1967. static std::vector<uint32_t> ggml_vk_find_memory_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  1968. std::vector<uint32_t> indices;
  1969. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  1970. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  1971. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  1972. (flags & memory_type.propertyFlags) == flags &&
  1973. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  1974. indices.push_back(i);
  1975. }
  1976. }
  1977. return indices;
  1978. }
  1979. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, const std::initializer_list<vk::MemoryPropertyFlags> & req_flags_list) {
  1980. VK_LOG_DEBUG("ggml_vk_create_buffer(" << device->name << ", " << size << ", " << to_string(req_flags_list.begin()[0]) << ", " << to_string(req_flags_list.begin()[req_flags_list.size()-1]) << ")");
  1981. if (size > device->max_buffer_size) {
  1982. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device buffer size limit");
  1983. }
  1984. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  1985. if (size == 0) {
  1986. buf->size = 0;
  1987. return buf;
  1988. }
  1989. vk::BufferUsageFlags usage_flags = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst;
  1990. vk::MemoryAllocateFlags mem_flags {};
  1991. if (device->buffer_device_address) {
  1992. usage_flags |= vk::BufferUsageFlagBits::eShaderDeviceAddress;
  1993. mem_flags |= vk::MemoryAllocateFlagBits::eDeviceAddress;
  1994. }
  1995. vk::BufferCreateInfo buffer_create_info{
  1996. vk::BufferCreateFlags(),
  1997. size,
  1998. usage_flags,
  1999. vk::SharingMode::eExclusive,
  2000. 0,
  2001. nullptr,
  2002. };
  2003. buf->buffer = device->device.createBuffer(buffer_create_info);
  2004. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  2005. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  2006. const vk::MemoryPriorityAllocateInfoEXT mem_priority_info { 1.0f };
  2007. vk::MemoryAllocateFlagsInfo mem_flags_info { mem_flags };
  2008. if (device->memory_priority) {
  2009. mem_flags_info.setPNext(&mem_priority_info);
  2010. }
  2011. for (auto it = req_flags_list.begin(); it != req_flags_list.end(); it++) {
  2012. const auto & req_flags = *it;
  2013. const std::vector<uint32_t> memory_type_indices = ggml_vk_find_memory_properties(&mem_props, &mem_req, req_flags);
  2014. if (memory_type_indices.empty()) {
  2015. continue;
  2016. }
  2017. buf->memory_property_flags = req_flags;
  2018. bool done = false;
  2019. for (auto mtype_it = memory_type_indices.begin(); mtype_it != memory_type_indices.end(); mtype_it++) {
  2020. try {
  2021. buf->device_memory = device->device.allocateMemory({ mem_req.size, *mtype_it, &mem_flags_info });
  2022. done = true;
  2023. break;
  2024. } catch (const vk::SystemError& e) {
  2025. // loop and retry
  2026. // during last attempt throw the exception
  2027. if (it + 1 == req_flags_list.end() && mtype_it + 1 == memory_type_indices.end()) {
  2028. device->device.destroyBuffer(buf->buffer);
  2029. throw e;
  2030. }
  2031. }
  2032. }
  2033. if (done) {
  2034. break;
  2035. }
  2036. }
  2037. if (!buf->device_memory) {
  2038. device->device.destroyBuffer(buf->buffer);
  2039. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  2040. }
  2041. buf->ptr = nullptr;
  2042. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2043. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  2044. }
  2045. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  2046. buf->device = device;
  2047. buf->size = size;
  2048. if (device->buffer_device_address) {
  2049. const vk::BufferDeviceAddressInfo addressInfo(buf->buffer);
  2050. buf->bda_addr = device->device.getBufferAddress(addressInfo);
  2051. }
  2052. #ifdef GGML_VULKAN_MEMORY_DEBUG
  2053. device->memory_logger->log_allocation(buf, size);
  2054. #endif
  2055. return buf;
  2056. }
  2057. static vk_buffer ggml_vk_create_buffer_check(vk_device& device, size_t size, vk::MemoryPropertyFlags req_flags, vk::MemoryPropertyFlags fallback_flags = vk::MemoryPropertyFlags(0)) {
  2058. try {
  2059. return ggml_vk_create_buffer(device, size, {req_flags, fallback_flags});
  2060. } catch (const vk::SystemError& e) {
  2061. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  2062. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  2063. throw e;
  2064. }
  2065. }
  2066. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  2067. vk_buffer buf;
  2068. try {
  2069. if (device->prefer_host_memory) {
  2070. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2071. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2072. } else if (device->uma) {
  2073. // Fall back to host memory type
  2074. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2075. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2076. } else if (device->disable_host_visible_vidmem) {
  2077. if (device->allow_sysmem_fallback) {
  2078. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2079. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2080. } else {
  2081. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  2082. }
  2083. } else {
  2084. // use rebar if available, otherwise fallback to device only visible memory
  2085. if (device->allow_sysmem_fallback) {
  2086. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2087. vk::MemoryPropertyFlagBits::eDeviceLocal,
  2088. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2089. } else {
  2090. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2091. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2092. }
  2093. }
  2094. } catch (const vk::SystemError& e) {
  2095. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  2096. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  2097. throw e;
  2098. }
  2099. return buf;
  2100. }
  2101. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  2102. if (buf == nullptr) {
  2103. return;
  2104. }
  2105. #ifdef GGML_VULKAN_MEMORY_DEBUG
  2106. if (buf->device != nullptr) {
  2107. buf->device->memory_logger->log_deallocation(buf);
  2108. }
  2109. #endif
  2110. buf.reset();
  2111. }
  2112. static vk_subbuffer ggml_vk_subbuffer(const ggml_backend_vk_context* ctx, const vk_buffer& buf, size_t offset = 0) {
  2113. return { buf, offset, ggml_vk_get_max_buffer_range(ctx, buf, offset) };
  2114. }
  2115. static void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) {
  2116. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  2117. const bool transfer_queue = subctx->p->q->transfer_only;
  2118. if (ctx) {
  2119. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  2120. }
  2121. subctx->s->buffer.pipelineBarrier(
  2122. subctx->p->q->stage_flags,
  2123. subctx->p->q->stage_flags,
  2124. {},
  2125. { {
  2126. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  2127. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  2128. } },
  2129. {},
  2130. {}
  2131. );
  2132. }
  2133. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  2134. VK_LOG_DEBUG("ggml_vk_wait_events()");
  2135. if (events.empty()) {
  2136. return;
  2137. }
  2138. ctx->s->buffer.waitEvents(
  2139. events,
  2140. ctx->p->q->stage_flags,
  2141. ctx->p->q->stage_flags,
  2142. {},
  2143. {},
  2144. {}
  2145. );
  2146. }
  2147. // number of rows/cols for flash attention shader
  2148. static constexpr uint32_t flash_attention_num_small_rows = 32;
  2149. static constexpr uint32_t scalar_flash_attention_num_small_rows = 1;
  2150. static uint32_t get_fa_scalar_num_large_rows(uint32_t hsk, uint32_t hsv) {
  2151. if (hsv >= 192) {
  2152. return 2;
  2153. } else if ((hsv | hsk) & 8) {
  2154. return 4;
  2155. } else {
  2156. return 8;
  2157. }
  2158. }
  2159. // The FA coopmat1 shader assumes 16x16x16 matrix multiply support.
  2160. // 128 threads split into four subgroups, each subgroup does 1/4
  2161. // of the Bc dimension.
  2162. static constexpr uint32_t coopmat1_flash_attention_num_large_rows = 16;
  2163. static constexpr uint32_t scalar_flash_attention_Bc = 64;
  2164. static constexpr uint32_t scalar_flash_attention_workgroup_size = 128;
  2165. static uint32_t get_fa_num_small_rows(FaCodePath path) {
  2166. if (path == FA_COOPMAT2) {
  2167. return flash_attention_num_small_rows;
  2168. } else {
  2169. return scalar_flash_attention_num_small_rows;
  2170. }
  2171. }
  2172. static std::array<uint32_t, 2> fa_rows_cols(FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows) {
  2173. GGML_UNUSED(clamp);
  2174. GGML_UNUSED(hsv);
  2175. if (path == FA_SCALAR) {
  2176. if (small_rows) {
  2177. return {scalar_flash_attention_num_small_rows, 64};
  2178. } else {
  2179. if ((hsv | hsk) & 8) {
  2180. // HSV/HSK not being a multiple of 16 makes D_split smaller, which makes cols_per_iter
  2181. // larger, and Bc needs to be >= cols_per_thread. 64 is large enough, 32 is not.
  2182. return {get_fa_scalar_num_large_rows(hsk, hsv), 64};
  2183. } else {
  2184. return {get_fa_scalar_num_large_rows(hsk, hsv), 32};
  2185. }
  2186. }
  2187. }
  2188. if (path == FA_COOPMAT1) {
  2189. if (small_rows) {
  2190. return {scalar_flash_attention_num_small_rows, scalar_flash_attention_Bc};
  2191. } else {
  2192. return {coopmat1_flash_attention_num_large_rows, scalar_flash_attention_Bc};
  2193. }
  2194. }
  2195. // small rows, large cols
  2196. if (small_rows) {
  2197. return {get_fa_num_small_rows(FA_COOPMAT2), 32};
  2198. }
  2199. // small cols to reduce register count
  2200. if (ggml_is_quantized(type) || hsk >= 256 || hsv >= 256) {
  2201. if (hsk >= 512 || hsv >= 512) {
  2202. return {32, 32};
  2203. } else {
  2204. return {64, 32};
  2205. }
  2206. }
  2207. return {64, 64};
  2208. }
  2209. static uint32_t fa_align(FaCodePath path, uint32_t hsk, uint32_t hsv, ggml_type type, bool small_rows) {
  2210. return fa_rows_cols(path, hsk, hsv, 0, type, small_rows)[1];
  2211. }
  2212. static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector<uint32_t>& warptile, bool mul_mat_id, ggml_type src0_type) {
  2213. uint32_t lut_size = 0;
  2214. switch (src0_type) {
  2215. case GGML_TYPE_IQ1_S:
  2216. case GGML_TYPE_IQ1_M:
  2217. lut_size = 2*2048;
  2218. break;
  2219. case GGML_TYPE_IQ2_XXS:
  2220. lut_size = 8*256;
  2221. break;
  2222. case GGML_TYPE_IQ2_XS:
  2223. lut_size = 8*512;
  2224. break;
  2225. case GGML_TYPE_IQ2_S:
  2226. lut_size = 8*1024;
  2227. break;
  2228. case GGML_TYPE_IQ3_XXS:
  2229. lut_size = 4*256;
  2230. break;
  2231. case GGML_TYPE_IQ3_S:
  2232. lut_size = 4*512;
  2233. break;
  2234. case GGML_TYPE_IQ4_NL:
  2235. case GGML_TYPE_IQ4_XS:
  2236. case GGML_TYPE_MXFP4:
  2237. lut_size = 4*16;
  2238. break;
  2239. default:
  2240. break;
  2241. }
  2242. // Needs to be kept up to date on shader changes
  2243. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  2244. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  2245. const uint32_t warps = warptile[0] / warptile[10];
  2246. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  2247. const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0;
  2248. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  2249. const uint32_t ballots_sh = mul_mat_id ? (warps * 4 * sizeof(uint32_t)) : 0;
  2250. const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size + ballots_sh;
  2251. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  2252. VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), "
  2253. "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported);
  2254. return supported;
  2255. }
  2256. struct GpuPipelineConfig {
  2257. // GPU architecture identifier.
  2258. // Example: vk_device_architecture::AMD_GCN
  2259. vk_device_architecture arch;
  2260. // Mapping of pipeline names to their specific subgroup sizes.
  2261. // Example: {"soft_max_f32", 64}
  2262. std::unordered_map<std::string, uint32_t> pipelines;
  2263. // Default subgroup size for this GPU.
  2264. // Defaults to 0 if not explicitly provided.
  2265. uint32_t default_subgroup_size = 0;
  2266. };
  2267. // Pipeline configuration for RDNA1 GPUs.
  2268. static const std::unordered_map<std::string, uint32_t> rdna1_pipelines = {
  2269. {"soft_max", 64}, {"im2col", 64},
  2270. {"argmax", 64}, {"mul_mat_vec", 64},
  2271. {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32}
  2272. };
  2273. // Pipeline configuration for RDNA2 GPUs.
  2274. static const std::unordered_map<std::string, uint32_t> rdna2_pipelines = {
  2275. {"soft_max", 64}, {"im2col", 64},
  2276. };
  2277. static constexpr uint32_t RDNA_DEFAULT_SUBGROUP_SIZE = 32;
  2278. // Define configurations for different GPUs.
  2279. static std::vector<GpuPipelineConfig> gpu_pipeline_configs = {
  2280. {
  2281. vk_device_architecture::AMD_RDNA1,
  2282. {
  2283. rdna1_pipelines,
  2284. },
  2285. RDNA_DEFAULT_SUBGROUP_SIZE
  2286. },
  2287. {
  2288. vk_device_architecture::AMD_RDNA2,
  2289. {
  2290. rdna2_pipelines,
  2291. },
  2292. RDNA_DEFAULT_SUBGROUP_SIZE
  2293. },
  2294. };
  2295. static uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) {
  2296. for (const auto &config : gpu_pipeline_configs) {
  2297. if (config.arch == arch) {
  2298. auto pipIt = config.pipelines.find(pipeline_name);
  2299. if (pipIt != config.pipelines.end()) {
  2300. return pipIt->second;
  2301. }
  2302. std::vector<std::pair<std::string, uint32_t>> sorted_pipelines(config.pipelines.begin(), config.pipelines.end());
  2303. std::sort(sorted_pipelines.begin(), sorted_pipelines.end(),
  2304. [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
  2305. for (const auto &entry : sorted_pipelines) {
  2306. if (pipeline_name.find(entry.first) != std::string::npos) {
  2307. return entry.second;
  2308. }
  2309. }
  2310. return config.default_subgroup_size;
  2311. }
  2312. }
  2313. return 0; // If no matching configuration is found
  2314. }
  2315. static void ggml_vk_load_shaders(vk_device& device) {
  2316. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  2317. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  2318. // some shaders have a minimum subgroup size
  2319. const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u);
  2320. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  2321. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  2322. const uint32_t mul_mat_subgroup_size = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  2323. const uint32_t mul_mat_subgroup_size_8 = std::max(mul_mat_subgroup_size, 8u);
  2324. const uint32_t mul_mat_subgroup_size_16 = std::max(mul_mat_subgroup_size, 16u);
  2325. const uint32_t mul_mat_subgroup_size_32 = std::max(mul_mat_subgroup_size, 32u);
  2326. const bool subgroup_min_size_16 = (!device->subgroup_size_control && device->subgroup_size >= 16) ||
  2327. (device->subgroup_size_control && device->subgroup_max_size >= 16);
  2328. // mulmat
  2329. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  2330. l_warptile_id, m_warptile_id, s_warptile_id,
  2331. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  2332. l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int,
  2333. l_warptile_mmq_int_k, m_warptile_mmq_int_k, s_warptile_mmq_int_k,
  2334. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  2335. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid,
  2336. l_warptile_mmqid_int, m_warptile_mmqid_int, s_warptile_mmqid_int,
  2337. l_warptile_mmqid_int_k, m_warptile_mmqid_int_k, s_warptile_mmqid_int_k;
  2338. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  2339. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  2340. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  2341. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  2342. uint32_t l_align, m_align, s_align;
  2343. if (device->coopmat2) {
  2344. // spec constants and tile sizes for non-quant matmul/matmul_id
  2345. l_warptile = { 256, 128, 256, 64, 1 };
  2346. m_warptile = { 256, 128, 128, 64, 0 };
  2347. s_warptile = { 128, 64, 64, 64, 0 };
  2348. l_wg_denoms = {128, 256, 1 };
  2349. m_wg_denoms = {128, 128, 1 };
  2350. s_wg_denoms = { 64, 64, 1 };
  2351. // spec constants and tile sizes for quant matmul (non-Qi_K)
  2352. l_warptile_mmq = { 256, 128, 256, 64, 1 };
  2353. m_warptile_mmq = { 256, 128, 128, 64, 1 };
  2354. s_warptile_mmq = { 256, 32, 64, 128, 0 };
  2355. l_mmq_wg_denoms = { 128, 256, 1 };
  2356. m_mmq_wg_denoms = { 128, 128, 1 };
  2357. s_mmq_wg_denoms = { 32, 64, 1 };
  2358. // spec constants and tile sizes for quant matmul (Qi_K)
  2359. l_warptile_mmq_k = { 256, 128, 256, 64, 1 };
  2360. m_warptile_mmq_k = { 256, 128, 128, 64, 1 };
  2361. s_warptile_mmq_k = { 256, 32, 64, 128, 0 };
  2362. l_mmq_wg_denoms_k = { 128, 256, 1 };
  2363. m_mmq_wg_denoms_k = { 128, 128, 1 };
  2364. s_mmq_wg_denoms_k = { 32, 64, 1 };
  2365. // spec constants and tile sizes for quant matmul_id
  2366. l_warptile_mmqid = { 256, 128, 128, 16, 1, device->subgroup_size };
  2367. m_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2368. s_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2369. l_mmqid_wg_denoms = { 128, 128, 1 };
  2370. m_mmqid_wg_denoms = { 128, 64, 1 };
  2371. s_mmqid_wg_denoms = { 128, 64, 1 };
  2372. l_align = 128;
  2373. m_align = 64;
  2374. s_align = 32;
  2375. } else {
  2376. // Matrix cores require different warp group sizes
  2377. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  2378. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  2379. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  2380. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  2381. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  2382. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  2383. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  2384. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  2385. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  2386. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2387. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2388. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2389. l_warptile_mmq = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2390. m_warptile_mmq = { 128, 64, 64, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2391. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2392. // Integer MMQ has a smaller shared memory profile, but heavier register use
  2393. l_warptile_mmq_int = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2394. m_warptile_mmq_int = { 128, 64, 64, 32, subgroup_size_8, 32, 2, 2, 2, 1, subgroup_size_8 };
  2395. s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, subgroup_size_8 };
  2396. // K-quants use even more registers, mitigate by setting WMITER to 1
  2397. l_warptile_mmq_int_k = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 1, 4, 4, 1, subgroup_size_8 };
  2398. m_warptile_mmq_int_k = { 128, 64, 64, 32, subgroup_size_8, 32, 1, 2, 2, 1, subgroup_size_8 };
  2399. s_warptile_mmq_int_k = { subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, subgroup_size_8 };
  2400. l_warptile_id = { 128, 128, 128, 16, mul_mat_subgroup_size_16 * 2, 64, 2, tm_l, tn_l, tk_l, mul_mat_subgroup_size_16 };
  2401. m_warptile_id = { 128, 64, 64, 16, mul_mat_subgroup_size_16, 32, 2, tm_m, tn_m, tk_m, mul_mat_subgroup_size_16 };
  2402. s_warptile_id = { mul_mat_subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_16 };
  2403. l_warptile_mmqid = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, mul_mat_subgroup_size_8 };
  2404. m_warptile_mmqid = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, mul_mat_subgroup_size_8 };
  2405. s_warptile_mmqid = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_8 };
  2406. l_warptile_mmqid_int = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, 4, 4, 1, mul_mat_subgroup_size_8 };
  2407. m_warptile_mmqid_int = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, 2, 2, 1, mul_mat_subgroup_size_8 };
  2408. s_warptile_mmqid_int = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, mul_mat_subgroup_size_8 };
  2409. l_warptile_mmqid_int_k = { 128, 128, 128, 32, mul_mat_subgroup_size_16 * 2, 64, 1, 4, 4, 1, mul_mat_subgroup_size_16 };
  2410. m_warptile_mmqid_int_k = { 128, 64, 64, 32, mul_mat_subgroup_size_16, 32, 1, 2, 2, 1, mul_mat_subgroup_size_16 };
  2411. s_warptile_mmqid_int_k = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, mul_mat_subgroup_size_16 };
  2412. // chip specific tuning
  2413. if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) {
  2414. m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2415. m_warptile_mmqid = m_warptile_mmqid_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2416. }
  2417. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  2418. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  2419. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  2420. l_align = 128;
  2421. m_align = 64;
  2422. s_align = 32;
  2423. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  2424. ggml_type t = (ggml_type)i;
  2425. // Disable medium and large matrix multiplication if not enough shared memory is available
  2426. // Check mmq warptiles as the largest configuration
  2427. // Throw an error if not enough for any matrix multiplication is available
  2428. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) {
  2429. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  2430. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  2431. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) {
  2432. device->mul_mat_m[i] = false;
  2433. device->mul_mat_l[i] = false;
  2434. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) {
  2435. device->mul_mat_l[i] = false;
  2436. }
  2437. // Disable mul_mat_id if not enough shared memory is available
  2438. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmqid, true, t)) {
  2439. device->mul_mat_id_s[i] = false;
  2440. device->mul_mat_id_m[i] = false;
  2441. device->mul_mat_id_l[i] = false;
  2442. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmqid, true, t)) {
  2443. device->mul_mat_id_m[i] = false;
  2444. device->mul_mat_id_l[i] = false;
  2445. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmqid, true, t)) {
  2446. device->mul_mat_id_l[i] = false;
  2447. }
  2448. }
  2449. }
  2450. if (!device->pipeline_matmul_f32) {
  2451. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2452. }
  2453. if (!device->pipeline_matmul_f32_f16) {
  2454. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  2455. }
  2456. if (!device->pipeline_matmul_id_f32) {
  2457. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2458. }
  2459. if (!device->pipeline_matmul_bf16) {
  2460. device->pipeline_matmul_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2461. }
  2462. if (!device->pipeline_matmul_id_bf16) {
  2463. device->pipeline_matmul_id_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2464. }
  2465. std::vector<std::future<void>> compiles;
  2466. auto const &ggml_vk_create_pipeline = [&](vk_device& device, vk_pipeline& pipeline, const char *name, size_t spv_size, const void* spv_data, const char *entrypoint,
  2467. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2468. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2469. if (!require_full_subgroups && required_subgroup_size == 0) {
  2470. required_subgroup_size = get_subgroup_size(name, device->architecture);
  2471. }
  2472. if (!pipeline) {
  2473. pipeline = std::make_shared<vk_pipeline_struct>();
  2474. }
  2475. if (!pipeline->initialized) {
  2476. pipeline->name = name;
  2477. pipeline->parameter_count = parameter_count;
  2478. pipeline->push_constant_size = push_constant_size;
  2479. pipeline->wg_denoms = wg_denoms;
  2480. pipeline->align = align;
  2481. pipeline->initialized = true;
  2482. }
  2483. if (!pipeline->needed || pipeline->compiled) {
  2484. return;
  2485. }
  2486. // TODO: We're no longer benefitting from the async compiles (shaders are
  2487. // compiled individually, as needed) and this complexity can be removed.
  2488. {
  2489. // wait until fewer than N compiles are in progress
  2490. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  2491. std::unique_lock<std::mutex> guard(compile_count_mutex);
  2492. while (compile_count >= N) {
  2493. compile_count_cond.wait(guard);
  2494. }
  2495. compile_count++;
  2496. }
  2497. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  2498. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  2499. };
  2500. auto const &ggml_vk_create_pipeline2 = [&](vk_device& device, vk_pipeline& pipeline, const std::string &name, size_t spv_size, const void* spv_data, const char *entrypoint,
  2501. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2502. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2503. return ggml_vk_create_pipeline(device, pipeline, name.c_str(), spv_size, spv_data, entrypoint,
  2504. parameter_count, push_constant_size, wg_denoms, specialization_constants,
  2505. align, disable_robustness, require_full_subgroups, required_subgroup_size);
  2506. };
  2507. auto const &fa_wg_denoms = [&](FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows) -> std::array<uint32_t, 3> {
  2508. return {fa_rows_cols(path, hsk, hsv, clamp, type, small_rows)[0], 1, 1};
  2509. };
  2510. auto const &fa_spec_constants = [&](FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows) -> std::vector<uint32_t> {
  2511. // For large number of rows, 128 invocations seems to work best.
  2512. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  2513. // can't use 256 for D==80.
  2514. // For scalar, use 128 (arbitrary)
  2515. // The same D_split value is used for both HSK and HSV, so just base it on the union of the LSBs.
  2516. const uint32_t D = (hsk|hsv);
  2517. uint32_t wg_size = (path == FA_SCALAR || path == FA_COOPMAT1)
  2518. ? scalar_flash_attention_workgroup_size
  2519. : ((small_rows && (D % 32) == 0) ? 256 : 128);
  2520. auto rows_cols = fa_rows_cols(path, hsk, hsv, clamp, type, small_rows);
  2521. // D_split can't be larger than a subgroup because we use subgroupShuffle to reduce it.
  2522. // D_split can't be larger than the LSB of D divided by 4 due to vectorization in the shader.
  2523. const uint32_t D_lsb = D ^ (D & (D-1));
  2524. uint32_t D_split = std::min(std::min(device->subgroup_size, 8u), D_lsb / 4);
  2525. return {wg_size, rows_cols[0], rows_cols[1], hsk, hsv, clamp, D_split};
  2526. };
  2527. #define CREATE_FA(TYPE, NAMELC, FAPATH, SUFFIX) \
  2528. for (auto &fa : device->pipeline_flash_attn_f32_f16[TYPE]) { \
  2529. uint32_t HSK = fa.first.HSK; \
  2530. uint32_t HSV = fa.first.HSV; \
  2531. bool small_rows = fa.first.small_rows; \
  2532. FaCodePath path = fa.first.path; \
  2533. bool aligned = fa.first.aligned; \
  2534. bool f32acc = fa.first.f32acc; \
  2535. if (path == FAPATH) { \
  2536. if (aligned) { \
  2537. if (f32acc) { \
  2538. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_aligned_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_align(FAPATH,HSK,HSV,TYPE,small_rows), true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2539. } else { \
  2540. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_aligned_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_align(FAPATH,HSK,HSV,TYPE,small_rows), true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2541. } \
  2542. } else { \
  2543. if (f32acc) { \
  2544. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,1,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows), 1, true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2545. } else { \
  2546. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,1,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows), 1, true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2547. } \
  2548. } \
  2549. } \
  2550. }
  2551. CREATE_FA(GGML_TYPE_F32, f32, FA_SCALAR, )
  2552. CREATE_FA(GGML_TYPE_F16, f16, FA_SCALAR, )
  2553. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_SCALAR, )
  2554. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_SCALAR, )
  2555. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2556. if (device->coopmat1_fa_support) {
  2557. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT1, _cm1)
  2558. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT1, _cm1)
  2559. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT1, _cm1)
  2560. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT1, _cm1)
  2561. }
  2562. #endif
  2563. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2564. if (device->coopmat2) {
  2565. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT2, _cm2)
  2566. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT2, _cm2)
  2567. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT2, _cm2)
  2568. CREATE_FA(GGML_TYPE_Q4_1, q4_1, FA_COOPMAT2, _cm2)
  2569. CREATE_FA(GGML_TYPE_Q5_0, q5_0, FA_COOPMAT2, _cm2)
  2570. CREATE_FA(GGML_TYPE_Q5_1, q5_1, FA_COOPMAT2, _cm2)
  2571. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT2, _cm2)
  2572. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl, FA_COOPMAT2, _cm2)
  2573. }
  2574. #endif
  2575. #undef CREATE_FA
  2576. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2577. if (device->coopmat2) {
  2578. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2579. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2580. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _cm2_len, NAMELC ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  2581. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _cm2_len, NAMELC ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  2582. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _cm2_len, NAMELC ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  2583. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _cm2_len, NAMELC ## _aligned ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align); \
  2584. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _cm2_len, NAMELC ## _aligned ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align); \
  2585. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _cm2_len, NAMELC ## _aligned ## F16ACC ## _cm2_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align); \
  2586. // Create 2 variants, {f16,f32} accumulator
  2587. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2588. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2589. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2590. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2591. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2592. if (device->coopmat_bf16_support) {
  2593. CREATE_MM(pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2594. }
  2595. #endif
  2596. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_0], matmul_q4_0_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2597. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_1], matmul_q4_1_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2598. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_0], matmul_q5_0_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2599. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_1], matmul_q5_1_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2600. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q8_0], matmul_q8_0_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2601. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q2_K], matmul_q2_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2602. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q3_K], matmul_q3_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2603. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_K], matmul_q4_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2604. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_K], matmul_q5_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2605. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q6_K], matmul_q6_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2606. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ1_S], matmul_iq1_s_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2607. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ1_M], matmul_iq1_m_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2608. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2609. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2610. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ2_S], matmul_iq2_s_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2611. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2612. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ3_S], matmul_iq3_s_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2613. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2614. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2615. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_MXFP4], matmul_mxfp4_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2616. GGML_ASSERT(device->subgroup_ballot);
  2617. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2618. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2619. if (device->coopmat_bf16_support) {
  2620. CREATE_MM(pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2621. }
  2622. #endif
  2623. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2624. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2625. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2626. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2627. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2628. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2629. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2630. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2631. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2632. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2633. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2634. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2635. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2636. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2637. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2638. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2639. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2640. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2641. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2642. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2643. #undef CREATE_MM
  2644. #undef CREATE_MM2
  2645. } else
  2646. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2647. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2648. if (device->coopmat_support) {
  2649. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2650. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2651. if (device->mul_mat ## ID ## _l[TYPE]) \
  2652. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _cm1_len, NAMELC ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, true); \
  2653. if (device->mul_mat ## ID ## _m[TYPE]) \
  2654. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _cm1_len, NAMELC ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, true); \
  2655. if (device->mul_mat ## ID ## _s[TYPE]) \
  2656. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _cm1_len, NAMELC ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, true); \
  2657. if (device->mul_mat ## ID ## _l[TYPE]) \
  2658. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _cm1_len, NAMELC ## _aligned ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, true); \
  2659. if (device->mul_mat ## ID ## _m[TYPE]) \
  2660. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _cm1_len, NAMELC ## _aligned ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, true); \
  2661. if (device->mul_mat ## ID ## _s[TYPE]) \
  2662. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _cm1_len, NAMELC ## _aligned ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, true); \
  2663. // Create 2 variants, {f16,f32} accumulator
  2664. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2665. if (device->coopmat_acc_f16_support) { \
  2666. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2667. } \
  2668. if (device->coopmat_acc_f32_support) { \
  2669. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2670. } \
  2671. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2672. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2673. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2674. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2675. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2676. if (device->coopmat_bf16_support) {
  2677. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, )
  2678. }
  2679. #endif
  2680. if (device->coopmat_acc_f16_support) {
  2681. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0], matmul_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2682. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1], matmul_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2683. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0], matmul_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2684. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1], matmul_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2685. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0], matmul_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2686. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K], matmul_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2687. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K], matmul_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2688. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K], matmul_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2689. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K], matmul_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2690. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K], matmul_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2691. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S], matmul_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2692. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M], matmul_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2693. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2694. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2695. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S], matmul_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2696. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2697. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S], matmul_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2698. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2699. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2700. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4], matmul_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2701. } else {
  2702. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2703. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2704. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2705. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2706. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2707. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2708. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2709. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2710. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2711. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2712. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S].f32acc, matmul_iq1_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2713. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M].f32acc, matmul_iq1_m_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2714. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS].f32acc, matmul_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2715. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS].f32acc, matmul_iq2_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2716. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S].f32acc, matmul_iq2_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2717. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS].f32acc, matmul_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2718. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S].f32acc, matmul_iq3_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2719. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS].f32acc, matmul_iq4_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2720. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f32acc, matmul_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2721. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4].f32acc, matmul_mxfp4_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2722. }
  2723. GGML_ASSERT(device->subgroup_ballot);
  2724. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2725. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2726. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2727. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2728. if (device->coopmat_bf16_support) {
  2729. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2730. }
  2731. #endif
  2732. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2733. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2734. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2735. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2736. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2737. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2738. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2739. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2740. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2741. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2742. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2743. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2744. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2745. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2746. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2747. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2748. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2749. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2750. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2751. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2752. #undef CREATE_MM2
  2753. #undef CREATE_MM
  2754. } else
  2755. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2756. if (device->fp16) {
  2757. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2758. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2759. if (device->mul_mat ## ID ## _l[TYPE]) \
  2760. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2761. if (device->mul_mat ## ID ## _m[TYPE]) \
  2762. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2763. if (device->mul_mat ## ID ## _s[TYPE]) \
  2764. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2765. if (device->mul_mat ## ID ## _l[TYPE]) \
  2766. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2767. if (device->mul_mat ## ID ## _m[TYPE]) \
  2768. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2769. if (device->mul_mat ## ID ## _s[TYPE]) \
  2770. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2771. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2772. if (device->mul_mat ## ID ## _l[TYPE]) { \
  2773. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->l, #NAMELC "_l", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2774. } \
  2775. if (device->mul_mat ## ID ## _m[TYPE]) { \
  2776. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->m, #NAMELC "_m", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2777. } \
  2778. if (device->mul_mat ## ID ## _s[TYPE]) { \
  2779. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->s, #NAMELC "_s", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2780. } \
  2781. // Create 2 variants, {f16,f32} accumulator
  2782. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2783. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2784. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2785. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2786. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2787. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2788. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2789. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2790. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0], matmul_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2791. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1], matmul_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2792. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0], matmul_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2793. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1], matmul_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2794. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0], matmul_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2795. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K], matmul_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2796. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K], matmul_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2797. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K], matmul_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2798. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K], matmul_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2799. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K], matmul_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2800. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S], matmul_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2801. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M], matmul_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2802. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2803. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2804. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S], matmul_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2805. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2806. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S], matmul_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2807. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2808. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2809. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4], matmul_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2810. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2811. if (device->integer_dot_product) {
  2812. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_0], matmul_q4_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2813. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_1], matmul_q4_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2814. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_0], matmul_q5_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2815. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_1], matmul_q5_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2816. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q8_0], matmul_q8_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2817. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_MXFP4], matmul_mxfp4_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2818. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q2_K], matmul_q2_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2819. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q3_K], matmul_q3_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2820. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_K], matmul_q4_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2821. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_K], matmul_q5_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2822. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q6_K], matmul_q6_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2823. }
  2824. #endif
  2825. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2826. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2827. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2828. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2829. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2830. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2831. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2832. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2833. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2834. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2835. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2836. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2837. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2838. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2839. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2840. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2841. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2842. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2843. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2844. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2845. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2846. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2847. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2848. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2849. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2850. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2851. if (device->integer_dot_product) {
  2852. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2853. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2854. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2855. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2856. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2857. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2858. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2859. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2860. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2861. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2862. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2863. }
  2864. #endif
  2865. } else {
  2866. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2867. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2868. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2869. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2870. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2871. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2872. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2873. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2874. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2875. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2876. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2877. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2878. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2879. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2880. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2881. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2882. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2883. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2884. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2885. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2886. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2887. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2888. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2889. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2890. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2891. if (device->integer_dot_product) {
  2892. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_0], matmul_id_q4_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2893. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_1], matmul_id_q4_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2894. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_0], matmul_id_q5_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2895. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_1], matmul_id_q5_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2896. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q8_0], matmul_id_q8_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2897. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_MXFP4], matmul_id_mxfp4_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2898. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q2_K], matmul_id_q2_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2899. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q3_K], matmul_id_q3_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2900. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_K], matmul_id_q4_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2901. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_K], matmul_id_q5_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2902. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q6_K], matmul_id_q6_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2903. }
  2904. #endif
  2905. }
  2906. #undef CREATE_MM2
  2907. #undef CREATE_MMQ
  2908. #undef CREATE_MM
  2909. } else {
  2910. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2911. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2912. if (device->mul_mat ## ID ## _l[TYPE]) \
  2913. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2914. if (device->mul_mat ## ID ## _m[TYPE]) \
  2915. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2916. if (device->mul_mat ## ID ## _s[TYPE]) \
  2917. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2918. if (device->mul_mat ## ID ## _l[TYPE]) \
  2919. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2920. if (device->mul_mat ## ID ## _m[TYPE]) \
  2921. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2922. if (device->mul_mat ## ID ## _s[TYPE]) \
  2923. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2924. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2925. if (device->mul_mat ## ID ## _l[TYPE]) \
  2926. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC "_l", NAMELC ## _fp32_len, NAMELC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  2927. if (device->mul_mat ## ID ## _m[TYPE]) \
  2928. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC "_m", NAMELC ## _fp32_len, NAMELC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  2929. if (device->mul_mat ## ID ## _s[TYPE]) \
  2930. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC "_s", NAMELC ## _fp32_len, NAMELC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  2931. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2932. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2933. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2934. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2935. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2936. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2937. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2938. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2939. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2940. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2941. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2942. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2943. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2944. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2945. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2946. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S].f32acc, matmul_iq1_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2947. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M].f32acc, matmul_iq1_m_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2948. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS].f32acc, matmul_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2949. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS].f32acc, matmul_iq2_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2950. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S].f32acc, matmul_iq2_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2951. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS].f32acc, matmul_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2952. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S].f32acc, matmul_iq3_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2953. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS].f32acc, matmul_iq4_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2954. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f32acc, matmul_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2955. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4].f32acc, matmul_mxfp4_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2956. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2957. if (device->integer_dot_product) {
  2958. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2959. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2960. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2961. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2962. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2963. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2964. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2965. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2966. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2967. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2968. }
  2969. #endif
  2970. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2971. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2972. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_subgroup_f16, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2973. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_subgroup_f16_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2974. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2975. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_subgroup_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2976. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_subgroup_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2977. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_subgroup_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2978. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_subgroup_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2979. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_subgroup_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2980. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_subgroup_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2981. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_subgroup_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2982. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_subgroup_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2983. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_subgroup_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2984. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_subgroup_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2985. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_subgroup_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2986. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_subgroup_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2987. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_subgroup_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2988. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_subgroup_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2989. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_subgroup_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2990. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_subgroup_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2991. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_subgroup_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2992. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_subgroup_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2993. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_subgroup_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2994. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_subgroup_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2995. } else {
  2996. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2997. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2998. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2999. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  3000. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3001. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3002. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3003. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3004. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3005. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3006. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3007. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3008. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3009. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3010. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3011. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3012. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3013. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3014. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3015. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3016. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3017. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3018. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3019. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  3020. }
  3021. }
  3022. // reusing CREATE_MM from the fp32 path
  3023. if ((device->coopmat2 || device->coopmat_support)
  3024. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3025. && !device->coopmat_bf16_support
  3026. #endif
  3027. ) {
  3028. // use scalar tile sizes
  3029. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  3030. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, 4, 2, 1, subgroup_size_8 };
  3031. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, 2, 2, 1, subgroup_size_8 };
  3032. l_wg_denoms = {128, 128, 1 };
  3033. m_wg_denoms = { 64, 64, 1 };
  3034. s_wg_denoms = { 32, 32, 1 };
  3035. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  3036. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  3037. }
  3038. #undef CREATE_MM
  3039. // mul mat vec
  3040. // the number of rows computed per shader depends on GPU model and quant
  3041. uint32_t rm_stdq = 1;
  3042. uint32_t rm_kq = 2;
  3043. uint32_t rm_stdq_int = 1;
  3044. uint32_t rm_kq_int = 1;
  3045. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3046. if (device->architecture == AMD_GCN) {
  3047. rm_stdq = 2;
  3048. rm_kq = 4;
  3049. rm_stdq_int = 4;
  3050. }
  3051. } else if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3052. rm_stdq = 2;
  3053. rm_stdq_int = 2;
  3054. }
  3055. uint32_t rm_iq = 2 * rm_kq;
  3056. const bool use_subgroups = device->subgroup_arithmetic && device->architecture != vk_device_architecture::AMD_GCN;
  3057. // Ensure a subgroup size >= 16 is available
  3058. const bool use_subgroups16 = use_subgroups && subgroup_min_size_16;
  3059. const uint32_t subgroup_size = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control && device->subgroup_min_size <= 16 && device->subgroup_max_size >= 16) ? 16 : device->subgroup_size;
  3060. const uint32_t subgroup_size16 = std::max(subgroup_size, 16u);
  3061. const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0;
  3062. const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0;
  3063. static constexpr uint32_t mul_mat_vec_num_bindings = 5;
  3064. static constexpr uint32_t mul_mat_vec_id_num_bindings = 6;
  3065. for (uint32_t w = 0; w < DMMV_WG_SIZE_COUNT; ++w) {
  3066. const uint32_t wg_size_subgroup = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size : (subgroup_size * 4);
  3067. const uint32_t wg_size_subgroup16 = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size16 : (subgroup_size16 * 4);
  3068. const shader_reduction_mode reduc = (use_subgroups && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  3069. (use_subgroups && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  3070. SHADER_REDUCTION_MODE_SHMEM;
  3071. const shader_reduction_mode reduc16 = (use_subgroups16 && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  3072. (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  3073. SHADER_REDUCTION_MODE_SHMEM;
  3074. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  3075. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f32_f32", arr_dmmv_f32_f32_f32_len[reduc], arr_dmmv_f32_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {wg_size_subgroup, 1, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3076. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f32_f32", arr_dmmv_f16_f32_f32_len[reduc], arr_dmmv_f16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3077. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f32_f32", arr_dmmv_bf16_f32_f32_len[reduc], arr_dmmv_bf16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3078. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f32_f32", arr_dmmv_q4_0_f32_f32_len[reduc], arr_dmmv_q4_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3079. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f32_f32", arr_dmmv_q4_1_f32_f32_len[reduc], arr_dmmv_q4_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3080. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f32_f32", arr_dmmv_q5_0_f32_f32_len[reduc], arr_dmmv_q5_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3081. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f32_f32", arr_dmmv_q5_1_f32_f32_len[reduc], arr_dmmv_q5_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3082. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f32_f32", arr_dmmv_q8_0_f32_f32_len[reduc], arr_dmmv_q8_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3083. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f32_f32", arr_dmmv_q2_k_f32_f32_len[reduc16], arr_dmmv_q2_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3084. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f32_f32", arr_dmmv_q3_k_f32_f32_len[reduc16], arr_dmmv_q3_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3085. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f32_f32", arr_dmmv_q4_k_f32_f32_len[reduc16], arr_dmmv_q4_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3086. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f32_f32", arr_dmmv_q5_k_f32_f32_len[reduc16], arr_dmmv_q5_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3087. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f32_f32", arr_dmmv_q6_k_f32_f32_len[reduc16], arr_dmmv_q6_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3088. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f32_f32", arr_dmmv_iq1_s_f32_f32_len[reduc16], arr_dmmv_iq1_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3089. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f32_f32", arr_dmmv_iq1_m_f32_f32_len[reduc16], arr_dmmv_iq1_m_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3090. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f32_f32", arr_dmmv_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_iq2_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3091. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f32_f32", arr_dmmv_iq2_xs_f32_f32_len[reduc16], arr_dmmv_iq2_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3092. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f32_f32", arr_dmmv_iq2_s_f32_f32_len[reduc16], arr_dmmv_iq2_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3093. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f32_f32", arr_dmmv_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_iq3_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3094. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f32_f32", arr_dmmv_iq3_s_f32_f32_len[reduc16], arr_dmmv_iq3_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3095. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f32_f32", arr_dmmv_iq4_xs_f32_f32_len[reduc16], arr_dmmv_iq4_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3096. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f32_f32", arr_dmmv_iq4_nl_f32_f32_len[reduc16], arr_dmmv_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3097. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f32_f32", arr_dmmv_mxfp4_f32_f32_len[reduc16], arr_dmmv_mxfp4_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3098. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f16_f32", arr_dmmv_f32_f16_f32_len[reduc], arr_dmmv_f32_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {wg_size_subgroup, 1, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3099. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f16_f32", arr_dmmv_f16_f16_f32_len[reduc], arr_dmmv_f16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3100. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f16_f32", arr_dmmv_bf16_f16_f32_len[reduc], arr_dmmv_bf16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3101. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f16_f32", arr_dmmv_q4_0_f16_f32_len[reduc], arr_dmmv_q4_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3102. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f16_f32", arr_dmmv_q4_1_f16_f32_len[reduc], arr_dmmv_q4_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3103. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f16_f32", arr_dmmv_q5_0_f16_f32_len[reduc], arr_dmmv_q5_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3104. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f16_f32", arr_dmmv_q5_1_f16_f32_len[reduc], arr_dmmv_q5_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3105. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f16_f32", arr_dmmv_q8_0_f16_f32_len[reduc], arr_dmmv_q8_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3106. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f16_f32", arr_dmmv_q2_k_f16_f32_len[reduc16], arr_dmmv_q2_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3107. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f16_f32", arr_dmmv_q3_k_f16_f32_len[reduc16], arr_dmmv_q3_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3108. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f16_f32", arr_dmmv_q4_k_f16_f32_len[reduc16], arr_dmmv_q4_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3109. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f16_f32", arr_dmmv_q5_k_f16_f32_len[reduc16], arr_dmmv_q5_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3110. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f16_f32", arr_dmmv_q6_k_f16_f32_len[reduc16], arr_dmmv_q6_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3111. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f16_f32", arr_dmmv_iq1_s_f16_f32_len[reduc16], arr_dmmv_iq1_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3112. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f16_f32", arr_dmmv_iq1_m_f16_f32_len[reduc16], arr_dmmv_iq1_m_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3113. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f16_f32", arr_dmmv_iq2_xxs_f16_f32_len[reduc16], arr_dmmv_iq2_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3114. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f16_f32", arr_dmmv_iq2_xs_f16_f32_len[reduc16], arr_dmmv_iq2_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3115. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f16_f32", arr_dmmv_iq2_s_f16_f32_len[reduc16], arr_dmmv_iq2_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3116. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f16_f32", arr_dmmv_iq3_xxs_f16_f32_len[reduc16], arr_dmmv_iq3_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3117. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f16_f32", arr_dmmv_iq3_s_f16_f32_len[reduc16], arr_dmmv_iq3_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3118. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f16_f32", arr_dmmv_iq4_xs_f16_f32_len[reduc16], arr_dmmv_iq4_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3119. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f16_f32", arr_dmmv_iq4_nl_f16_f32_len[reduc16], arr_dmmv_iq4_nl_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3120. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f16_f32", arr_dmmv_mxfp4_f16_f32_len[reduc16], arr_dmmv_mxfp4_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3121. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3122. if (device->integer_dot_product) {
  3123. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  3124. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  3125. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_q8_1_f32", arr_dmmv_q4_0_q8_1_f32_len[reduc], arr_dmmv_q4_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3126. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_q8_1_f32", arr_dmmv_q4_1_q8_1_f32_len[reduc], arr_dmmv_q4_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3127. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_q8_1_f32", arr_dmmv_q5_0_q8_1_f32_len[reduc], arr_dmmv_q5_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3128. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_q8_1_f32", arr_dmmv_q5_1_q8_1_f32_len[reduc], arr_dmmv_q5_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3129. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_q8_1_f32", arr_dmmv_q8_0_q8_1_f32_len[reduc], arr_dmmv_q8_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3130. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_q8_1_f32", arr_dmmv_mxfp4_q8_1_f32_len[reduc], arr_dmmv_mxfp4_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3131. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_q8_1_f32", arr_dmmv_q2_k_q8_1_f32_len[reduc], arr_dmmv_q2_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 2*rm_kq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3132. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_q8_1_f32", arr_dmmv_q3_k_q8_1_f32_len[reduc], arr_dmmv_q3_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3133. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_q8_1_f32", arr_dmmv_q4_k_q8_1_f32_len[reduc], arr_dmmv_q4_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3134. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_q8_1_f32", arr_dmmv_q5_k_q8_1_f32_len[reduc], arr_dmmv_q5_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3135. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_q8_1_f32", arr_dmmv_q6_k_q8_1_f32_len[reduc], arr_dmmv_q6_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3136. }
  3137. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  3138. }
  3139. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_F32 ], "mul_mat_vec_id_f32_f32", arr_dmmv_id_f32_f32_f32_len[reduc], arr_dmmv_id_f32_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1, 1, 1}, {wg_size_subgroup, 1}, 1, false, use_subgroups, force_subgroup_size);
  3140. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_F16 ], "mul_mat_vec_id_f16_f32", arr_dmmv_id_f16_f32_f32_len[reduc], arr_dmmv_id_f16_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {wg_size_subgroup, 2}, 1, false, use_subgroups, force_subgroup_size);
  3141. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_BF16], "mul_mat_vec_id_bf16_f32", arr_dmmv_id_bf16_f32_f32_len[reduc], arr_dmmv_id_bf16_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {wg_size_subgroup, 2}, 1, false, use_subgroups, force_subgroup_size);
  3142. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_0], "mul_mat_vec_id_q4_0_f32", arr_dmmv_id_q4_0_f32_f32_len[reduc], arr_dmmv_id_q4_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size);
  3143. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_1], "mul_mat_vec_id_q4_1_f32", arr_dmmv_id_q4_1_f32_f32_len[reduc], arr_dmmv_id_q4_1_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size);
  3144. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_0], "mul_mat_vec_id_q5_0_f32", arr_dmmv_id_q5_0_f32_f32_len[reduc], arr_dmmv_id_q5_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size);
  3145. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_1], "mul_mat_vec_id_q5_1_f32", arr_dmmv_id_q5_1_f32_f32_len[reduc], arr_dmmv_id_q5_1_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq}, 1, true, use_subgroups, force_subgroup_size);
  3146. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q8_0], "mul_mat_vec_id_q8_0_f32", arr_dmmv_id_q8_0_f32_f32_len[reduc], arr_dmmv_id_q8_0_f32_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq}, 1, true, use_subgroups, force_subgroup_size);
  3147. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q2_K], "mul_mat_vec_id_q2_k_f32", arr_dmmv_id_q2_k_f32_f32_len[reduc16], arr_dmmv_id_q2_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16);
  3148. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q3_K], "mul_mat_vec_id_q3_k_f32", arr_dmmv_id_q3_k_f32_f32_len[reduc16], arr_dmmv_id_q3_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16);
  3149. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q4_K], "mul_mat_vec_id_q4_k_f32", arr_dmmv_id_q4_k_f32_f32_len[reduc16], arr_dmmv_id_q4_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16);
  3150. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q5_K], "mul_mat_vec_id_q5_k_f32", arr_dmmv_id_q5_k_f32_f32_len[reduc16], arr_dmmv_id_q5_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16);
  3151. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_Q6_K], "mul_mat_vec_id_q6_k_f32", arr_dmmv_id_q6_k_f32_f32_len[reduc16], arr_dmmv_id_q6_k_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq}, 1, true, use_subgroups16, force_subgroup_size16);
  3152. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ1_S], "mul_mat_vec_id_iq1_s_f32", arr_dmmv_id_iq1_s_f32_f32_len[reduc16], arr_dmmv_id_iq1_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3153. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ1_M], "mul_mat_vec_id_iq1_m_f32", arr_dmmv_id_iq1_m_f32_f32_len[reduc16], arr_dmmv_id_iq1_m_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3154. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_XXS], "mul_mat_vec_id_iq2_xxs_f32", arr_dmmv_id_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_id_iq2_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3155. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_XS], "mul_mat_vec_id_iq2_xs_f32", arr_dmmv_id_iq2_xs_f32_f32_len[reduc16], arr_dmmv_id_iq2_xs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3156. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ2_S], "mul_mat_vec_id_iq2_s_f32", arr_dmmv_id_iq2_s_f32_f32_len[reduc16], arr_dmmv_id_iq2_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3157. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ3_XXS], "mul_mat_vec_id_iq3_xxs_f32", arr_dmmv_id_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_id_iq3_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3158. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ3_S], "mul_mat_vec_id_iq3_s_f32", arr_dmmv_id_iq3_s_f32_f32_len[reduc16], arr_dmmv_id_iq3_s_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3159. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ4_XS], "mul_mat_vec_id_iq4_xs_f32", arr_dmmv_id_iq4_xs_f32_f32_len[reduc16], arr_dmmv_id_iq4_xs_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3160. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ4_NL], "mul_mat_vec_id_iq4_nl_f32", arr_dmmv_id_iq4_nl_f32_f32_len[reduc16], arr_dmmv_id_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3161. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_f32", arr_dmmv_id_mxfp4_f32_f32_len[reduc16], arr_dmmv_id_mxfp4_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
  3162. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3163. if (device->integer_dot_product) {
  3164. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  3165. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  3166. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q4_0], "mul_mat_vec_id_q4_0_q8_1_f32", arr_dmmv_id_q4_0_q8_1_f32_len[reduc], arr_dmmv_id_q4_0_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3167. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q4_1], "mul_mat_vec_id_q4_1_q8_1_f32", arr_dmmv_id_q4_1_q8_1_f32_len[reduc], arr_dmmv_id_q4_1_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3168. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q5_0], "mul_mat_vec_id_q5_0_q8_1_f32", arr_dmmv_id_q5_0_q8_1_f32_len[reduc], arr_dmmv_id_q5_0_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3169. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q5_1], "mul_mat_vec_id_q5_1_q8_1_f32", arr_dmmv_id_q5_1_q8_1_f32_len[reduc], arr_dmmv_id_q5_1_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3170. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q8_0], "mul_mat_vec_id_q8_0_q8_1_f32", arr_dmmv_id_q8_0_q8_1_f32_len[reduc], arr_dmmv_id_q8_0_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3171. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_q8_1_f32", arr_dmmv_id_mxfp4_q8_1_f32_len[reduc], arr_dmmv_id_mxfp4_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq_int, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq_int}, 1, true, use_subgroups, subgroup_size_int);
  3172. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q2_K], "mul_mat_vec_id_q2_k_q8_1_f32", arr_dmmv_id_q2_k_q8_1_f32_len[reduc], arr_dmmv_id_q2_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 2*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3173. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q3_K], "mul_mat_vec_id_q3_k_q8_1_f32", arr_dmmv_id_q3_k_q8_1_f32_len[reduc], arr_dmmv_id_q3_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3174. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q4_K], "mul_mat_vec_id_q4_k_q8_1_f32", arr_dmmv_id_q4_k_q8_1_f32_len[reduc], arr_dmmv_id_q4_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3175. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q5_K], "mul_mat_vec_id_q5_k_q8_1_f32", arr_dmmv_id_q5_k_q8_1_f32_len[reduc], arr_dmmv_id_q5_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3176. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[w][GGML_TYPE_Q6_K], "mul_mat_vec_id_q6_k_q8_1_f32", arr_dmmv_id_q6_k_q8_1_f32_len[reduc], arr_dmmv_id_q6_k_q8_1_f32_data[reduc], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_kq_int, 1, 1}, {wg_size_subgroup_int, 1*rm_kq_int}, 1, true, use_subgroups, subgroup_size_int);
  3177. }
  3178. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  3179. }
  3180. #if !defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3181. GGML_UNUSED(rm_stdq_int);
  3182. GGML_UNUSED(rm_kq_int);
  3183. #endif
  3184. // dequant shaders
  3185. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_F32 ], "f32_to_f16", dequant_f32_len, dequant_f32_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3186. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_0], "dequant_q4_0", dequant_q4_0_len, dequant_q4_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3187. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_1], "dequant_q4_1", dequant_q4_1_len, dequant_q4_1_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3188. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_0], "dequant_q5_0", dequant_q5_0_len, dequant_q5_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3189. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_1], "dequant_q5_1", dequant_q5_1_len, dequant_q5_1_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3190. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q8_0], "dequant_q8_0", dequant_q8_0_len, dequant_q8_0_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3191. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q2_K], "dequant_q2_k", dequant_q2_k_len, dequant_q2_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  3192. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q3_K], "dequant_q3_k", dequant_q3_k_len, dequant_q3_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  3193. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q4_K], "dequant_q4_k", dequant_q4_k_len, dequant_q4_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3194. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q5_K], "dequant_q5_k", dequant_q5_k_len, dequant_q5_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  3195. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_Q6_K], "dequant_q6_k", dequant_q6_k_len, dequant_q6_k_data, "main", 2, 5 * sizeof(uint32_t), {256 * 64, 1, 1}, {}, 1);
  3196. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ1_S], "dequant_iq1_s", dequant_iq1_s_len, dequant_iq1_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3197. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ1_M], "dequant_iq1_m", dequant_iq1_m_len, dequant_iq1_m_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3198. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_XXS], "dequant_iq2_xxs", dequant_iq2_xxs_len, dequant_iq2_xxs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3199. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_XS], "dequant_iq2_xs", dequant_iq2_xs_len, dequant_iq2_xs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3200. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_S], "dequant_iq2_s", dequant_iq2_s_len, dequant_iq2_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3201. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ3_XXS], "dequant_iq3_xxs", dequant_iq3_xxs_len, dequant_iq3_xxs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3202. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ3_S], "dequant_iq3_s", dequant_iq3_s_len, dequant_iq3_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3203. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ4_XS], "dequant_iq4_xs", dequant_iq4_xs_len, dequant_iq4_xs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  3204. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ4_NL], "dequant_iq4_nl", dequant_iq4_nl_len, dequant_iq4_nl_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3205. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_MXFP4], "dequant_mxfp4", dequant_mxfp4_len, dequant_mxfp4_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  3206. // get_rows
  3207. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_F32 ], "get_rows_f32", get_rows_f32_len, get_rows_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  3208. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_F16 ], "get_rows_f16", get_rows_f16_len, get_rows_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  3209. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_BF16], "get_rows_bf16", get_rows_bf16_len, get_rows_bf16_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  3210. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_0], "get_rows_q4_0", get_rows_q4_0_len, get_rows_q4_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3211. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_1], "get_rows_q4_1", get_rows_q4_1_len, get_rows_q4_1_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3212. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_0], "get_rows_q5_0", get_rows_q5_0_len, get_rows_q5_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3213. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_1], "get_rows_q5_1", get_rows_q5_1_len, get_rows_q5_1_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3214. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q8_0], "get_rows_q8_0", get_rows_q8_0_len, get_rows_q8_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3215. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q2_K], "get_rows_q2_k", get_rows_q2_k_len, get_rows_q2_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3216. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q3_K], "get_rows_q3_k", get_rows_q3_k_len, get_rows_q3_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3217. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_K], "get_rows_q4_k", get_rows_q4_k_len, get_rows_q4_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3218. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_K], "get_rows_q5_k", get_rows_q5_k_len, get_rows_q5_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3219. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q6_K], "get_rows_q6_k", get_rows_q6_k_len, get_rows_q6_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3220. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ1_S], "get_rows_iq1_s", get_rows_iq1_s_len, get_rows_iq1_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3221. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ1_M], "get_rows_iq1_m", get_rows_iq1_m_len, get_rows_iq1_m_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3222. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_XXS], "get_rows_iq2_xxs", get_rows_iq2_xxs_len, get_rows_iq2_xxs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3223. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_XS], "get_rows_iq2_xs", get_rows_iq2_xs_len, get_rows_iq2_xs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3224. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_S], "get_rows_iq2_s", get_rows_iq2_s_len, get_rows_iq2_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3225. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ3_XXS], "get_rows_iq3_xxs", get_rows_iq3_xxs_len, get_rows_iq3_xxs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3226. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ3_S], "get_rows_iq3_s", get_rows_iq3_s_len, get_rows_iq3_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3227. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ4_XS], "get_rows_iq4_xs", get_rows_iq4_xs_len, get_rows_iq4_xs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3228. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ4_NL], "get_rows_iq4_nl", get_rows_iq4_nl_len, get_rows_iq4_nl_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3229. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_MXFP4], "get_rows_mxfp4", get_rows_mxfp4_len, get_rows_mxfp4_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3230. ggml_vk_create_pipeline(device, device->pipeline_get_rows_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);
  3231. 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);
  3232. 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);
  3233. 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);
  3234. 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);
  3235. 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);
  3236. 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);
  3237. 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);
  3238. 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);
  3239. 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);
  3240. 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);
  3241. 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);
  3242. 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);
  3243. 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);
  3244. 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);
  3245. 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);
  3246. 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);
  3247. 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);
  3248. 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);
  3249. 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);
  3250. 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);
  3251. 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);
  3252. 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);
  3253. 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);
  3254. 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);
  3255. if (device->subgroup_clustered && device->subgroup_require_full_support) {
  3256. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1_x4, "quantize_q8_1_x4", quantize_q8_1_x4_subgroup_len, quantize_q8_1_x4_subgroup_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1, true, true);
  3257. } else {
  3258. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1_x4, "quantize_q8_1_x4", quantize_q8_1_x4_len, quantize_q8_1_x4_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1);
  3259. }
  3260. for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) {
  3261. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3262. 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);
  3263. } else {
  3264. 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);
  3265. }
  3266. }
  3267. 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);
  3268. 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);
  3269. 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);
  3270. 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);
  3271. 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);
  3272. 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);
  3273. 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);
  3274. if (device->float_controls_rte_fp16 &&
  3275. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= device->properties.limits.maxPushConstantsSize) {
  3276. 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);
  3277. 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);
  3278. }
  3279. 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);
  3280. 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);
  3281. 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);
  3282. 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);
  3283. 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);
  3284. 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);
  3285. 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);
  3286. 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);
  3287. 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);
  3288. 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);
  3289. 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);
  3290. 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);
  3291. 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);
  3292. 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);
  3293. 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);
  3294. 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);
  3295. 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);
  3296. 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);
  3297. if (device->float_controls_rte_fp16) {
  3298. 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);
  3299. 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);
  3300. 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);
  3301. 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);
  3302. 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);
  3303. 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);
  3304. } else {
  3305. 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);
  3306. 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);
  3307. 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);
  3308. 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);
  3309. 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);
  3310. 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);
  3311. }
  3312. #define SET_ROWS(itype, rte) \
  3313. 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); \
  3314. 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); \
  3315. 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); \
  3316. 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); \
  3317. 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); \
  3318. 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); \
  3319. 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); \
  3320. 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); \
  3321. 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);
  3322. if (device->float_controls_rte_fp16) {
  3323. SET_ROWS(_i32, _rte)
  3324. SET_ROWS(_i64, _rte)
  3325. } else {
  3326. SET_ROWS(_i32, )
  3327. SET_ROWS(_i64, )
  3328. }
  3329. #undef SET_ROWS
  3330. 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);
  3331. 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);
  3332. 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);
  3333. 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);
  3334. 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);
  3335. 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);
  3336. auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) {
  3337. std::string s;
  3338. s += std::string(src0_f16 ? "_f16" : "_f32");
  3339. s += std::string(src1_f16 ? "_f16" : "_f32");
  3340. s += std::string(dst_f16 ? "_f16" : "_f32");
  3341. return s;
  3342. };
  3343. bool rte = device->float_controls_rte_fp16;
  3344. #define CREATE_BINARY(name, namemod, spec, bindings) \
  3345. for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \
  3346. ggml_vk_create_pipeline2(device, device->pipeline_ ## name ## namemod[s0][s1][d], \
  3347. #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d][rte], name ## _data[s0][s1][d][rte], \
  3348. "main", (bindings), sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1);
  3349. CREATE_BINARY(add, , {0}, 4)
  3350. CREATE_BINARY(add, _norepeat, {1}, 4)
  3351. CREATE_BINARY(sub, , {0}, 3)
  3352. CREATE_BINARY(sub, _norepeat, {1}, 3)
  3353. CREATE_BINARY(mul, , {0}, 3)
  3354. CREATE_BINARY(mul, _norepeat, {1}, 3)
  3355. CREATE_BINARY(div, , {0}, 3)
  3356. CREATE_BINARY(div, _norepeat, {1}, 3)
  3357. CREATE_BINARY(add_rms, , {0}, 4)
  3358. CREATE_BINARY(add_rms, _norepeat, {1}, 4)
  3359. #undef CREATE_BINARY
  3360. if (device->multi_add) {
  3361. for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) {
  3362. 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);
  3363. 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);
  3364. }
  3365. }
  3366. 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);
  3367. 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);
  3368. 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);
  3369. 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);
  3370. 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);
  3371. 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);
  3372. 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);
  3373. 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);
  3374. 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);
  3375. 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);
  3376. 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);
  3377. 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);
  3378. 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);
  3379. if (device->float_controls_rte_fp16) {
  3380. 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);
  3381. 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);
  3382. } else {
  3383. 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);
  3384. 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);
  3385. }
  3386. 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);
  3387. 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);
  3388. 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);
  3389. 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);
  3390. 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);
  3391. 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);
  3392. 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);
  3393. 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);
  3394. 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);
  3395. #define CREATE_UNARY(name) \
  3396. 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); \
  3397. 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);
  3398. CREATE_UNARY(gelu)
  3399. CREATE_UNARY(gelu_erf)
  3400. CREATE_UNARY(gelu_quick)
  3401. CREATE_UNARY(silu)
  3402. CREATE_UNARY(relu)
  3403. CREATE_UNARY(neg)
  3404. CREATE_UNARY(tanh)
  3405. CREATE_UNARY(sigmoid)
  3406. CREATE_UNARY(hardsigmoid)
  3407. CREATE_UNARY(hardswish)
  3408. CREATE_UNARY(abs)
  3409. CREATE_UNARY(softplus)
  3410. CREATE_UNARY(step)
  3411. CREATE_UNARY(round)
  3412. CREATE_UNARY(ceil)
  3413. CREATE_UNARY(floor)
  3414. CREATE_UNARY(trunc)
  3415. #undef CREATE_UNARY
  3416. #define CREATE_UNARY_RTE(name) \
  3417. if (device->float_controls_rte_fp16) { \
  3418. 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); \
  3419. 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); \
  3420. } else { \
  3421. 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); \
  3422. 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); \
  3423. }
  3424. CREATE_UNARY_RTE(exp)
  3425. #undef CREATE_UNARY_RTE
  3426. 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);
  3427. 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);
  3428. 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);
  3429. ggml_vk_create_pipeline(device, device->pipeline_arange_f32, "arange_f32", arange_f32_len, arange_f32_data, "main", 1, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3430. ggml_vk_create_pipeline(device, device->pipeline_fill_f32, "fill_f32", fill_f32_len, fill_f32_data, "main", 1, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3431. #define CREATE_GLU(name) \
  3432. if (device->float_controls_rte_fp16) { \
  3433. 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); \
  3434. 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); \
  3435. } else { \
  3436. 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); \
  3437. 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); \
  3438. }
  3439. CREATE_GLU(geglu)
  3440. CREATE_GLU(reglu)
  3441. CREATE_GLU(swiglu)
  3442. CREATE_GLU(swiglu_oai)
  3443. CREATE_GLU(geglu_erf)
  3444. CREATE_GLU(geglu_quick)
  3445. #undef CREATE_GLU
  3446. 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);
  3447. 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);
  3448. 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);
  3449. 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);
  3450. 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);
  3451. 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);
  3452. 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);
  3453. 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);
  3454. 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);
  3455. 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);
  3456. 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);
  3457. 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);
  3458. 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);
  3459. 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);
  3460. 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);
  3461. 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);
  3462. 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);
  3463. 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);
  3464. if (device->float_controls_rte_fp16) {
  3465. 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);
  3466. 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);
  3467. 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);
  3468. 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);
  3469. 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);
  3470. 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);
  3471. } else {
  3472. 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);
  3473. 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);
  3474. 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);
  3475. 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);
  3476. 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);
  3477. 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);
  3478. }
  3479. for (uint32_t i = 0; i < num_argsort_pipelines; ++i) {
  3480. uint32_t BLOCK_SIZE = 1u << std::min(i, device->max_workgroup_size_log2);
  3481. if (i <= device->max_workgroup_size_log2 &&
  3482. 2 * sizeof(int) * BLOCK_SIZE <= device->properties.limits.maxComputeSharedMemorySize) {
  3483. const uint32_t NCOLS_PADDED_LOG2 = i;
  3484. 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);
  3485. }
  3486. const uint32_t WG_UNROLL_FACTOR = BLOCK_SIZE > 1 ? 2 : 1;
  3487. BLOCK_SIZE /= WG_UNROLL_FACTOR;
  3488. 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);
  3489. }
  3490. for (uint32_t i = 0; i < num_topk_pipelines; ++i) {
  3491. const uint32_t BLOCK_SIZE = 1u << i;
  3492. const uint32_t NCOLS_PADDED_LOG2 = i;
  3493. if (i <= device->max_workgroup_size_log2) {
  3494. uint32_t nary_shmem = 2 * sizeof(int) * BLOCK_SIZE +
  3495. sizeof(int) * device->subgroup_size +
  3496. 2 * sizeof(int) +
  3497. 2 * (BLOCK_SIZE / device->subgroup_size) * sizeof(int);
  3498. if (device->subgroup_arithmetic && device->subgroup_require_full_support && device->subgroup_shuffle && device->subgroup_ballot &&
  3499. nary_shmem <= device->properties.limits.maxComputeSharedMemorySize) {
  3500. 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);
  3501. } else if (2 * sizeof(int) * BLOCK_SIZE <= device->properties.limits.maxComputeSharedMemorySize) {
  3502. 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);
  3503. }
  3504. }
  3505. }
  3506. 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);
  3507. 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);
  3508. ggml_vk_create_pipeline(device, device->pipeline_cumsum_f32, "cumsum_f32", cumsum_f32_len, cumsum_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { 128, device->subgroup_size }, 1, true, true, device->subgroup_size);
  3509. 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);
  3510. for (auto &s : device->pipeline_solve_tri_f32) {
  3511. const vk_solve_tri_pipeline_state &state = s.first;
  3512. // Max number of rows to load at a time, limited by shared memory
  3513. const uint32_t batch_N = device->properties.limits.maxComputeSharedMemorySize / ((state.N + state.K) * sizeof(float));
  3514. // Need at least K invocations, and prefer a minimum of 128 to spread out loading shared memory
  3515. const uint32_t block_size = std::max(128u, 1u << (uint32_t)ceilf(log2f(float(state.K))));
  3516. ggml_vk_create_pipeline(
  3517. device, s.second, "solve_tri_f32",
  3518. solve_tri_f32_len, solve_tri_f32_data, "main", 3,
  3519. sizeof(vk_op_binary_push_constants), {1, 1, 1}, { 0, state.N, state.K, batch_N, block_size }, 1, true);
  3520. }
  3521. #define IM2COL(bda) \
  3522. 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); \
  3523. 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); \
  3524. if (device->float_controls_rte_fp16) { \
  3525. 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); \
  3526. 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); \
  3527. } else { \
  3528. 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); \
  3529. 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); \
  3530. }
  3531. if (device->shader_int64 && device->buffer_device_address) {
  3532. IM2COL(_bda)
  3533. } else {
  3534. IM2COL()
  3535. }
  3536. 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);
  3537. 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);
  3538. 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);
  3539. 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);
  3540. 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);
  3541. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3542. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 16}, 1, true, true);
  3543. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 16}, 1, true, true);
  3544. } else {
  3545. 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);
  3546. 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);
  3547. }
  3548. 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);
  3549. 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);
  3550. 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);
  3551. // conv2d, conv_transpose_2d
  3552. for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) {
  3553. uint32_t conv2d_WG_SIZE = 256;
  3554. uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices.
  3555. uint32_t conv2d_TS_K = (s == CONV_SHAPE_64x32) ? 4 : 8;
  3556. uint32_t conv2d_SHMEM_PAD = 4;
  3557. vk_conv_block_size conv2d_BS = vk_conv_block_sizes[s];
  3558. bool conv2d_UNROLL = true;
  3559. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3560. if (device->coopmat2) {
  3561. conv2d_SHMEM_PAD = 8; // 8 float16_t
  3562. }
  3563. #endif
  3564. if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3565. conv2d_SHMEM_PAD = 0;
  3566. conv2d_UNROLL = false;
  3567. } else if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3568. conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4;
  3569. if (s == CONV_SHAPE_128x128 && device->architecture != vk_device_architecture::AMD_GCN) {
  3570. conv2d_UNROLL = false;
  3571. }
  3572. }
  3573. // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math.
  3574. bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA ||
  3575. device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  3576. bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD ||
  3577. device->architecture == vk_device_architecture::AMD_GCN;
  3578. if (device->subgroup_shuffle &&
  3579. device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316.
  3580. allow_collectives_nv &&
  3581. allow_collectives_amd) {
  3582. use_collectives = 1;
  3583. conv2d_BS.CRS = std::min(
  3584. device->subgroup_size,
  3585. conv2d_BS.CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used.
  3586. }
  3587. uint32_t conv2d_shmem_req =
  3588. (conv2d_BS.K * (conv2d_BS.CRS + conv2d_SHMEM_PAD) + conv2d_BS.CRS * (conv2d_BS.NPQ + conv2d_SHMEM_PAD)) * sizeof(float);
  3589. if (device->properties.limits.maxComputeSharedMemorySize < conv2d_shmem_req) {
  3590. conv2d_BS.CRS = 8;
  3591. if (use_collectives) {
  3592. conv2d_BS.CRS = std::min(device->subgroup_size, conv2d_BS.CRS);
  3593. }
  3594. }
  3595. std::array<uint32_t, 3> wg_denoms = { conv2d_BS.K, 1, 1 };
  3596. 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 };
  3597. #define CREATE_CONV(name, type_suffix, spv_suffix) \
  3598. for (auto &c : device->pipeline_##name##type_suffix[s]) { \
  3599. const vk_conv2d_pipeline_state &state = c.first; \
  3600. std::vector<uint32_t> spec_constants_cpy = spec_constants; \
  3601. spec_constants_cpy.push_back(state.s0); \
  3602. spec_constants_cpy.push_back(state.s1); \
  3603. spec_constants_cpy.push_back(state.p0); \
  3604. spec_constants_cpy.push_back(state.p1); \
  3605. spec_constants_cpy.push_back(state.d0); \
  3606. spec_constants_cpy.push_back(state.d1); \
  3607. spec_constants_cpy.push_back(state.KW); \
  3608. spec_constants_cpy.push_back(state.KH); \
  3609. ggml_vk_create_pipeline( \
  3610. device, c.second, #name #type_suffix, \
  3611. name##type_suffix##spv_suffix##_len, name##type_suffix##spv_suffix##_data, "main", 3, \
  3612. sizeof(vk_op_conv2d_push_constants), wg_denoms, spec_constants_cpy, 1, true, use_collectives); \
  3613. }
  3614. #define CREATE_CONVS(spv_suffix) \
  3615. CREATE_CONV(conv2d, _f32, spv_suffix) \
  3616. CREATE_CONV(conv2d, _f16_f32, spv_suffix) \
  3617. CREATE_CONV(conv_transpose_2d, _f32, spv_suffix) \
  3618. CREATE_CONV(conv_transpose_2d, _f16_f32, spv_suffix)
  3619. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3620. if (device->coopmat2) {
  3621. CREATE_CONVS(_cm2)
  3622. } else
  3623. #endif
  3624. if (conv2d_UNROLL) {
  3625. CREATE_CONVS(_unroll)
  3626. } else {
  3627. CREATE_CONVS( )
  3628. }
  3629. #undef CREATE_CONV
  3630. #undef CREATE_CONVS
  3631. }
  3632. 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);
  3633. 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);
  3634. 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);
  3635. 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);
  3636. for (uint32_t use_push = 0; use_push < 2; ++use_push) {
  3637. for (uint32_t i = 0; i < num_topk_moe_pipelines; ++i) {
  3638. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_EARLY_SOFTMAX][use_push], "topk_moe_f32_early_softmax_"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 0, 0, use_push}, 1, true, true, device->subgroup_size);
  3639. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_EARLY_SOFTMAX_NORM][use_push], "topk_moe_f32_early_softmax_norm"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 1, 0, use_push}, 1, true, true, device->subgroup_size);
  3640. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_LATE_SOFTMAX][use_push], "topk_moe_f32_late_softmax"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 0, 1, use_push}, 1, true, true, device->subgroup_size);
  3641. }
  3642. }
  3643. for (auto &c : compiles) {
  3644. c.wait();
  3645. }
  3646. }
  3647. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch);
  3648. static vk_device ggml_vk_get_device(size_t idx) {
  3649. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  3650. if (vk_instance.devices[idx] == nullptr) {
  3651. VK_LOG_DEBUG("Initializing new vk_device");
  3652. vk_device device = std::make_shared<vk_device_struct>();
  3653. vk_instance.devices[idx] = device;
  3654. #ifdef GGML_VULKAN_MEMORY_DEBUG
  3655. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  3656. #endif
  3657. size_t dev_num = vk_instance.device_indices[idx];
  3658. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  3659. if (dev_num >= physical_devices.size()) {
  3660. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3661. throw std::runtime_error("Device not found");
  3662. }
  3663. device->physical_device = physical_devices[dev_num];
  3664. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  3665. device->architecture = get_device_architecture(device->physical_device);
  3666. const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY");
  3667. device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr;
  3668. const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM");
  3669. device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr;
  3670. const char* GGML_VK_ALLOW_SYSMEM_FALLBACK = getenv("GGML_VK_ALLOW_SYSMEM_FALLBACK");
  3671. device->allow_sysmem_fallback = GGML_VK_ALLOW_SYSMEM_FALLBACK != nullptr;
  3672. const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE");
  3673. device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr;
  3674. bool fp16_storage = false;
  3675. bool fp16_compute = false;
  3676. bool maintenance4_support = false;
  3677. bool sm_builtins = false;
  3678. bool amd_shader_core_properties2 = false;
  3679. bool pipeline_robustness = false;
  3680. bool coopmat2_support = false;
  3681. bool pipeline_executable_properties_support = false;
  3682. device->coopmat_support = false;
  3683. device->integer_dot_product = false;
  3684. bool bfloat16_support = false;
  3685. for (const auto& properties : ext_props) {
  3686. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  3687. maintenance4_support = true;
  3688. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3689. fp16_storage = true;
  3690. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3691. fp16_compute = true;
  3692. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  3693. sm_builtins = true;
  3694. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  3695. amd_shader_core_properties2 = true;
  3696. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  3697. pipeline_robustness = true;
  3698. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  3699. device->subgroup_size_control = true;
  3700. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3701. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3702. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3703. device->coopmat_support = true;
  3704. device->coopmat_m = 0;
  3705. device->coopmat_n = 0;
  3706. device->coopmat_k = 0;
  3707. #endif
  3708. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3709. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3710. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3711. coopmat2_support = true;
  3712. #endif
  3713. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3714. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3715. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3716. device->integer_dot_product = true;
  3717. #endif
  3718. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3719. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3720. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3721. bfloat16_support = true;
  3722. #endif
  3723. } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) {
  3724. pipeline_executable_properties_support = true;
  3725. } else if (strcmp("VK_EXT_memory_priority", properties.extensionName) == 0 &&
  3726. getenv("GGML_VK_ENABLE_MEMORY_PRIORITY")) {
  3727. device->memory_priority = true;
  3728. }
  3729. }
  3730. vk::PhysicalDeviceProperties2 props2;
  3731. vk::PhysicalDeviceMaintenance3Properties props3;
  3732. vk::PhysicalDeviceMaintenance4Properties props4;
  3733. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3734. vk::PhysicalDeviceDriverProperties driver_props;
  3735. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  3736. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  3737. vk::PhysicalDeviceVulkan11Properties vk11_props;
  3738. vk::PhysicalDeviceVulkan12Properties vk12_props;
  3739. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  3740. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3741. props2.pNext = &props3;
  3742. props3.pNext = &subgroup_props;
  3743. subgroup_props.pNext = &driver_props;
  3744. driver_props.pNext = &vk11_props;
  3745. vk11_props.pNext = &vk12_props;
  3746. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  3747. if (maintenance4_support) {
  3748. last_struct->pNext = (VkBaseOutStructure *)&props4;
  3749. last_struct = (VkBaseOutStructure *)&props4;
  3750. }
  3751. if (sm_builtins) {
  3752. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  3753. last_struct = (VkBaseOutStructure *)&sm_props;
  3754. }
  3755. if (amd_shader_core_properties2) {
  3756. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3757. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3758. }
  3759. if (device->subgroup_size_control) {
  3760. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  3761. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  3762. }
  3763. #if defined(VK_NV_cooperative_matrix2)
  3764. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  3765. if (coopmat2_support) {
  3766. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  3767. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  3768. }
  3769. #endif
  3770. if (device->integer_dot_product) {
  3771. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3772. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3773. }
  3774. device->physical_device.getProperties2(&props2);
  3775. device->properties = props2.properties;
  3776. device->vendor_id = device->properties.vendorID;
  3777. device->driver_id = driver_props.driverID;
  3778. // Implementing the async backend interfaces seems broken on older Intel HW,
  3779. // see https://github.com/ggml-org/llama.cpp/issues/17302.
  3780. device->support_async = (device->vendor_id != VK_VENDOR_ID_INTEL ||
  3781. std::string(device->properties.deviceName.data()).find("(DG1)") == std::string::npos) &&
  3782. getenv("GGML_VK_DISABLE_ASYNC") == nullptr;
  3783. if (!device->support_async) {
  3784. GGML_LOG_DEBUG("ggml_vulkan: WARNING: Async execution disabled on certain Intel devices.\n");
  3785. }
  3786. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  3787. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  3788. device->max_memory_allocation_size = std::stoull(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  3789. } else if (maintenance4_support) {
  3790. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  3791. } else {
  3792. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  3793. }
  3794. const char* GGML_VK_FORCE_MAX_BUFFER_SIZE = getenv("GGML_VK_FORCE_MAX_BUFFER_SIZE");
  3795. if (GGML_VK_FORCE_MAX_BUFFER_SIZE != nullptr) {
  3796. device->max_buffer_size = std::stoull(GGML_VK_FORCE_MAX_BUFFER_SIZE);
  3797. } else if (maintenance4_support) {
  3798. device->max_buffer_size = props4.maxBufferSize;
  3799. } else {
  3800. device->max_buffer_size = device->max_memory_allocation_size;
  3801. }
  3802. const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE");
  3803. if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) {
  3804. device->suballocation_block_size = std::stoull(GGML_VK_SUBALLOCATION_BLOCK_SIZE);
  3805. } else {
  3806. // Limit batching of allocations to 1GB by default to avoid fragmentation issues
  3807. device->suballocation_block_size = 1024*1024*1024;
  3808. }
  3809. device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size);
  3810. device->subgroup_size = subgroup_props.subgroupSize;
  3811. device->subgroup_size_log2 = uint32_t(log2f(float(device->subgroup_size)));
  3812. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3813. if (sm_builtins) {
  3814. device->shader_core_count = sm_props.shaderSMCount;
  3815. } else if (amd_shader_core_properties2) {
  3816. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  3817. } else {
  3818. device->shader_core_count = 0;
  3819. }
  3820. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  3821. device->subgroup_arithmetic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3822. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic);
  3823. #ifdef __APPLE__
  3824. // Workaround for subgroup arithmetic failing on MoltenVK with AMD GPUs (issue 15846)
  3825. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3826. device->subgroup_arithmetic = false;
  3827. }
  3828. #endif
  3829. device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3830. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle);
  3831. device->subgroup_clustered = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3832. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eClustered);
  3833. device->subgroup_ballot = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3834. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBallot);
  3835. device->subgroup_vote = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3836. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eVote);
  3837. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  3838. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  3839. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) {
  3840. device->coopmat_support = false;
  3841. }
  3842. device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated;
  3843. device->max_workgroup_size_log2 = uint32_t(log2f(float(device->properties.limits.maxComputeWorkGroupInvocations)));
  3844. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  3845. // Try to find a non-graphics compute queue and transfer-focused queues
  3846. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  3847. 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);
  3848. const float priorities[] = { 1.0f, 1.0f };
  3849. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  3850. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  3851. if (compute_queue_family_index != transfer_queue_family_index) {
  3852. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3853. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  3854. } else if(!device->single_queue) {
  3855. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  3856. } else {
  3857. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3858. }
  3859. vk::DeviceCreateInfo device_create_info;
  3860. std::vector<const char *> device_extensions;
  3861. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  3862. VkPhysicalDeviceFeatures2 device_features2;
  3863. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  3864. device_features2.pNext = nullptr;
  3865. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  3866. VkPhysicalDeviceVulkan11Features vk11_features;
  3867. vk11_features.pNext = nullptr;
  3868. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  3869. device_features2.pNext = &vk11_features;
  3870. VkPhysicalDeviceVulkan12Features vk12_features;
  3871. vk12_features.pNext = nullptr;
  3872. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  3873. vk11_features.pNext = &vk12_features;
  3874. last_struct = (VkBaseOutStructure *)&vk12_features;
  3875. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  3876. pl_robustness_features.pNext = nullptr;
  3877. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  3878. pl_robustness_features.pipelineRobustness = VK_FALSE;
  3879. if (pipeline_robustness) {
  3880. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  3881. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  3882. device_extensions.push_back("VK_EXT_pipeline_robustness");
  3883. }
  3884. VkPhysicalDeviceMemoryPriorityFeaturesEXT memory_priority_features;
  3885. memory_priority_features.pNext = nullptr;
  3886. memory_priority_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PRIORITY_FEATURES_EXT;
  3887. memory_priority_features.memoryPriority = VK_FALSE;
  3888. if (device->memory_priority) {
  3889. last_struct->pNext = (VkBaseOutStructure *)&memory_priority_features;
  3890. last_struct = (VkBaseOutStructure *)&memory_priority_features;
  3891. device_extensions.push_back("VK_EXT_memory_priority");
  3892. }
  3893. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  3894. subgroup_size_control_features.pNext = nullptr;
  3895. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  3896. subgroup_size_control_features.computeFullSubgroups = false;
  3897. subgroup_size_control_features.subgroupSizeControl = false;
  3898. if (device->subgroup_size_control) {
  3899. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  3900. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  3901. }
  3902. #if defined(VK_KHR_cooperative_matrix)
  3903. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  3904. coopmat_features.pNext = nullptr;
  3905. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  3906. coopmat_features.cooperativeMatrix = VK_FALSE;
  3907. if (device->coopmat_support) {
  3908. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  3909. last_struct = (VkBaseOutStructure *)&coopmat_features;
  3910. }
  3911. #endif
  3912. #if defined(VK_NV_cooperative_matrix2)
  3913. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  3914. coopmat2_features.pNext = nullptr;
  3915. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  3916. if (coopmat2_support) {
  3917. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  3918. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  3919. device_extensions.push_back("VK_NV_cooperative_matrix2");
  3920. }
  3921. #endif
  3922. #if defined(VK_KHR_shader_bfloat16)
  3923. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  3924. bfloat16_features.pNext = nullptr;
  3925. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  3926. if (bfloat16_support) {
  3927. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  3928. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  3929. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3930. }
  3931. #endif
  3932. VkPhysicalDeviceMaintenance4Features maint4_features {};
  3933. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  3934. if (maintenance4_support) {
  3935. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  3936. last_struct = (VkBaseOutStructure *)&maint4_features;
  3937. device_extensions.push_back("VK_KHR_maintenance4");
  3938. }
  3939. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  3940. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  3941. if (device->integer_dot_product) {
  3942. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3943. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3944. device_extensions.push_back("VK_KHR_shader_integer_dot_product");
  3945. }
  3946. VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pep_features {};
  3947. pep_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR;
  3948. if (pipeline_executable_properties_support) {
  3949. last_struct->pNext = (VkBaseOutStructure *)&pep_features;
  3950. last_struct = (VkBaseOutStructure *)&pep_features;
  3951. device_extensions.push_back("VK_KHR_pipeline_executable_properties");
  3952. }
  3953. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  3954. device->pipeline_executable_properties_support = pipeline_executable_properties_support;
  3955. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  3956. #if defined(VK_KHR_shader_bfloat16)
  3957. device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  3958. #else
  3959. device->bf16 = false;
  3960. #endif
  3961. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  3962. device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 &&
  3963. device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) &&
  3964. getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr;
  3965. device->shader_int64 = device_features2.features.shaderInt64;
  3966. device->buffer_device_address = vk12_features.bufferDeviceAddress;
  3967. device->vulkan_memory_model = vk12_features.vulkanMemoryModel;
  3968. if (device->subgroup_size_control) {
  3969. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  3970. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  3971. device_extensions.push_back("VK_EXT_subgroup_size_control");
  3972. }
  3973. device->subgroup_size_control = device->subgroup_size_control &&
  3974. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  3975. subgroup_size_control_features.subgroupSizeControl;
  3976. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  3977. #if defined(VK_KHR_cooperative_matrix)
  3978. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  3979. // coopmat1 fa shader currently assumes 32 invocations per subgroup
  3980. device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support &&
  3981. device->subgroup_size_control && device->subgroup_min_size <= 32 &&
  3982. device->subgroup_max_size >= 32;
  3983. #endif
  3984. if (coopmat2_support) {
  3985. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3986. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  3987. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  3988. coopmat2_features.cooperativeMatrixReductions &&
  3989. coopmat2_features.cooperativeMatrixConversions &&
  3990. coopmat2_features.cooperativeMatrixPerElementOperations &&
  3991. coopmat2_features.cooperativeMatrixTensorAddressing &&
  3992. coopmat2_features.cooperativeMatrixBlockLoads &&
  3993. vk12_features.bufferDeviceAddress) {
  3994. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  3995. uint32_t count = 0;
  3996. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  3997. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  3998. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  3999. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  4000. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  4001. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  4002. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  4003. flexible_dimensions.resize(count, empty_prop);
  4004. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  4005. bool found_fp16_128 = false,
  4006. found_fp16_256 = false,
  4007. found_fp32_128 = false,
  4008. found_fp32_256 = false;
  4009. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  4010. // with 32x16x16 and 256 with 32x32x16.
  4011. for (auto &prop : flexible_dimensions) {
  4012. if (prop.saturatingAccumulation == VK_FALSE &&
  4013. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  4014. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4015. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4016. if (prop.workgroupInvocations == 128 &&
  4017. prop.MGranularity <= 32 &&
  4018. prop.NGranularity <= 16 &&
  4019. prop.KGranularity <= 16) {
  4020. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4021. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4022. found_fp16_128 = true;
  4023. }
  4024. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4025. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  4026. found_fp32_128 = true;
  4027. }
  4028. }
  4029. if (prop.workgroupInvocations == 256 &&
  4030. prop.MGranularity <= 32 &&
  4031. prop.NGranularity <= 32 &&
  4032. prop.KGranularity <= 16) {
  4033. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  4034. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  4035. found_fp16_256 = true;
  4036. }
  4037. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4038. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  4039. found_fp32_256 = true;
  4040. }
  4041. }
  4042. }
  4043. }
  4044. if (found_fp16_128 && found_fp16_256 &&
  4045. found_fp32_128 && found_fp32_256 &&
  4046. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  4047. device->coopmat2 = true;
  4048. }
  4049. }
  4050. #endif
  4051. }
  4052. if (!vk11_features.storageBuffer16BitAccess) {
  4053. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  4054. throw std::runtime_error("Unsupported device");
  4055. }
  4056. device_extensions.push_back("VK_KHR_16bit_storage");
  4057. #ifdef GGML_VULKAN_VALIDATE
  4058. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  4059. #endif
  4060. if (device->fp16) {
  4061. device_extensions.push_back("VK_KHR_shader_float16_int8");
  4062. }
  4063. #if defined(VK_KHR_cooperative_matrix)
  4064. if (device->coopmat_support) {
  4065. // Query supported shapes
  4066. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  4067. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  4068. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  4069. uint32_t cm_props_num;
  4070. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  4071. cm_props.resize(cm_props_num);
  4072. for (auto& prop : cm_props) {
  4073. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  4074. }
  4075. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  4076. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  4077. for (auto& prop : cm_props) {
  4078. 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));
  4079. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  4080. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  4081. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  4082. ) {
  4083. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  4084. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  4085. // coopmat sizes not set yet
  4086. if (device->coopmat_m == 0) {
  4087. device->coopmat_acc_f32_support = true;
  4088. device->coopmat_m = prop.MSize;
  4089. device->coopmat_n = prop.NSize;
  4090. device->coopmat_k = prop.KSize;
  4091. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4092. // Only enable if shape is identical
  4093. device->coopmat_acc_f32_support = true;
  4094. }
  4095. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  4096. device->coopmat_support_16x16x16_f32acc = true;
  4097. }
  4098. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  4099. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  4100. // coopmat sizes not set yet
  4101. if (device->coopmat_m == 0) {
  4102. device->coopmat_acc_f16_support = true;
  4103. device->coopmat_m = prop.MSize;
  4104. device->coopmat_n = prop.NSize;
  4105. device->coopmat_k = prop.KSize;
  4106. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4107. // Only enable if shape is identical
  4108. device->coopmat_acc_f16_support = true;
  4109. }
  4110. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  4111. device->coopmat_support_16x16x16_f16acc = true;
  4112. }
  4113. }
  4114. } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 &&
  4115. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 &&
  4116. (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 &&
  4117. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 &&
  4118. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup &&
  4119. device->coopmat_int_m == 0
  4120. ) {
  4121. device->coopmat_int_support = true;
  4122. device->coopmat_int_m = prop.MSize;
  4123. device->coopmat_int_n = prop.NSize;
  4124. device->coopmat_int_k = prop.KSize;
  4125. }
  4126. #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4127. if (prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  4128. prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  4129. prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4130. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4131. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  4132. ) {
  4133. // coopmat sizes not set yet
  4134. if (device->coopmat_m == 0) {
  4135. device->coopmat_bf16_support = true;
  4136. device->coopmat_m = prop.MSize;
  4137. device->coopmat_n = prop.NSize;
  4138. device->coopmat_k = prop.KSize;
  4139. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4140. // Only enable if shape is identical
  4141. device->coopmat_bf16_support = true;
  4142. }
  4143. }
  4144. #endif
  4145. }
  4146. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  4147. // No suitable matmul mode found
  4148. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  4149. device->coopmat_support = false;
  4150. }
  4151. if (getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4152. device->coopmat_bf16_support = false;
  4153. }
  4154. }
  4155. if (device->coopmat_support) {
  4156. device_extensions.push_back("VK_KHR_cooperative_matrix");
  4157. }
  4158. #if defined(VK_KHR_shader_bfloat16)
  4159. if (device->coopmat_bf16_support) {
  4160. device_extensions.push_back("VK_KHR_shader_bfloat16");
  4161. }
  4162. #endif
  4163. #endif
  4164. device->name = GGML_VK_NAME + std::to_string(idx);
  4165. device_create_info = {
  4166. vk::DeviceCreateFlags(),
  4167. device_queue_create_infos,
  4168. {},
  4169. device_extensions
  4170. };
  4171. device_create_info.setPNext(&device_features2);
  4172. device->device = device->physical_device.createDevice(device_create_info);
  4173. // Queues
  4174. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  4175. // Shaders
  4176. // Disable matmul tile sizes early if performance low or not supported
  4177. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  4178. switch (device->vendor_id) {
  4179. #ifndef GGML_VULKAN_RUN_TESTS
  4180. case VK_VENDOR_ID_AMD:
  4181. case VK_VENDOR_ID_INTEL:
  4182. device->mul_mat_l[i] = false;
  4183. device->mul_mat_m[i] = true;
  4184. device->mul_mat_s[i] = true;
  4185. device->mul_mat_id_l[i] = false;
  4186. device->mul_mat_id_m[i] = true;
  4187. device->mul_mat_id_s[i] = true;
  4188. break;
  4189. case VK_VENDOR_ID_APPLE:
  4190. device->mul_mat_l[i] = false;
  4191. device->mul_mat_m[i] = true;
  4192. device->mul_mat_s[i] = false;
  4193. device->mul_mat_id_l[i] = false;
  4194. device->mul_mat_id_m[i] = true;
  4195. device->mul_mat_id_s[i] = false;
  4196. break;
  4197. #endif
  4198. default:
  4199. device->mul_mat_l[i] = true;
  4200. device->mul_mat_m[i] = true;
  4201. device->mul_mat_s[i] = true;
  4202. device->mul_mat_id_l[i] = true;
  4203. device->mul_mat_id_m[i] = true;
  4204. device->mul_mat_id_s[i] = true;
  4205. break;
  4206. }
  4207. }
  4208. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  4209. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  4210. for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
  4211. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  4212. dsl_binding_flags.push_back({});
  4213. }
  4214. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  4215. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  4216. {},
  4217. dsl_binding);
  4218. descriptor_set_layout_create_info.setPNext(&dslbfci);
  4219. device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  4220. ggml_vk_load_shaders(device);
  4221. if (!device->single_queue) {
  4222. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  4223. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  4224. } else {
  4225. // TODO: Use pointer or reference to avoid copy
  4226. device->transfer_queue.copyFrom(device->compute_queue);
  4227. device->transfer_queue.cmd_pool.init(device, &device->transfer_queue);
  4228. }
  4229. device->buffer_type = {
  4230. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  4231. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  4232. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  4233. };
  4234. device->fence = device->device.createFence({});
  4235. device->idx = idx;
  4236. device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr;
  4237. device->add_rms_fusion = !device->disable_fusion &&
  4238. device->subgroup_arithmetic &&
  4239. device->vendor_id != VK_VENDOR_ID_INTEL;
  4240. device->partials_binding_alignment =
  4241. std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment);
  4242. device->mmvq_mode = 0;
  4243. if (getenv("GGML_VK_DISABLE_MMVQ")) {
  4244. device->mmvq_mode = -1;
  4245. } else if (getenv("GGML_VK_FORCE_MMVQ")) {
  4246. device->mmvq_mode = 1;
  4247. }
  4248. return device;
  4249. }
  4250. return vk_instance.devices[idx];
  4251. }
  4252. static void ggml_vk_print_gpu_info(size_t idx) {
  4253. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4254. size_t dev_num = vk_instance.device_indices[idx];
  4255. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  4256. GGML_ASSERT(vk_instance_initialized);
  4257. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4258. if (dev_num >= devices.size()) {
  4259. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  4260. throw std::runtime_error("Device not found");
  4261. }
  4262. vk::PhysicalDevice physical_device = devices[dev_num];
  4263. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  4264. bool fp16_storage = false;
  4265. bool fp16_compute = false;
  4266. bool coopmat_support = false;
  4267. bool coopmat2_support = false;
  4268. bool integer_dot_product = false;
  4269. bool bfloat16_support = false;
  4270. for (auto properties : ext_props) {
  4271. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  4272. fp16_storage = true;
  4273. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  4274. fp16_compute = true;
  4275. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4276. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  4277. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  4278. coopmat_support = true;
  4279. #endif
  4280. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  4281. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  4282. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  4283. coopmat2_support = true;
  4284. #endif
  4285. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  4286. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  4287. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  4288. integer_dot_product = true;
  4289. #endif
  4290. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4291. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  4292. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4293. bfloat16_support = true;
  4294. #endif
  4295. }
  4296. }
  4297. const vk_device_architecture device_architecture = get_device_architecture(physical_device);
  4298. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  4299. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  4300. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  4301. vk::PhysicalDeviceProperties2 props2;
  4302. vk::PhysicalDeviceMaintenance3Properties props3;
  4303. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  4304. vk::PhysicalDeviceDriverProperties driver_props;
  4305. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  4306. props2.pNext = &props3;
  4307. props3.pNext = &subgroup_props;
  4308. subgroup_props.pNext = &driver_props;
  4309. // Pointer to the last chain element
  4310. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  4311. if (integer_dot_product) {
  4312. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4313. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4314. }
  4315. physical_device.getProperties2(&props2);
  4316. VkPhysicalDeviceFeatures2 device_features2;
  4317. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  4318. device_features2.pNext = nullptr;
  4319. VkPhysicalDeviceVulkan11Features vk11_features;
  4320. vk11_features.pNext = nullptr;
  4321. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  4322. device_features2.pNext = &vk11_features;
  4323. VkPhysicalDeviceVulkan12Features vk12_features;
  4324. vk12_features.pNext = nullptr;
  4325. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  4326. vk11_features.pNext = &vk12_features;
  4327. // Pointer to the last chain element
  4328. last_struct = (VkBaseOutStructure *)&vk12_features;
  4329. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4330. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  4331. coopmat_features.pNext = nullptr;
  4332. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  4333. coopmat_features.cooperativeMatrix = VK_FALSE;
  4334. if (coopmat_support) {
  4335. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  4336. last_struct = (VkBaseOutStructure *)&coopmat_features;
  4337. }
  4338. #endif
  4339. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  4340. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  4341. if (integer_dot_product) {
  4342. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4343. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4344. }
  4345. #if defined(VK_KHR_shader_bfloat16)
  4346. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  4347. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  4348. if (bfloat16_support) {
  4349. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  4350. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  4351. }
  4352. #endif
  4353. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  4354. fp16 = fp16 && vk12_features.shaderFloat16;
  4355. #if defined(VK_KHR_shader_bfloat16)
  4356. bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4357. #else
  4358. bool bf16 = false;
  4359. #endif
  4360. uint32_t default_subgroup_size = get_subgroup_size("", device_architecture);
  4361. const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize;
  4362. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  4363. integer_dot_product = integer_dot_product
  4364. && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated
  4365. && shader_integer_dot_product_features.shaderIntegerDotProduct;
  4366. coopmat_support = coopmat_support
  4367. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4368. && coopmat_features.cooperativeMatrix
  4369. #endif
  4370. && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture);
  4371. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  4372. std::string device_name = props2.properties.deviceName.data();
  4373. 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",
  4374. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, bf16, subgroup_size,
  4375. props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str());
  4376. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  4377. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  4378. }
  4379. }
  4380. static bool ggml_vk_instance_layer_settings_available();
  4381. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  4382. static bool ggml_vk_instance_debug_utils_ext_available(const std::vector<vk::ExtensionProperties> & instance_extensions);
  4383. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev);
  4384. static DispatchLoaderDynamic ggml_vk_default_dispatcher_instance;
  4385. DispatchLoaderDynamic & ggml_vk_default_dispatcher() {
  4386. return ggml_vk_default_dispatcher_instance;
  4387. }
  4388. static void ggml_vk_instance_init() {
  4389. if (vk_instance_initialized) {
  4390. return;
  4391. }
  4392. VK_LOG_DEBUG("ggml_vk_instance_init()");
  4393. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4394. ggml_vk_default_dispatcher_instance.init(vkGetInstanceProcAddr);
  4395. uint32_t api_version = vk::enumerateInstanceVersion();
  4396. if (api_version < VK_API_VERSION_1_2) {
  4397. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  4398. throw vk::SystemError(vk::Result::eErrorFeatureNotPresent, "Vulkan 1.2 required");
  4399. }
  4400. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  4401. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  4402. const bool layer_settings = ggml_vk_instance_layer_settings_available();
  4403. #ifdef __APPLE__
  4404. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  4405. #endif
  4406. const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr;
  4407. std::vector<const char*> layers;
  4408. if (layer_settings) {
  4409. layers.push_back("VK_LAYER_KHRONOS_validation");
  4410. }
  4411. std::vector<const char*> extensions;
  4412. if (layer_settings) {
  4413. extensions.push_back("VK_EXT_layer_settings");
  4414. }
  4415. #ifdef __APPLE__
  4416. if (portability_enumeration_ext) {
  4417. extensions.push_back("VK_KHR_portability_enumeration");
  4418. }
  4419. #endif
  4420. if (debug_utils_ext) {
  4421. extensions.push_back("VK_EXT_debug_utils");
  4422. }
  4423. VkBool32 enable_best_practice = layer_settings;
  4424. std::vector<vk::LayerSettingEXT> settings = {
  4425. {
  4426. "VK_LAYER_KHRONOS_validation",
  4427. "validate_best_practices",
  4428. vk::LayerSettingTypeEXT::eBool32,
  4429. 1,
  4430. &enable_best_practice
  4431. },
  4432. };
  4433. vk::LayerSettingsCreateInfoEXT layer_setting_info(settings);
  4434. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions, &layer_setting_info);
  4435. #ifdef __APPLE__
  4436. if (portability_enumeration_ext) {
  4437. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  4438. }
  4439. #endif
  4440. vk_instance.instance = vk::createInstance(instance_create_info);
  4441. vk_instance_initialized = true;
  4442. if (debug_utils_ext) {
  4443. vk_instance.debug_utils_support = true;
  4444. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT");
  4445. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT");
  4446. vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT");
  4447. vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT");
  4448. vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT");
  4449. vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT");
  4450. }
  4451. vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr;
  4452. const char* GGML_VK_PERF_LOGGER_FREQUENCY = getenv("GGML_VK_PERF_LOGGER_FREQUENCY");
  4453. if (GGML_VK_PERF_LOGGER_FREQUENCY != nullptr) {
  4454. vk_perf_logger_frequency = std::stoul(GGML_VK_PERF_LOGGER_FREQUENCY);
  4455. }
  4456. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4457. VULKAN_HPP_DEFAULT_DISPATCHER.init(vk_instance.instance);
  4458. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4459. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  4460. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  4461. if (devices_env != nullptr) {
  4462. size_t num_available_devices = devices.size();
  4463. std::string devices(devices_env);
  4464. std::replace(devices.begin(), devices.end(), ',', ' ');
  4465. std::stringstream ss(devices);
  4466. size_t tmp;
  4467. while (ss >> tmp) {
  4468. if(tmp >= num_available_devices) {
  4469. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  4470. throw std::runtime_error("Invalid Vulkan device index");
  4471. }
  4472. vk_instance.device_indices.push_back(tmp);
  4473. }
  4474. } else {
  4475. // If no vulkan devices are found, return early
  4476. if (devices.empty()) {
  4477. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4478. return;
  4479. }
  4480. // Default to using all dedicated GPUs
  4481. for (size_t i = 0; i < devices.size(); i++) {
  4482. vk::PhysicalDeviceProperties2 new_props;
  4483. vk::PhysicalDeviceDriverProperties new_driver;
  4484. vk::PhysicalDeviceIDProperties new_id;
  4485. new_props.pNext = &new_driver;
  4486. new_driver.pNext = &new_id;
  4487. devices[i].getProperties2(&new_props);
  4488. if ((new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu || new_props.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) && ggml_vk_device_is_supported(devices[i])) {
  4489. // Check if there are two physical devices corresponding to the same GPU
  4490. auto old_device = std::find_if(
  4491. vk_instance.device_indices.begin(),
  4492. vk_instance.device_indices.end(),
  4493. [&devices, &new_id](const size_t k){
  4494. vk::PhysicalDeviceProperties2 old_props;
  4495. vk::PhysicalDeviceIDProperties old_id;
  4496. old_props.pNext = &old_id;
  4497. devices[k].getProperties2(&old_props);
  4498. bool equals = std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  4499. equals = equals || (
  4500. old_id.deviceLUIDValid && new_id.deviceLUIDValid &&
  4501. std::equal(std::begin(old_id.deviceLUID), std::end(old_id.deviceLUID), std::begin(new_id.deviceLUID))
  4502. );
  4503. return equals;
  4504. }
  4505. );
  4506. if (old_device == vk_instance.device_indices.end()) {
  4507. vk_instance.device_indices.push_back(i);
  4508. } else {
  4509. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  4510. // This can cause error when splitting layers aross the devices, need to keep only 1
  4511. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  4512. vk::PhysicalDeviceProperties2 old_props;
  4513. vk::PhysicalDeviceDriverProperties old_driver;
  4514. old_props.pNext = &old_driver;
  4515. devices[*old_device].getProperties2(&old_props);
  4516. std::map<vk::DriverId, int> driver_priorities {};
  4517. int old_priority = std::numeric_limits<int>::max();
  4518. int new_priority = std::numeric_limits<int>::max();
  4519. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  4520. // Smaller number -> higher priority
  4521. switch (old_props.properties.vendorID) {
  4522. case VK_VENDOR_ID_AMD:
  4523. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  4524. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  4525. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  4526. break;
  4527. case VK_VENDOR_ID_INTEL:
  4528. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  4529. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  4530. break;
  4531. case VK_VENDOR_ID_NVIDIA:
  4532. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  4533. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  4534. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  4535. #endif
  4536. break;
  4537. }
  4538. driver_priorities[vk::DriverId::eMesaDozen] = 100;
  4539. if (driver_priorities.count(old_driver.driverID)) {
  4540. old_priority = driver_priorities[old_driver.driverID];
  4541. }
  4542. if (driver_priorities.count(new_driver.driverID)) {
  4543. new_priority = driver_priorities[new_driver.driverID];
  4544. }
  4545. if (new_priority < old_priority) {
  4546. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  4547. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  4548. vk_instance.device_indices.push_back(i);
  4549. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  4550. }
  4551. else {
  4552. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  4553. }
  4554. }
  4555. }
  4556. }
  4557. // If no GPUs found, fall back to the first non-CPU device.
  4558. // If only CPU devices are available, return without devices.
  4559. if (vk_instance.device_indices.empty()) {
  4560. for (size_t i = 0; i < devices.size(); i++) {
  4561. if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) {
  4562. vk_instance.device_indices.push_back(i);
  4563. break;
  4564. }
  4565. }
  4566. }
  4567. if (vk_instance.device_indices.empty()) {
  4568. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4569. return;
  4570. }
  4571. }
  4572. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  4573. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  4574. vk::PhysicalDevice vkdev = devices[vk_instance.device_indices[i]];
  4575. std::vector<vk::ExtensionProperties> extensionprops = vkdev.enumerateDeviceExtensionProperties();
  4576. bool membudget_supported = false;
  4577. for (const auto & ext : extensionprops) {
  4578. if (strcmp(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, ext.extensionName) == 0) {
  4579. membudget_supported = true;
  4580. break;
  4581. }
  4582. }
  4583. vk_instance.device_supports_membudget.push_back(membudget_supported);
  4584. ggml_vk_print_gpu_info(i);
  4585. }
  4586. }
  4587. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  4588. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  4589. ggml_vk_instance_init();
  4590. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4591. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4592. ctx->device = ggml_vk_get_device(idx);
  4593. ctx->semaphore_idx = 0;
  4594. ctx->event_idx = 0;
  4595. ctx->prealloc_size_x = 0;
  4596. ctx->prealloc_size_y = 0;
  4597. ctx->prealloc_size_split_k = 0;
  4598. // Fixed size of 1KB, for deterministic behavior
  4599. ctx->prealloc_size_add_rms_partials = 1024;
  4600. ctx->fence = ctx->device->device.createFence({});
  4601. ctx->almost_ready_fence = ctx->device->device.createFence({});
  4602. ctx->compute_cmd_pool.init(ctx->device, &ctx->device->compute_queue);
  4603. ctx->transfer_cmd_pool.init(ctx->device, &ctx->device->transfer_queue);
  4604. if (vk_perf_logger_enabled) {
  4605. ctx->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  4606. }
  4607. #ifdef GGML_VULKAN_CHECK_RESULTS
  4608. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  4609. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  4610. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  4611. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  4612. #endif
  4613. }
  4614. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  4615. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  4616. switch (type) {
  4617. case GGML_TYPE_F32:
  4618. case GGML_TYPE_Q4_0:
  4619. case GGML_TYPE_Q4_1:
  4620. case GGML_TYPE_Q5_0:
  4621. case GGML_TYPE_Q5_1:
  4622. case GGML_TYPE_Q8_0:
  4623. case GGML_TYPE_Q2_K:
  4624. case GGML_TYPE_Q3_K:
  4625. case GGML_TYPE_Q4_K:
  4626. case GGML_TYPE_Q5_K:
  4627. case GGML_TYPE_Q6_K:
  4628. case GGML_TYPE_IQ1_S:
  4629. case GGML_TYPE_IQ1_M:
  4630. case GGML_TYPE_IQ2_XXS:
  4631. case GGML_TYPE_IQ2_XS:
  4632. case GGML_TYPE_IQ2_S:
  4633. case GGML_TYPE_IQ3_XXS:
  4634. case GGML_TYPE_IQ3_S:
  4635. case GGML_TYPE_IQ4_XS:
  4636. case GGML_TYPE_IQ4_NL:
  4637. case GGML_TYPE_MXFP4:
  4638. break;
  4639. default:
  4640. return nullptr;
  4641. }
  4642. return ctx->device->pipeline_dequant[type];
  4643. }
  4644. 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) {
  4645. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ", " << prec << ")");
  4646. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4647. return ctx->device->pipeline_matmul_f32;
  4648. }
  4649. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4650. return ctx->device->pipeline_matmul_f32_f16;
  4651. }
  4652. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4653. return ctx->device->pipeline_matmul_bf16;
  4654. }
  4655. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4656. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4657. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  4658. }
  4659. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4660. return ctx->device->pipeline_matmul_f16.f16acc;
  4661. }
  4662. } else {
  4663. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4664. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  4665. }
  4666. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4667. return ctx->device->pipeline_matmul_f16.f32acc;
  4668. }
  4669. }
  4670. // MMQ
  4671. if (src1_type == GGML_TYPE_Q8_1) {
  4672. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1[src0_type].f32acc;
  4673. if (pipelines->is_empty()) {
  4674. return nullptr;
  4675. }
  4676. return pipelines;
  4677. }
  4678. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  4679. return nullptr;
  4680. }
  4681. switch (src0_type) {
  4682. case GGML_TYPE_Q4_0:
  4683. case GGML_TYPE_Q4_1:
  4684. case GGML_TYPE_Q5_0:
  4685. case GGML_TYPE_Q5_1:
  4686. case GGML_TYPE_Q8_0:
  4687. case GGML_TYPE_Q2_K:
  4688. case GGML_TYPE_Q3_K:
  4689. case GGML_TYPE_Q4_K:
  4690. case GGML_TYPE_Q5_K:
  4691. case GGML_TYPE_Q6_K:
  4692. case GGML_TYPE_IQ1_S:
  4693. case GGML_TYPE_IQ1_M:
  4694. case GGML_TYPE_IQ2_XXS:
  4695. case GGML_TYPE_IQ2_XS:
  4696. case GGML_TYPE_IQ2_S:
  4697. case GGML_TYPE_IQ3_XXS:
  4698. case GGML_TYPE_IQ3_S:
  4699. case GGML_TYPE_IQ4_XS:
  4700. case GGML_TYPE_IQ4_NL:
  4701. case GGML_TYPE_MXFP4:
  4702. break;
  4703. default:
  4704. return nullptr;
  4705. }
  4706. if (ctx->device->coopmat2) {
  4707. assert(src1_type == GGML_TYPE_F16);
  4708. 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;
  4709. }
  4710. if (ctx->device->coopmat_support) {
  4711. 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;
  4712. }
  4713. 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;
  4714. }
  4715. 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) {
  4716. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  4717. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1);
  4718. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  4719. if (b_type == GGML_TYPE_Q8_1) {
  4720. switch (a_type) {
  4721. case GGML_TYPE_Q4_0:
  4722. case GGML_TYPE_Q4_1:
  4723. case GGML_TYPE_Q5_0:
  4724. case GGML_TYPE_Q5_1:
  4725. case GGML_TYPE_Q8_0:
  4726. case GGML_TYPE_MXFP4:
  4727. case GGML_TYPE_Q2_K:
  4728. case GGML_TYPE_Q3_K:
  4729. case GGML_TYPE_Q4_K:
  4730. case GGML_TYPE_Q5_K:
  4731. case GGML_TYPE_Q6_K:
  4732. break;
  4733. default:
  4734. return nullptr;
  4735. }
  4736. }
  4737. switch (a_type) {
  4738. case GGML_TYPE_F32:
  4739. case GGML_TYPE_F16:
  4740. case GGML_TYPE_BF16:
  4741. case GGML_TYPE_Q4_0:
  4742. case GGML_TYPE_Q4_1:
  4743. case GGML_TYPE_Q5_0:
  4744. case GGML_TYPE_Q5_1:
  4745. case GGML_TYPE_Q8_0:
  4746. case GGML_TYPE_Q2_K:
  4747. case GGML_TYPE_Q3_K:
  4748. case GGML_TYPE_Q4_K:
  4749. case GGML_TYPE_Q5_K:
  4750. case GGML_TYPE_Q6_K:
  4751. case GGML_TYPE_IQ1_S:
  4752. case GGML_TYPE_IQ1_M:
  4753. case GGML_TYPE_IQ2_XXS:
  4754. case GGML_TYPE_IQ2_XS:
  4755. case GGML_TYPE_IQ2_S:
  4756. case GGML_TYPE_IQ3_XXS:
  4757. case GGML_TYPE_IQ3_S:
  4758. case GGML_TYPE_IQ4_XS:
  4759. case GGML_TYPE_IQ4_NL:
  4760. case GGML_TYPE_MXFP4:
  4761. break;
  4762. default:
  4763. return nullptr;
  4764. }
  4765. // heuristic to choose workgroup size
  4766. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4767. 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) {
  4768. // Prefer larger workgroups when M is small, to spread the work out more
  4769. // and keep more SMs busy.
  4770. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4771. if (a_type == GGML_TYPE_Q6_K) {
  4772. if (m < 4096 && k >= 1024) {
  4773. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4774. }
  4775. } else {
  4776. if (m <= 8192 && k >= 1024) {
  4777. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4778. }
  4779. }
  4780. }
  4781. if (b_type == GGML_TYPE_Q8_1) {
  4782. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4783. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4784. }
  4785. return ctx->device->pipeline_dequant_mul_mat_vec_q8_1_f32[dmmv_wg][a_type][num_cols-1];
  4786. }
  4787. 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];
  4788. }
  4789. 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) {
  4790. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  4791. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4792. return ctx->device->pipeline_matmul_id_f32;
  4793. }
  4794. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4795. return ctx->device->pipeline_matmul_id_bf16;
  4796. }
  4797. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4798. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4799. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  4800. }
  4801. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4802. return ctx->device->pipeline_matmul_id_f16.f16acc;
  4803. }
  4804. } else {
  4805. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4806. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  4807. }
  4808. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4809. return ctx->device->pipeline_matmul_id_f16.f32acc;
  4810. }
  4811. }
  4812. // MMQ
  4813. if (src1_type == GGML_TYPE_Q8_1) {
  4814. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_id_q8_1[src0_type].f32acc;
  4815. if (pipelines->is_empty()) {
  4816. return nullptr;
  4817. }
  4818. return pipelines;
  4819. }
  4820. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  4821. switch (src0_type) {
  4822. case GGML_TYPE_Q4_0:
  4823. case GGML_TYPE_Q4_1:
  4824. case GGML_TYPE_Q5_0:
  4825. case GGML_TYPE_Q5_1:
  4826. case GGML_TYPE_Q8_0:
  4827. case GGML_TYPE_Q2_K:
  4828. case GGML_TYPE_Q3_K:
  4829. case GGML_TYPE_Q4_K:
  4830. case GGML_TYPE_Q5_K:
  4831. case GGML_TYPE_Q6_K:
  4832. case GGML_TYPE_IQ1_S:
  4833. case GGML_TYPE_IQ1_M:
  4834. case GGML_TYPE_IQ2_XXS:
  4835. case GGML_TYPE_IQ2_XS:
  4836. case GGML_TYPE_IQ2_S:
  4837. case GGML_TYPE_IQ3_XXS:
  4838. case GGML_TYPE_IQ3_S:
  4839. case GGML_TYPE_IQ4_XS:
  4840. case GGML_TYPE_IQ4_NL:
  4841. case GGML_TYPE_MXFP4:
  4842. break;
  4843. default:
  4844. return nullptr;
  4845. }
  4846. vk_matmul_pipeline2& mmp = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type];
  4847. // XXX TODO 'prec' is not actually allowed in mul_mat_id.
  4848. bool prefer_fp16acc = ctx->device->fp16 /*&& prec == GGML_PREC_DEFAULT*/;
  4849. bool support_fp16acc = !mmp.f16acc->is_empty();
  4850. bool support_fp32acc = !mmp.f32acc->is_empty();
  4851. if (support_fp16acc && (prefer_fp16acc || !support_fp32acc)) {
  4852. return mmp.f16acc;
  4853. } else {
  4854. GGML_ASSERT(support_fp32acc);
  4855. return mmp.f32acc;
  4856. }
  4857. }
  4858. 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) {
  4859. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()");
  4860. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_Q8_1);
  4861. if (b_type == GGML_TYPE_Q8_1) {
  4862. switch (a_type) {
  4863. case GGML_TYPE_Q4_0:
  4864. case GGML_TYPE_Q4_1:
  4865. case GGML_TYPE_Q5_0:
  4866. case GGML_TYPE_Q5_1:
  4867. case GGML_TYPE_Q8_0:
  4868. case GGML_TYPE_MXFP4:
  4869. case GGML_TYPE_Q2_K:
  4870. case GGML_TYPE_Q3_K:
  4871. case GGML_TYPE_Q4_K:
  4872. case GGML_TYPE_Q5_K:
  4873. case GGML_TYPE_Q6_K:
  4874. break;
  4875. default:
  4876. return nullptr;
  4877. }
  4878. }
  4879. switch (a_type) {
  4880. case GGML_TYPE_F32:
  4881. case GGML_TYPE_F16:
  4882. case GGML_TYPE_BF16:
  4883. case GGML_TYPE_Q4_0:
  4884. case GGML_TYPE_Q4_1:
  4885. case GGML_TYPE_Q5_0:
  4886. case GGML_TYPE_Q5_1:
  4887. case GGML_TYPE_Q8_0:
  4888. case GGML_TYPE_Q2_K:
  4889. case GGML_TYPE_Q3_K:
  4890. case GGML_TYPE_Q4_K:
  4891. case GGML_TYPE_Q5_K:
  4892. case GGML_TYPE_Q6_K:
  4893. case GGML_TYPE_IQ1_S:
  4894. case GGML_TYPE_IQ1_M:
  4895. case GGML_TYPE_IQ2_XXS:
  4896. case GGML_TYPE_IQ2_XS:
  4897. case GGML_TYPE_IQ2_S:
  4898. case GGML_TYPE_IQ3_XXS:
  4899. case GGML_TYPE_IQ3_S:
  4900. case GGML_TYPE_IQ4_XS:
  4901. case GGML_TYPE_IQ4_NL:
  4902. case GGML_TYPE_MXFP4:
  4903. break;
  4904. default:
  4905. return nullptr;
  4906. }
  4907. // heuristic to choose workgroup size
  4908. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4909. 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) {
  4910. // Prefer larger workgroups when M is small, to spread the work out more
  4911. // and keep more SMs busy.
  4912. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4913. if (a_type == GGML_TYPE_Q6_K) {
  4914. if (m < 4096 && k >= 1024) {
  4915. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4916. }
  4917. } else {
  4918. if (m <= 8192 && k >= 1024) {
  4919. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4920. }
  4921. }
  4922. }
  4923. if (b_type == GGML_TYPE_Q8_1) {
  4924. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4925. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4926. }
  4927. return ctx->device->pipeline_dequant_mul_mat_vec_id_q8_1_f32[dmmv_wg][a_type];
  4928. }
  4929. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[dmmv_wg][a_type];
  4930. }
  4931. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  4932. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  4933. vk_buffer buf = ggml_vk_create_buffer(device, size,
  4934. {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4935. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  4936. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  4937. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  4938. size/1024.0/1024.0);
  4939. device->device.freeMemory(buf->device_memory);
  4940. device->device.destroyBuffer(buf->buffer);
  4941. return nullptr;
  4942. }
  4943. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4944. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  4945. return buf->ptr;
  4946. }
  4947. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  4948. if (ptr == nullptr) {
  4949. return;
  4950. }
  4951. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  4952. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4953. vk_buffer buf;
  4954. size_t index;
  4955. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4956. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4957. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4958. if (ptr >= addr && ptr < endr) {
  4959. buf = std::get<2>(device->pinned_memory[i]);
  4960. index = i;
  4961. break;
  4962. }
  4963. }
  4964. if (buf == nullptr) {
  4965. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  4966. return;
  4967. }
  4968. ggml_vk_destroy_buffer(buf);
  4969. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  4970. }
  4971. static void ggml_vk_host_get(const vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  4972. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4973. buf = nullptr;
  4974. buf_offset = 0;
  4975. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4976. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4977. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4978. if (ptr >= addr && ptr < endr) {
  4979. buf = std::get<2>(device->pinned_memory[i]);
  4980. buf_offset = ((const uint8_t *)ptr) - addr;
  4981. break;
  4982. }
  4983. }
  4984. }
  4985. static vk_subbuffer ggml_vk_tensor_subbuffer(
  4986. const ggml_backend_vk_context * ctx, const ggml_tensor * tensor, bool allow_misalign = false) {
  4987. vk_buffer buffer = nullptr;
  4988. size_t offset = 0;
  4989. if (ctx->device->uma) {
  4990. ggml_vk_host_get(ctx->device, tensor->data, buffer, offset);
  4991. }
  4992. if (!buffer) {
  4993. auto buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  4994. buffer = buf_ctx->dev_buffer;
  4995. offset = vk_tensor_offset(tensor) + tensor->view_offs;
  4996. }
  4997. GGML_ASSERT(buffer != nullptr);
  4998. size_t size = ggml_nbytes(tensor);
  4999. size_t misalign_bytes = offset & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  5000. // The shader must support misaligned offsets when indexing into the buffer
  5001. GGML_ASSERT(allow_misalign || misalign_bytes == 0);
  5002. offset &= ~misalign_bytes;
  5003. size += misalign_bytes;
  5004. return vk_subbuffer{buffer, offset, size};
  5005. }
  5006. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) {
  5007. vk_submission s;
  5008. s.buffer = ggml_vk_create_cmd_buffer(device, p);
  5009. if (one_time) {
  5010. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  5011. } else {
  5012. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  5013. }
  5014. return s;
  5015. }
  5016. template <typename T> size_t push_constant_size(const T &t) {
  5017. static_assert(std::is_class<T>::value, "T must be a struct/class");
  5018. GGML_UNUSED(t);
  5019. return sizeof(T);
  5020. }
  5021. template <typename T> size_t push_constant_size(const std::vector<T> &t) {
  5022. GGML_UNUSED(t);
  5023. return sizeof(T) * t.size();
  5024. }
  5025. template <typename T, uint32_t N> size_t push_constant_size(const std::array<T, N> &t) {
  5026. GGML_UNUSED(t);
  5027. return sizeof(T) * N;
  5028. }
  5029. template <typename T> const T *push_constant_data(const T &t) {
  5030. static_assert(std::is_class<T>::value, "T must be a struct/class");
  5031. return &t;
  5032. }
  5033. template <typename T> const T *push_constant_data(const std::vector<T> &t) {
  5034. return t.data();
  5035. }
  5036. template <typename T, uint32_t N> const T *push_constant_data(const std::array<T, N> &t) {
  5037. return t.data();
  5038. }
  5039. template <typename T>
  5040. 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) {
  5041. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  5042. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  5043. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  5044. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  5045. for (auto& buffer : descriptor_buffer_infos) {
  5046. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  5047. }
  5048. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  5049. GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size());
  5050. GGML_ASSERT(descriptor_buffer_infos.size() <= MAX_PARAMETER_COUNT);
  5051. GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size());
  5052. vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[ctx->descriptor_set_idx++];
  5053. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  5054. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  5055. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size(push_constants), push_constant_data(push_constants));
  5056. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  5057. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  5058. pipeline->layout,
  5059. 0,
  5060. { descriptor_set },
  5061. {});
  5062. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  5063. }
  5064. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  5065. s.buffer.end();
  5066. s.wait_semaphores = std::move(wait_semaphores);
  5067. s.signal_semaphores = std::move(signal_semaphores);
  5068. }
  5069. static void ggml_vk_ctx_end(vk_context& ctx) {
  5070. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  5071. if (ctx->s == nullptr) {
  5072. return;
  5073. }
  5074. ctx->s->buffer.end();
  5075. ctx->s = nullptr;
  5076. }
  5077. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  5078. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  5079. if (subctx->s != nullptr) {
  5080. ggml_vk_ctx_end(subctx);
  5081. }
  5082. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) });
  5083. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  5084. }
  5085. static size_t ggml_vk_align_size(size_t width, size_t align) {
  5086. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  5087. return CEIL_DIV(width, align) * align;
  5088. }
  5089. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  5090. if (memcpys == nullptr) {
  5091. memcpy(dst, src, size);
  5092. } else {
  5093. memcpys->emplace_back(dst, src, size);
  5094. }
  5095. }
  5096. static void deferred_memset(void * dst, uint32_t val, size_t size, std::vector<vk_staging_memset>* memsets = nullptr) {
  5097. if (memsets == nullptr) {
  5098. memset(dst, val, size);
  5099. } else {
  5100. memsets->emplace_back(dst, val, size);
  5101. }
  5102. }
  5103. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  5104. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  5105. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  5106. ggml_vk_destroy_buffer(device->sync_staging);
  5107. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  5108. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  5109. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  5110. }
  5111. }
  5112. static void ggml_vk_ensure_sync_staging_buffer(ggml_backend_vk_context * ctx, size_t size) {
  5113. if (ctx->sync_staging == nullptr || ctx->sync_staging->size < size) {
  5114. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  5115. ggml_vk_destroy_buffer(ctx->sync_staging);
  5116. ctx->sync_staging = ggml_vk_create_buffer_check(ctx->device, size,
  5117. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  5118. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  5119. }
  5120. }
  5121. 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) {
  5122. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  5123. GGML_ASSERT(!ggml_is_contiguous(tensor));
  5124. // Buffer is already mapped
  5125. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5126. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  5127. GGML_ABORT("fatal error");
  5128. }
  5129. // Check if src is pinned memory
  5130. vk_buffer buf = nullptr;
  5131. size_t buf_offset = 0;
  5132. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  5133. const uint64_t ne0 = tensor->ne[0];
  5134. const uint64_t ne1 = tensor->ne[1];
  5135. const uint64_t ne2 = tensor->ne[2];
  5136. const uint64_t ne3 = tensor->ne[3];
  5137. const uint64_t nb0 = tensor->nb[0];
  5138. const uint64_t nb1 = tensor->nb[1];
  5139. const uint64_t nb2 = tensor->nb[2];
  5140. const uint64_t nb3 = tensor->nb[3];
  5141. const ggml_type type = tensor->type;
  5142. const uint64_t ts = ggml_type_size(type);
  5143. const uint64_t bs = ggml_blck_size(type);
  5144. const uint64_t dstnb0 = ts;
  5145. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  5146. const uint64_t dstnb2 = dstnb1*ne1;
  5147. const uint64_t dstnb3 = dstnb2*ne2;
  5148. const uint64_t ne = ggml_nelements(tensor);
  5149. if (buf != nullptr) {
  5150. // Memory is pinned, use as staging buffer
  5151. std::vector<vk::BufferCopy> slices;
  5152. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  5153. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  5154. // Find longest contiguous slice
  5155. if (ne1*nb1 == dstnb2) {
  5156. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  5157. } else {
  5158. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  5159. if (ne0*nb0/bs == dstnb1) {
  5160. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  5161. } else {
  5162. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  5163. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  5164. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  5165. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  5166. }
  5167. }
  5168. }
  5169. }
  5170. }
  5171. }
  5172. ggml_vk_sync_buffers(ctx, subctx);
  5173. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  5174. return;
  5175. }
  5176. if (!sync_staging) {
  5177. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  5178. }
  5179. // Staging buffer required
  5180. vk_buffer& staging = ctx->device->sync_staging;
  5181. const uint64_t copy_size = ts*ne/bs;
  5182. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  5183. VkBufferCopy buf_copy{ 0, offset, copy_size };
  5184. ggml_vk_sync_buffers(ctx, subctx);
  5185. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  5186. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  5187. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  5188. // Find longest contiguous slice
  5189. if (ne1*nb1 == dstnb2) {
  5190. 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);
  5191. } else {
  5192. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  5193. if (ne0*nb0/bs == dstnb1) {
  5194. 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);
  5195. } else {
  5196. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  5197. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  5198. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  5199. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  5200. }
  5201. }
  5202. }
  5203. }
  5204. }
  5205. }
  5206. }
  5207. static void ggml_vk_buffer_write_2d_async(vk_context subctx, vk_buffer& dst, size_t offset, const void * src, size_t spitch, size_t width, size_t height, bool sync_staging = false) {
  5208. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  5209. // Buffer is already mapped
  5210. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5211. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  5212. GGML_ABORT("fatal error");
  5213. }
  5214. // Check if src is pinned memory
  5215. vk_buffer buf = nullptr;
  5216. size_t buf_offset = 0;
  5217. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  5218. if (buf != nullptr) {
  5219. // Memory is pinned, use as staging buffer
  5220. std::vector<vk::BufferCopy> slices(1);
  5221. if (width == spitch) {
  5222. // Only do single write if stride is equal
  5223. slices[0].srcOffset = buf_offset;
  5224. slices[0].dstOffset = offset;
  5225. slices[0].size = width * height;
  5226. } else {
  5227. slices.resize(height);
  5228. for (size_t i = 0; i < height; i++) {
  5229. slices[i].srcOffset = buf_offset + i * spitch;
  5230. slices[i].dstOffset = offset + i * width;
  5231. slices[i].size = width;
  5232. }
  5233. }
  5234. ggml_vk_sync_buffers(nullptr, subctx);
  5235. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  5236. return;
  5237. }
  5238. VK_LOG_DEBUG("STAGING");
  5239. if (!sync_staging) {
  5240. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  5241. }
  5242. // Staging buffer required
  5243. const size_t copy_size = width*height;
  5244. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  5245. vk_buffer& staging_buffer = dst->device->sync_staging;
  5246. VkBufferCopy buf_copy = {
  5247. 0,
  5248. offset,
  5249. copy_size};
  5250. ggml_vk_sync_buffers(nullptr, subctx);
  5251. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  5252. if (width == spitch) {
  5253. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  5254. } else {
  5255. for (size_t i = 0; i < height; i++) {
  5256. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  5257. }
  5258. }
  5259. }
  5260. static void ggml_vk_buffer_write_async(vk_context subctx, vk_buffer& dst, size_t offset, const void * src, size_t size, bool sync_staging = false) {
  5261. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  5262. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  5263. }
  5264. 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) {
  5265. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  5266. // Buffer is already mapped
  5267. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5268. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5269. for (size_t i = 0; i < height; i++) {
  5270. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  5271. }
  5272. } else {
  5273. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5274. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5275. ggml_vk_ctx_begin(dst->device, subctx);
  5276. ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  5277. ggml_vk_ctx_end(subctx);
  5278. for (auto& cpy : subctx->in_memcpys) {
  5279. memcpy(cpy.dst, cpy.src, cpy.n);
  5280. }
  5281. for (auto& mset : subctx->memsets) {
  5282. memset(mset.dst, mset.val, mset.n);
  5283. }
  5284. ggml_vk_submit(subctx, dst->device->fence);
  5285. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  5286. dst->device->device.resetFences({ dst->device->fence });
  5287. ggml_vk_queue_command_pools_cleanup(dst->device);
  5288. }
  5289. }
  5290. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  5291. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  5292. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  5293. }
  5294. 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) {
  5295. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  5296. GGML_ASSERT(width > 0);
  5297. GGML_ASSERT(height > 0);
  5298. GGML_ASSERT(src != nullptr);
  5299. // TODO: staging_offset is not used
  5300. // Check if dst is pinned memory
  5301. vk_buffer buf = nullptr;
  5302. size_t buf_offset = 0;
  5303. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  5304. std::vector<vk::BufferCopy> slices(1);
  5305. if (width == spitch && width == dpitch) {
  5306. // Only do single write if stride is equal
  5307. slices[0].srcOffset = offset;
  5308. slices[0].dstOffset = buf_offset;
  5309. slices[0].size = width * height;
  5310. } else {
  5311. slices.resize(height);
  5312. for (size_t i = 0; i < height; i++) {
  5313. slices[i].srcOffset = offset + i * spitch;
  5314. slices[i].dstOffset = buf_offset + i * dpitch;
  5315. slices[i].size = width;
  5316. }
  5317. }
  5318. if (buf != nullptr) {
  5319. // Memory is pinned, use as staging buffer
  5320. ggml_vk_sync_buffers(nullptr, subctx);
  5321. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  5322. return true;
  5323. }
  5324. VK_LOG_DEBUG("STAGING");
  5325. if (!sync_staging) {
  5326. // copy was not handled caller needs to fall back
  5327. return false;
  5328. }
  5329. // Fall back to staging buffer
  5330. const size_t copy_size = dpitch * height;
  5331. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  5332. vk_buffer& staging_buffer = src->device->sync_staging;
  5333. ggml_vk_sync_buffers(nullptr, subctx);
  5334. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  5335. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  5336. return true;
  5337. }
  5338. 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) {
  5339. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  5340. }
  5341. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  5342. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  5343. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  5344. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  5345. // the HW device to host copy path.
  5346. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  5347. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5348. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  5349. } else {
  5350. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5351. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5352. ggml_vk_ctx_begin(src->device, subctx);
  5353. bool ret = ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  5354. GGML_ASSERT(ret);
  5355. ggml_vk_ctx_end(subctx);
  5356. ggml_vk_submit(subctx, src->device->fence);
  5357. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  5358. src->device->device.resetFences({ src->device->fence });
  5359. ggml_vk_queue_command_pools_cleanup(src->device);
  5360. for (auto& cpy : subctx->out_memcpys) {
  5361. memcpy(cpy.dst, cpy.src, cpy.n);
  5362. }
  5363. }
  5364. }
  5365. 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) {
  5366. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  5367. // Make sure both buffers are on same device
  5368. GGML_ASSERT(src->device == dst->device);
  5369. VkBufferCopy bc{ src_offset, dst_offset, size };
  5370. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  5371. }
  5372. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  5373. if (src->device == dst->device) {
  5374. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5375. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  5376. // Copy within the device
  5377. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5378. ggml_vk_ctx_begin(src->device, subctx);
  5379. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  5380. ggml_vk_ctx_end(subctx);
  5381. ggml_vk_submit(subctx, src->device->fence);
  5382. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  5383. src->device->device.resetFences({ src->device->fence });
  5384. ggml_vk_queue_command_pools_cleanup(src->device);
  5385. } else {
  5386. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  5387. // Copy device to device
  5388. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  5389. // Copy to src staging buffer
  5390. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  5391. // Copy to dst buffer
  5392. ggml_vk_buffer_write_2d(dst, dst_offset, src->device->sync_staging->ptr, 0, size, 1);
  5393. }
  5394. }
  5395. static void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5396. VK_LOG_DEBUG("ggml_vk_buffer_memset_async(" << offset << ", " << c << ", " << size << ")");
  5397. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5398. dst->device->uma) {
  5399. deferred_memset((uint8_t*)dst->ptr + offset, c, size, &ctx->memsets);
  5400. return;
  5401. }
  5402. // Fall back to GPU fillBuffer for non-UMA or non-host-visible buffers
  5403. ctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5404. }
  5405. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5406. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  5407. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5408. dst->device->uma) {
  5409. memset((uint8_t*)dst->ptr + offset, c, size);
  5410. return;
  5411. }
  5412. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5413. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5414. ggml_vk_ctx_begin(dst->device, subctx);
  5415. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5416. ggml_vk_ctx_end(subctx);
  5417. ggml_vk_submit(subctx, dst->device->fence);
  5418. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  5419. dst->device->device.resetFences({ dst->device->fence });
  5420. ggml_vk_queue_command_pools_cleanup(dst->device);
  5421. }
  5422. 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) {
  5423. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ", " << disable_split_k << ")");
  5424. if (disable_split_k) {
  5425. return 1;
  5426. }
  5427. uint32_t split_k = 1;
  5428. if (ctx->device->shader_core_count != 0 && m >= pipeline->wg_denoms[0] && n >= pipeline->wg_denoms[1]) {
  5429. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  5430. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  5431. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  5432. if (k >= 2048) {
  5433. if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) {
  5434. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  5435. } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) {
  5436. split_k = 3;
  5437. }
  5438. // Cap the split at 8x. Unless k is huge this is a lot of overhead.
  5439. split_k = std::min(split_k, 8u);
  5440. // ggml_vk_matmul will align the splits to be a multiple of 256.
  5441. // If this rounded up size would cause the last split to be empty,
  5442. // then reduce the split count.
  5443. while (true) {
  5444. if (split_k == 1) {
  5445. break;
  5446. }
  5447. uint32_t k_split = CEIL_DIV(k, split_k);
  5448. k_split = ROUNDUP_POW2(k_split, 256);
  5449. if (k_split * (split_k - 1) < k) {
  5450. break;
  5451. }
  5452. split_k--;
  5453. }
  5454. }
  5455. }
  5456. return split_k;
  5457. }
  5458. 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) {
  5459. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5460. if (ctx->device->coopmat2) {
  5461. const uint32_t shader_core_count = ctx->device->shader_core_count;
  5462. const uint32_t tiles_l = CEIL_DIV(m, mmp->a_l->wg_denoms[0]) * CEIL_DIV(n, mmp->a_l->wg_denoms[1]);
  5463. const uint32_t tiles_m = CEIL_DIV(m, mmp->a_m->wg_denoms[0]) * CEIL_DIV(n, mmp->a_m->wg_denoms[1]);
  5464. // Use large shader when the N dimension is greater than the medium shader's tile size
  5465. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5466. // Prefer large over medium if either:
  5467. // - medium or large tiles would overfill the GPU
  5468. // - large tiles with a split_k==3 fits in the GPU and medium tiles with split_k==2 does not
  5469. // (medium with split_k==2 is probably better if it fits - more workgroups running and less split_k overhead)
  5470. bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count ||
  5471. // split_k==3 with large tiles likely better than medium tiles with no split_k.
  5472. (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2);
  5473. 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])) {
  5474. return aligned ? mmp->a_l : mmp->l;
  5475. }
  5476. // Use medium shader when the N dimension is greater than the small shader's tile size
  5477. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5478. if ((ctx->device->mul_mat_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_s[src0_type]) {
  5479. return aligned ? mmp->a_m : mmp->m;
  5480. }
  5481. return aligned ? mmp->a_s : mmp->s;
  5482. }
  5483. 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])) {
  5484. return aligned ? mmp->a_s : mmp->s;
  5485. }
  5486. if ((ctx->device->mul_mat_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l[src0_type]) {
  5487. return aligned ? mmp->a_m : mmp->m;
  5488. }
  5489. return aligned ? mmp->a_l : mmp->l;
  5490. GGML_UNUSED(src1_type);
  5491. }
  5492. 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) {
  5493. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5494. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, src0_type, src1_type)->align;
  5495. }
  5496. static void ggml_vk_matmul(
  5497. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5498. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  5499. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5500. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5501. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3,
  5502. uint32_t padded_n) {
  5503. 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 << ")");
  5504. if (split_k == 1) {
  5505. 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 };
  5506. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc, { m, n, batch });
  5507. return;
  5508. }
  5509. if (ctx->prealloc_split_k_need_sync) {
  5510. ggml_vk_sync_buffers(ctx, subctx);
  5511. }
  5512. GGML_ASSERT(batch_stride_d == m * n);
  5513. // Round the split size up to a multiple of 256 (k-quant alignment)
  5514. uint32_t k_split = CEIL_DIV(k, split_k);
  5515. k_split = ROUNDUP_POW2(k_split, 256);
  5516. 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 };
  5517. // Make sure enough workgroups get assigned for split k to work
  5518. 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 });
  5519. ggml_vk_sync_buffers(ctx, subctx);
  5520. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  5521. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 });
  5522. ctx->prealloc_split_k_need_sync = true;
  5523. }
  5524. 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) {
  5525. VK_LOG_DEBUG("ggml_vk_guess_matmul_id_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ")");
  5526. if (ctx->device->coopmat2) {
  5527. // Use large shader when the N dimension is greater than the medium shader's tile size
  5528. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5529. 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])) {
  5530. return aligned ? mmp->a_l : mmp->l;
  5531. }
  5532. // Use medium shader when the N dimension is greater than the small shader's tile size
  5533. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5534. if ((ctx->device->mul_mat_id_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_id_s[src0_type]) {
  5535. return aligned ? mmp->a_m : mmp->m;
  5536. }
  5537. return aligned ? mmp->a_s : mmp->s;
  5538. }
  5539. 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])) {
  5540. return aligned ? mmp->a_s : mmp->s;
  5541. }
  5542. if ((ctx->device->mul_mat_id_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l[src0_type]) {
  5543. return aligned ? mmp->a_m : mmp->m;
  5544. }
  5545. return aligned ? mmp->a_l : mmp->l;
  5546. }
  5547. 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) {
  5548. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ")");
  5549. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true, src0_type)->align;
  5550. }
  5551. static void ggml_vk_matmul_id(
  5552. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5553. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  5554. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5555. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5556. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11,
  5557. uint32_t padded_n) {
  5558. 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 << "), " <<
  5559. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  5560. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  5561. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  5562. 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,
  5563. nei0, nei1, nbi1, ne11, padded_n };
  5564. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, pc, { m, nei1, n_as });
  5565. }
  5566. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  5567. return
  5568. tensor->nb[0] == ggml_type_size(tensor->type) &&
  5569. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  5570. (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]);
  5571. }
  5572. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  5573. // Choose "contiguous copy" shader if src/dst are contiguous
  5574. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  5575. // Use optimized "transpose" shader if src dim1 is the innermost dimension.
  5576. bool transpose = dst && src->nb[1] == ggml_type_size(to) && ggml_are_same_shape(dst, src);
  5577. if (transpose && src->type == to) {
  5578. if (ggml_type_size(to) == 4) {
  5579. return ctx->device->pipeline_cpy_transpose_32;
  5580. } else if (ggml_type_size(to) == 2) {
  5581. return ctx->device->pipeline_cpy_transpose_16;
  5582. }
  5583. }
  5584. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  5585. if (contig) {
  5586. return ctx->device->pipeline_contig_cpy_f32_f32;
  5587. } else {
  5588. return ctx->device->pipeline_cpy_f32_f32;
  5589. }
  5590. }
  5591. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  5592. if (contig) {
  5593. return ctx->device->pipeline_contig_cpy_f32_f16;
  5594. } else {
  5595. return ctx->device->pipeline_cpy_f32_f16;
  5596. }
  5597. }
  5598. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  5599. if (contig) {
  5600. return ctx->device->pipeline_contig_cpy_f16_f16;
  5601. } else {
  5602. return ctx->device->pipeline_cpy_f16_f16;
  5603. }
  5604. }
  5605. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) {
  5606. if (contig) {
  5607. return ctx->device->pipeline_contig_cpy_f16_f32;
  5608. } else {
  5609. return ctx->device->pipeline_cpy_f16_f32;
  5610. }
  5611. }
  5612. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) {
  5613. if (contig) {
  5614. return ctx->device->pipeline_contig_cpy_f32_bf16;
  5615. } else {
  5616. return ctx->device->pipeline_cpy_f32_bf16;
  5617. }
  5618. }
  5619. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
  5620. if (contig) {
  5621. return ctx->device->pipeline_contig_cpy_f32_i32;
  5622. } else {
  5623. return ctx->device->pipeline_cpy_f32_i32;
  5624. }
  5625. }
  5626. if (src->type == GGML_TYPE_I32 && to == GGML_TYPE_F32) {
  5627. if (contig) {
  5628. return ctx->device->pipeline_contig_cpy_i32_f32;
  5629. } else {
  5630. return ctx->device->pipeline_cpy_i32_f32;
  5631. }
  5632. }
  5633. if (src->type == GGML_TYPE_F32) {
  5634. switch (to) {
  5635. case GGML_TYPE_Q4_0:
  5636. case GGML_TYPE_Q4_1:
  5637. case GGML_TYPE_Q5_0:
  5638. case GGML_TYPE_Q5_1:
  5639. case GGML_TYPE_Q8_0:
  5640. case GGML_TYPE_IQ4_NL:
  5641. return ctx->device->pipeline_cpy_f32_quant[to];
  5642. default:
  5643. break;
  5644. }
  5645. }
  5646. if (to == GGML_TYPE_F32) {
  5647. switch (src->type) {
  5648. case GGML_TYPE_Q4_0:
  5649. case GGML_TYPE_Q4_1:
  5650. case GGML_TYPE_Q5_0:
  5651. case GGML_TYPE_Q5_1:
  5652. case GGML_TYPE_Q8_0:
  5653. case GGML_TYPE_IQ4_NL:
  5654. return ctx->device->pipeline_cpy_quant_f32[src->type];
  5655. default:
  5656. break;
  5657. }
  5658. }
  5659. if (src->type == to) {
  5660. // Copy two or four bytes at a time, depending on block size.
  5661. // For quantized types, we scale by block size/type size. But
  5662. // this path is also used for bf16->bf16 for example, where the
  5663. // type size must be exactly 2 or 4.
  5664. GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4);
  5665. if ((ggml_type_size(src->type) % 4) == 0) {
  5666. if (contig) {
  5667. return ctx->device->pipeline_contig_cpy_f32_f32;
  5668. } else {
  5669. return ctx->device->pipeline_cpy_f32_f32;
  5670. }
  5671. } else {
  5672. if (contig) {
  5673. return ctx->device->pipeline_contig_cpy_f16_f16;
  5674. } else {
  5675. return ctx->device->pipeline_cpy_f16_f16;
  5676. }
  5677. }
  5678. }
  5679. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  5680. GGML_ABORT("fatal error");
  5681. }
  5682. 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) {
  5683. 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] << "), ";
  5684. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  5685. const int tensor_type_size = ggml_type_size(tensor->type);
  5686. const uint32_t ne = ggml_nelements(tensor);
  5687. std::array<uint32_t, 3> elements;
  5688. if (ne > 262144) {
  5689. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  5690. } else if (ne > 512) {
  5691. elements = { 512, CEIL_DIV(ne, 512), 1 };
  5692. } else {
  5693. elements = { ne, 1, 1 };
  5694. }
  5695. vk_op_unary_push_constants pc = {
  5696. (uint32_t)ne,
  5697. (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,
  5698. (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]),
  5699. 0,
  5700. 0.0f, 0.0f,
  5701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5702. };
  5703. init_pushconst_fastdiv(pc);
  5704. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements);
  5705. ggml_vk_sync_buffers(ctx, subctx);
  5706. }
  5707. static vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type) {
  5708. switch(type) {
  5709. case GGML_TYPE_Q8_1:
  5710. return ctx->device->pipeline_quantize_q8_1_x4;
  5711. default:
  5712. std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl;
  5713. GGML_ABORT("fatal error");
  5714. }
  5715. }
  5716. 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) {
  5717. VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")");
  5718. vk_pipeline pipeline = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5719. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, std::array<uint32_t, 1>{ne}, { ne, 1, 1 });
  5720. ggml_vk_sync_buffers(ctx, subctx);
  5721. }
  5722. 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) {
  5723. 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];
  5724. 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];
  5725. 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];
  5726. std::cerr << "))");
  5727. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5728. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5729. const uint64_t ne00 = src0->ne[0];
  5730. const uint64_t ne01 = src0->ne[1];
  5731. const uint64_t ne02 = src0->ne[2];
  5732. const uint64_t ne03 = src0->ne[3];
  5733. const uint64_t ne10 = src1->ne[0];
  5734. const uint64_t ne11 = src1->ne[1];
  5735. const uint64_t ne12 = src1->ne[2];
  5736. const uint64_t ne13 = src1->ne[3];
  5737. const uint64_t ne21 = dst->ne[1];
  5738. const uint32_t stride_d = dst->nb[1] / ggml_type_size(dst->type);
  5739. const uint32_t stride_batch_d = stride_d*ne21;
  5740. const uint64_t r2 = ne12 / ne02;
  5741. const uint64_t r3 = ne13 / ne03;
  5742. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5743. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5744. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5745. vk_buffer d_Qx = nullptr;
  5746. size_t qx_buf_offset = 0;
  5747. vk_buffer d_Qy = nullptr;
  5748. size_t qy_buf_offset = 0;
  5749. bool src0_uma = false;
  5750. bool src1_uma = false;
  5751. if (ctx->device->uma) {
  5752. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5753. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5754. src0_uma = d_Qx != nullptr;
  5755. src1_uma = d_Qy != nullptr;
  5756. }
  5757. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5758. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5759. !ggml_vk_dim01_contiguous(src0);
  5760. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5761. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5762. !ggml_vk_dim01_contiguous(src1);
  5763. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5764. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5765. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5766. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  5767. // Check for mmq first
  5768. 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;
  5769. if (mmp == nullptr) {
  5770. // Fall back to f16 dequant mul mat
  5771. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  5772. quantize_y = false;
  5773. }
  5774. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5775. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  5776. if (qx_needs_dequant) {
  5777. // Fall back to dequant + f16 mulmat
  5778. 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]);
  5779. }
  5780. // Not implemented
  5781. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5782. 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)));
  5783. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8;
  5784. 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));
  5785. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  5786. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11;
  5787. const uint64_t x_ne = ggml_nelements(src0);
  5788. // 128 elements per Q8_1 x4 block
  5789. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  5790. const uint64_t d_ne = ggml_nelements(dst);
  5791. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline);
  5792. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  5793. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5794. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  5795. 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);
  5796. const uint64_t d_sz = sizeof(float) * d_ne;
  5797. vk_pipeline to_fp16_vk_0 = nullptr;
  5798. vk_pipeline to_fp16_vk_1 = nullptr;
  5799. vk_pipeline to_q8_1 = nullptr;
  5800. if (x_non_contig) {
  5801. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  5802. } else {
  5803. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  5804. }
  5805. if (y_non_contig) {
  5806. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  5807. } else {
  5808. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5809. }
  5810. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5811. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5812. if (quantize_y) {
  5813. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5814. }
  5815. {
  5816. const uint64_t split_k_size = split_k > 1 ? d_sz * split_k : 0;
  5817. if (
  5818. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  5819. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  5820. (split_k > 1 && split_k_size > ctx->device->properties.limits.maxStorageBufferRange)) {
  5821. GGML_ABORT("Requested preallocation size is too large");
  5822. }
  5823. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  5824. ctx->prealloc_size_x = x_sz;
  5825. ggml_vk_preallocate_buffers(ctx, subctx);
  5826. }
  5827. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  5828. ctx->prealloc_size_y = y_sz;
  5829. ggml_vk_preallocate_buffers(ctx, subctx);
  5830. }
  5831. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  5832. ctx->prealloc_size_split_k = split_k_size;
  5833. ggml_vk_preallocate_buffers(ctx, subctx);
  5834. }
  5835. // Request descriptor sets
  5836. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  5837. if (qx_needs_dequant) {
  5838. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5839. }
  5840. if (qy_needs_dequant) {
  5841. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5842. }
  5843. if (quantize_y) {
  5844. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5845. }
  5846. if (split_k > 1) {
  5847. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  5848. }
  5849. }
  5850. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5851. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5852. GGML_ASSERT(d_D != nullptr);
  5853. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz);
  5854. vk_buffer d_X;
  5855. uint64_t x_buf_offset = 0;
  5856. vk_buffer d_Y;
  5857. uint64_t y_buf_offset = 0;
  5858. if (!src0_uma) {
  5859. d_Qx = src0_buf_ctx->dev_buffer;
  5860. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5861. GGML_ASSERT(d_Qx != nullptr);
  5862. }
  5863. if (!src1_uma) {
  5864. d_Qy = src1_buf_ctx->dev_buffer;
  5865. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5866. GGML_ASSERT(d_Qy != nullptr);
  5867. }
  5868. if (qx_needs_dequant) {
  5869. d_X = ctx->prealloc_x;
  5870. GGML_ASSERT(d_X->size >= x_sz);
  5871. } else {
  5872. d_X = d_Qx;
  5873. x_buf_offset = qx_buf_offset;
  5874. GGML_ASSERT(qx_sz == x_sz);
  5875. }
  5876. if (qy_needs_dequant) {
  5877. d_Y = ctx->prealloc_y;
  5878. GGML_ASSERT(d_Y->size >= y_sz);
  5879. } else if (quantize_y) {
  5880. d_Y = ctx->prealloc_y;
  5881. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  5882. } else {
  5883. d_Y = d_Qy;
  5884. y_buf_offset = qy_buf_offset;
  5885. GGML_ASSERT(qy_sz == y_sz);
  5886. }
  5887. if (x_non_contig || qx_needs_dequant) {
  5888. if (ctx->prealloc_x_need_sync) {
  5889. ggml_vk_sync_buffers(ctx, subctx);
  5890. }
  5891. }
  5892. if (x_non_contig) {
  5893. 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));
  5894. } else if (qx_needs_dequant) {
  5895. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  5896. 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});
  5897. ggml_vk_sync_buffers(ctx, subctx);
  5898. }
  5899. if (y_non_contig) {
  5900. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5901. ctx->prealloc_y_last_tensor_used != src1) {
  5902. if (ctx->prealloc_y_need_sync) {
  5903. ggml_vk_sync_buffers(ctx, subctx);
  5904. }
  5905. 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));
  5906. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5907. ctx->prealloc_y_last_tensor_used = src1;
  5908. }
  5909. }
  5910. if (quantize_y) {
  5911. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5912. ctx->prealloc_y_last_tensor_used != src1) {
  5913. if (ctx->prealloc_y_need_sync) {
  5914. ggml_vk_sync_buffers(ctx, subctx);
  5915. }
  5916. 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);
  5917. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5918. ctx->prealloc_y_last_tensor_used = src1;
  5919. }
  5920. }
  5921. uint32_t stride_batch_x = ne00*ne01;
  5922. uint32_t stride_batch_y = ne10*ne11;
  5923. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5924. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5925. }
  5926. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  5927. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5928. }
  5929. // compute
  5930. ggml_vk_matmul(
  5931. ctx, subctx, pipeline,
  5932. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  5933. ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, d_sz * split_k },
  5934. ne01, ne11, ne10,
  5935. ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d,
  5936. split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n
  5937. ); // NOLINT
  5938. if (x_non_contig || qx_needs_dequant) {
  5939. ctx->prealloc_x_need_sync = true;
  5940. }
  5941. if (y_non_contig || quantize_y) {
  5942. ctx->prealloc_y_need_sync = true;
  5943. }
  5944. }
  5945. // Device tuning
  5946. static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_t n, uint32_t k, ggml_type src0_type) {
  5947. if (device->mmvq_mode == 1) {
  5948. return true;
  5949. } else if (device->mmvq_mode == -1) {
  5950. return false;
  5951. }
  5952. // General performance issue with q3_k and q6_k due to 2-byte alignment
  5953. if (src0_type == GGML_TYPE_Q3_K || src0_type == GGML_TYPE_Q6_K) {
  5954. return false;
  5955. }
  5956. // MMVQ is generally good for batches
  5957. if (n > 1) {
  5958. return true;
  5959. }
  5960. // Quantization overhead is not worth it for small k
  5961. switch (device->vendor_id) {
  5962. case VK_VENDOR_ID_NVIDIA:
  5963. if (src0_type == GGML_TYPE_Q2_K) {
  5964. return true;
  5965. }
  5966. if (k <= 4096) {
  5967. return false;
  5968. }
  5969. switch (src0_type) {
  5970. case GGML_TYPE_MXFP4:
  5971. case GGML_TYPE_Q8_0:
  5972. return device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  5973. default:
  5974. return true;
  5975. }
  5976. case VK_VENDOR_ID_AMD:
  5977. if (k < 2048) {
  5978. return false;
  5979. }
  5980. switch (src0_type) {
  5981. case GGML_TYPE_Q8_0:
  5982. return device->architecture == vk_device_architecture::AMD_GCN;
  5983. default:
  5984. return true;
  5985. }
  5986. case VK_VENDOR_ID_INTEL:
  5987. if (k < 2048) {
  5988. return false;
  5989. }
  5990. switch (src0_type) {
  5991. // From tests on A770 Linux, may need more tuning
  5992. case GGML_TYPE_Q4_0:
  5993. case GGML_TYPE_Q5_1:
  5994. return false;
  5995. default:
  5996. return true;
  5997. }
  5998. default:
  5999. return true;
  6000. }
  6001. GGML_UNUSED(m);
  6002. }
  6003. 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) {
  6004. ggml_tensor * dst = cgraph->nodes[node_idx];
  6005. const ggml_tensor * src0 = dst->src[0];
  6006. const ggml_tensor * src1 = dst->src[1];
  6007. 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];
  6008. 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];
  6009. 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];
  6010. std::cerr << ")),)");
  6011. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6012. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6013. const uint64_t ne00 = src0->ne[0];
  6014. const uint64_t ne01 = src0->ne[1];
  6015. const uint64_t ne02 = src0->ne[2];
  6016. const uint64_t ne03 = src0->ne[3];
  6017. const uint64_t ne10 = src1->ne[0];
  6018. const uint64_t ne11 = src1->ne[1];
  6019. const uint64_t ne12 = src1->ne[2];
  6020. const uint64_t ne13 = src1->ne[3];
  6021. const uint64_t ne20 = dst->ne[0];
  6022. const uint64_t ne21 = dst->ne[1];
  6023. // const uint64_t ne22 = dst->ne[2];
  6024. // const uint64_t ne23 = dst->ne[3];
  6025. const uint64_t r2 = ne12 / ne02;
  6026. const uint64_t r3 = ne13 / ne03;
  6027. // batch_n indicates that we need to compute a few vector results, and this assumes
  6028. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  6029. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  6030. bool batch_n = ne11 > 1;
  6031. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6032. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6033. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6034. 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);
  6035. vk_pipeline to_fp16_vk_0 = nullptr;
  6036. vk_pipeline to_fp16_vk_1 = nullptr;
  6037. if (x_non_contig) {
  6038. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6039. }
  6040. if (y_non_contig) {
  6041. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6042. } else {
  6043. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6044. }
  6045. // Check for mmq first
  6046. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr;
  6047. vk_pipeline to_q8_1 = nullptr;
  6048. if (dmmv == nullptr) {
  6049. // Fall back to f16 dequant mul mat
  6050. dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11, ne20, ne00);
  6051. quantize_y = false;
  6052. }
  6053. if (quantize_y) {
  6054. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6055. }
  6056. const bool qx_needs_dequant = x_non_contig;
  6057. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  6058. // Not implemented
  6059. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6060. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6061. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6062. GGML_ASSERT(dmmv != nullptr);
  6063. const uint64_t x_ne = ggml_nelements(src0);
  6064. const uint64_t y_ne = ggml_nelements(src1);
  6065. 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);
  6066. 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;
  6067. 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)) :
  6068. (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6069. {
  6070. if (
  6071. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6072. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6073. GGML_ABORT("Requested preallocation size is too large");
  6074. }
  6075. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6076. ctx->prealloc_size_x = x_sz;
  6077. ggml_vk_preallocate_buffers(ctx, subctx);
  6078. }
  6079. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6080. ctx->prealloc_size_y = y_sz;
  6081. ggml_vk_preallocate_buffers(ctx, subctx);
  6082. }
  6083. // Request descriptor sets
  6084. if (qx_needs_dequant) {
  6085. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6086. }
  6087. if (qy_needs_dequant) {
  6088. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6089. }
  6090. if (quantize_y) {
  6091. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6092. }
  6093. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6094. }
  6095. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6096. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6097. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  6098. vk_subbuffer d_X, d_Y;
  6099. if (qx_needs_dequant) {
  6100. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  6101. } else {
  6102. d_X = d_Qx;
  6103. GGML_ASSERT(qx_sz == x_sz);
  6104. }
  6105. if (qy_needs_dequant || quantize_y) {
  6106. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  6107. } else {
  6108. d_Y = d_Qy;
  6109. }
  6110. if (x_non_contig) {
  6111. if (ctx->prealloc_x_need_sync) {
  6112. ggml_vk_sync_buffers(ctx, subctx);
  6113. }
  6114. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6115. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  6116. }
  6117. if (y_non_contig) {
  6118. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6119. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6120. ctx->prealloc_y_last_tensor_used != src1) {
  6121. if (ctx->prealloc_y_need_sync) {
  6122. ggml_vk_sync_buffers(ctx, subctx);
  6123. }
  6124. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  6125. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6126. ctx->prealloc_y_last_tensor_used = src1;
  6127. }
  6128. }
  6129. if (quantize_y) {
  6130. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6131. ctx->prealloc_y_last_tensor_used != src1) {
  6132. if (ctx->prealloc_y_need_sync) {
  6133. ggml_vk_sync_buffers(ctx, subctx);
  6134. }
  6135. ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne);
  6136. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6137. ctx->prealloc_y_last_tensor_used = src1;
  6138. }
  6139. }
  6140. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  6141. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  6142. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  6143. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  6144. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6145. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6146. }
  6147. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6148. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6149. }
  6150. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6151. uint32_t groups_x = ne01;
  6152. uint32_t groups_z = 1;
  6153. if (ne01 > max_groups_x) {
  6154. groups_z = 64;
  6155. groups_x = CEIL_DIV(groups_x, groups_z);
  6156. }
  6157. uint32_t fusion_flags = 0;
  6158. vk_subbuffer d_F0 = d_D;
  6159. if (ctx->num_additional_fused_ops > 0) {
  6160. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6161. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6162. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6163. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6164. }
  6165. vk_subbuffer d_F1 = d_D;
  6166. if (ctx->num_additional_fused_ops == 2) {
  6167. const ggml_tensor * add = cgraph->nodes[node_idx + 2];
  6168. const ggml_tensor * bias = add->src[0] == cgraph->nodes[node_idx + 1] ? add->src[1] : add->src[0];
  6169. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6170. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6171. }
  6172. // compute
  6173. const vk_mat_vec_push_constants pc = {
  6174. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6175. stride_batch_x, stride_batch_y, stride_batch_d,
  6176. fusion_flags,
  6177. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  6178. };
  6179. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6180. {
  6181. d_X,
  6182. d_Y,
  6183. d_D,
  6184. d_F0,
  6185. d_F1,
  6186. },
  6187. pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  6188. if (x_non_contig) {
  6189. ctx->prealloc_x_need_sync = true;
  6190. }
  6191. if (y_non_contig || quantize_y) {
  6192. ctx->prealloc_y_need_sync = true;
  6193. }
  6194. }
  6195. 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) {
  6196. ggml_tensor * dst = cgraph->nodes[node_idx];
  6197. const ggml_tensor * src0 = dst->src[0];
  6198. const ggml_tensor * src1 = dst->src[1];
  6199. 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];
  6200. 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];
  6201. 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];
  6202. std::cerr << "))");
  6203. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  6204. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  6205. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  6206. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6207. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6208. const uint64_t ne00 = src0->ne[0];
  6209. const uint64_t ne01 = src0->ne[1];
  6210. const uint64_t ne02 = src0->ne[2];
  6211. // const uint64_t ne03 = src0->ne[3];
  6212. //const uint64_t ne10 = src1->ne[0];
  6213. const uint64_t ne11 = src1->ne[1];
  6214. const uint64_t ne12 = src1->ne[2];
  6215. // const uint64_t ne13 = src1->ne[3];
  6216. GGML_ASSERT(ne11 == 1);
  6217. // With grouped query attention there are > 1 Q matrices per K, V matrix.
  6218. uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02;
  6219. if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) {
  6220. gqa_ratio = 1;
  6221. }
  6222. {
  6223. // Request descriptor sets
  6224. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], 1);
  6225. }
  6226. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  6227. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6228. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  6229. vk_subbuffer d_F0 = d_D;
  6230. uint32_t fusion_flags = 0;
  6231. if (ctx->num_additional_fused_ops > 0) {
  6232. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6233. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6234. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6235. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6236. }
  6237. vk_subbuffer d_F1 = d_D;
  6238. if (ctx->num_additional_fused_ops > 1) {
  6239. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  6240. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6241. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6242. }
  6243. // compute
  6244. vk_mat_vec_p021_push_constants pc = {
  6245. (uint32_t)ne00, (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne12,
  6246. 0, 0, fusion_flags
  6247. };
  6248. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6249. uint32_t workgroups_z = (uint32_t)ne12;
  6250. // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups
  6251. if (gqa_ratio > 1) {
  6252. workgroups_z /= gqa_ratio;
  6253. }
  6254. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1],
  6255. {
  6256. d_Qx,
  6257. d_Qy,
  6258. d_D,
  6259. d_F0,
  6260. d_F1,
  6261. }, pc, { 1, (uint32_t)ne01, workgroups_z });
  6262. }
  6263. 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) {
  6264. ggml_tensor * dst = cgraph->nodes[node_idx];
  6265. const ggml_tensor * src0 = dst->src[0];
  6266. const ggml_tensor * src1 = dst->src[1];
  6267. 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];
  6268. 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];
  6269. 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];
  6270. std::cerr << "))");
  6271. GGML_ASSERT(!ggml_is_transposed(src0));
  6272. GGML_ASSERT(!ggml_is_transposed(src1));
  6273. GGML_ASSERT(!ggml_is_permuted(src0));
  6274. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6275. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6276. const uint64_t ne00 = src0->ne[0];
  6277. const uint64_t ne01 = src0->ne[1];
  6278. const uint64_t ne02 = src0->ne[2];
  6279. const uint64_t ne03 = src0->ne[3];
  6280. const uint64_t nb01 = src0->nb[1];
  6281. const uint64_t nb02 = src0->nb[2];
  6282. const uint64_t nb12 = src1->nb[2];
  6283. // const uint64_t ne10 = src1->ne[0];
  6284. const uint64_t ne11 = src1->ne[1];
  6285. const uint64_t ne12 = src1->ne[2];
  6286. // const uint64_t ne13 = src1->ne[3];
  6287. const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t));
  6288. const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float));
  6289. const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float));
  6290. GGML_ASSERT(ne11 == 1);
  6291. GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in supports_op
  6292. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  6293. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  6294. const uint32_t channel_stride_y = nb12 / sizeof(float);
  6295. {
  6296. // Request descriptor sets
  6297. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  6298. }
  6299. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  6300. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6301. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  6302. vk_subbuffer d_F0 = d_D;
  6303. uint32_t fusion_flags = 0;
  6304. if (ctx->num_additional_fused_ops > 0) {
  6305. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6306. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6307. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6308. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6309. }
  6310. vk_subbuffer d_F1 = d_D;
  6311. if (ctx->num_additional_fused_ops > 1) {
  6312. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  6313. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6314. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6315. }
  6316. // compute
  6317. vk_mat_vec_nc_push_constants pc = {
  6318. (uint32_t)ne00, (uint32_t)ne01,
  6319. row_stride_x, channel_stride_x, channel_stride_y,
  6320. (uint32_t)(ne12 / ne02), (uint32_t)ne12,
  6321. 0, 0,
  6322. nb03, nb13, nb23, fusion_flags
  6323. };
  6324. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6325. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  6326. {
  6327. d_Qx,
  6328. d_Qy,
  6329. d_D,
  6330. d_F0,
  6331. d_F1,
  6332. }, pc, { (uint32_t)ne03, (uint32_t)ne01, (uint32_t)ne12 });
  6333. }
  6334. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6335. ggml_tensor * dst = cgraph->nodes[node_idx];
  6336. ggml_tensor * src0 = dst->src[0];
  6337. ggml_tensor * src1 = dst->src[1];
  6338. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  6339. // Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases
  6340. // where the M dimension is very large.
  6341. // Split_k doesn't work with M splitting.
  6342. const size_t nbytes = ggml_nbytes(src0);
  6343. const bool needs_split = nbytes > ctx->device->properties.limits.maxStorageBufferRange;
  6344. if (needs_split) {
  6345. // Choose the number of rows that can fit (and divide by two, to allow for any additional offsets)
  6346. const uint32_t M_split = ctx->device->properties.limits.maxStorageBufferRange / (2 * src0->nb[1]);
  6347. uint32_t m_offset = 0;
  6348. while (m_offset < dst->ne[0]) {
  6349. const uint32_t cur_M_size = std::min(M_split, (uint32_t)(dst->ne[0] - m_offset));
  6350. ggml_tensor dst2 = *dst;
  6351. ggml_tensor src02 = *src0;
  6352. dst2.view_src = dst->view_src ? dst->view_src : dst;
  6353. src02.view_src = src0->view_src ? src0->view_src : src0;
  6354. dst2.view_offs += m_offset * dst->nb[0];
  6355. src02.view_offs += m_offset * src0->nb[1];
  6356. dst2.ne[0] = cur_M_size;
  6357. src02.ne[1] = cur_M_size;
  6358. ggml_vk_mul_mat_q_f16(ctx, subctx, &src02, src1, &dst2, true);
  6359. m_offset += cur_M_size;
  6360. }
  6361. } else if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  6362. // detect 0213 permutation, and batch size of 1
  6363. src0->nb[0] <= src0->nb[2] &&
  6364. src0->nb[2] <= src0->nb[1] &&
  6365. src0->nb[1] <= src0->nb[3] &&
  6366. src1->nb[0] <= src1->nb[2] &&
  6367. src1->nb[2] <= src1->nb[1] &&
  6368. src1->nb[1] <= src1->nb[3] &&
  6369. src0->ne[3] == 1 &&
  6370. src1->ne[3] == 1) {
  6371. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, cgraph, node_idx);
  6372. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  6373. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  6374. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, cgraph, node_idx);
  6375. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  6376. // when ne12 and ne13 are one.
  6377. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  6378. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
  6379. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx);
  6380. } else {
  6381. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false);
  6382. }
  6383. }
  6384. 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) {
  6385. 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];
  6386. 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];
  6387. 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];
  6388. 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] << "),)");
  6389. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6390. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6391. const uint64_t ne00 = src0->ne[0];
  6392. const uint64_t ne01 = src0->ne[1];
  6393. const uint64_t ne02 = src0->ne[2];
  6394. // const uint64_t ne03 = src0->ne[3];
  6395. const uint64_t ne10 = src1->ne[0];
  6396. const uint64_t ne11 = src1->ne[1];
  6397. const uint64_t ne12 = src1->ne[2];
  6398. const uint64_t ne13 = src1->ne[3];
  6399. const uint64_t nei0 = ids->ne[0];
  6400. const uint64_t nei1 = ids->ne[1];
  6401. const uint32_t nbi1 = ids->nb[1];
  6402. const uint32_t nbi2 = ids->nb[2];
  6403. const uint64_t ne20 = dst->ne[0];
  6404. const uint64_t ne21 = dst->ne[1];
  6405. // const uint64_t ne22 = dst->ne[2];
  6406. // const uint64_t ne23 = dst->ne[3];
  6407. const uint64_t n_as = ne02;
  6408. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6409. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6410. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6411. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6412. vk_buffer d_Qx = nullptr;
  6413. size_t qx_buf_offset = 0;
  6414. vk_buffer d_Qy = nullptr;
  6415. size_t qy_buf_offset = 0;
  6416. vk_buffer d_ids = nullptr;
  6417. size_t ids_buf_offset = 0;
  6418. bool src0_uma = false;
  6419. bool src1_uma = false;
  6420. bool ids_uma = false;
  6421. if (ctx->device->uma) {
  6422. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6423. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6424. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6425. src0_uma = d_Qx != nullptr;
  6426. src1_uma = d_Qy != nullptr;
  6427. ids_uma = d_ids != nullptr;
  6428. }
  6429. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  6430. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  6431. !ggml_vk_dim01_contiguous(src0);
  6432. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  6433. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  6434. !ggml_vk_dim01_contiguous(src1);
  6435. // If src0 is BF16, try to use a BF16 x BF16 multiply
  6436. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  6437. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  6438. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  6439. // Check for mmq first
  6440. 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;
  6441. if (mmp == nullptr) {
  6442. // Fall back to f16 dequant mul mat
  6443. 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]);
  6444. quantize_y = false;
  6445. }
  6446. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  6447. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  6448. if (qx_needs_dequant) {
  6449. // Fall back to dequant + f16 mulmat
  6450. 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]);
  6451. }
  6452. // Not implemented
  6453. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6454. 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));
  6455. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && nei1 > 8;
  6456. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned, qx_needs_dequant ? f16_type : src0->type);
  6457. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  6458. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) :ne11;
  6459. const uint64_t x_ne = ggml_nelements(src0);
  6460. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  6461. const uint64_t d_ne = ggml_nelements(dst);
  6462. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  6463. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6464. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  6465. 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);
  6466. const uint64_t ids_sz = nbi2;
  6467. const uint64_t d_sz = sizeof(float) * d_ne;
  6468. vk_pipeline to_fp16_vk_0 = nullptr;
  6469. vk_pipeline to_fp16_vk_1 = nullptr;
  6470. vk_pipeline to_q8_1 = nullptr;
  6471. if (x_non_contig) {
  6472. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  6473. } else {
  6474. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  6475. }
  6476. if (y_non_contig) {
  6477. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  6478. } else {
  6479. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6480. }
  6481. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6482. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6483. if (quantize_y) {
  6484. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6485. }
  6486. {
  6487. if (
  6488. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6489. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6490. GGML_ABORT("Requested preallocation size is too large");
  6491. }
  6492. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6493. ctx->prealloc_size_x = x_sz;
  6494. ggml_vk_preallocate_buffers(ctx, subctx);
  6495. }
  6496. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6497. ctx->prealloc_size_y = y_sz;
  6498. ggml_vk_preallocate_buffers(ctx, subctx);
  6499. }
  6500. // Request descriptor sets
  6501. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6502. if (qx_needs_dequant) {
  6503. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6504. }
  6505. if (qy_needs_dequant) {
  6506. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6507. }
  6508. if (quantize_y) {
  6509. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6510. }
  6511. }
  6512. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6513. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6514. GGML_ASSERT(d_D != nullptr);
  6515. vk_buffer d_X;
  6516. uint64_t x_buf_offset = 0;
  6517. vk_buffer d_Y;
  6518. uint64_t y_buf_offset = 0;
  6519. if (!src0_uma) {
  6520. d_Qx = src0_buf_ctx->dev_buffer;
  6521. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6522. GGML_ASSERT(d_Qx != nullptr);
  6523. }
  6524. if (!src1_uma) {
  6525. d_Qy = src1_buf_ctx->dev_buffer;
  6526. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6527. GGML_ASSERT(d_Qy != nullptr);
  6528. }
  6529. if (!ids_uma) {
  6530. d_ids = ids_buf_ctx->dev_buffer;
  6531. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6532. GGML_ASSERT(d_ids != nullptr);
  6533. }
  6534. if (qx_needs_dequant) {
  6535. d_X = ctx->prealloc_x;
  6536. GGML_ASSERT(d_X->size >= x_sz);
  6537. } else {
  6538. d_X = d_Qx;
  6539. x_buf_offset = qx_buf_offset;
  6540. GGML_ASSERT(qx_sz == x_sz);
  6541. }
  6542. if (qy_needs_dequant) {
  6543. d_Y = ctx->prealloc_y;
  6544. GGML_ASSERT(d_Y->size >= y_sz);
  6545. } else if (quantize_y) {
  6546. d_Y = ctx->prealloc_y;
  6547. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  6548. } else {
  6549. d_Y = d_Qy;
  6550. y_buf_offset = qy_buf_offset;
  6551. GGML_ASSERT(qy_sz == y_sz);
  6552. }
  6553. if (x_non_contig || qx_needs_dequant) {
  6554. if (ctx->prealloc_x_need_sync) {
  6555. ggml_vk_sync_buffers(ctx, subctx);
  6556. }
  6557. }
  6558. if (x_non_contig) {
  6559. 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));
  6560. } else if (qx_needs_dequant) {
  6561. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6562. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  6563. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)x_ne, 1, 1});
  6564. ggml_vk_sync_buffers(ctx, subctx);
  6565. }
  6566. if (y_non_contig) {
  6567. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6568. ctx->prealloc_y_last_tensor_used != src1) {
  6569. if (ctx->prealloc_y_need_sync) {
  6570. ggml_vk_sync_buffers(ctx, subctx);
  6571. }
  6572. 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));
  6573. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6574. ctx->prealloc_y_last_tensor_used = src1;
  6575. }
  6576. }
  6577. if (quantize_y) {
  6578. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6579. ctx->prealloc_y_last_tensor_used != src1) {
  6580. if (ctx->prealloc_y_need_sync) {
  6581. ggml_vk_sync_buffers(ctx, subctx);
  6582. }
  6583. 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);
  6584. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6585. ctx->prealloc_y_last_tensor_used = src1;
  6586. }
  6587. }
  6588. uint32_t stride_batch_x = ne00*ne01;
  6589. uint32_t stride_batch_y = ne10*ne11;
  6590. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6591. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6592. }
  6593. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  6594. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6595. }
  6596. // compute
  6597. ggml_vk_matmul_id(
  6598. ctx, subctx, pipeline,
  6599. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  6600. { d_D, d_buf_offset, d_sz }, { d_ids, ids_buf_offset, ids_sz },
  6601. ne01, ne21, ne10, ne10, ne10, ne01,
  6602. stride_batch_x, stride_batch_y, ne20*ne21,
  6603. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, padded_n
  6604. ); // NOLINT
  6605. if (x_non_contig || qx_needs_dequant) {
  6606. ctx->prealloc_x_need_sync = true;
  6607. }
  6608. if (y_non_contig || quantize_y) {
  6609. ctx->prealloc_y_need_sync = true;
  6610. }
  6611. }
  6612. 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) {
  6613. ggml_tensor * dst = cgraph->nodes[node_idx];
  6614. ggml_tensor * src0 = dst->src[0];
  6615. ggml_tensor * src1 = dst->src[1];
  6616. ggml_tensor * ids = dst->src[2];
  6617. 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];
  6618. 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];
  6619. 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];
  6620. 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];
  6621. std::cerr << "))");
  6622. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6623. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6624. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6625. const uint64_t ne00 = src0->ne[0];
  6626. const uint64_t ne01 = src0->ne[1];
  6627. // const uint64_t ne02 = src0->ne[2];
  6628. // const uint64_t ne03 = src0->ne[3];
  6629. const uint64_t ne10 = src1->ne[0];
  6630. const uint64_t ne11 = src1->ne[1];
  6631. const uint64_t ne12 = src1->ne[2];
  6632. // const uint64_t ne13 = src1->ne[3];
  6633. const uint64_t nei0 = ids->ne[0];
  6634. const uint64_t nei1 = ids->ne[1];
  6635. GGML_ASSERT(nei1 == 1);
  6636. const uint64_t ne20 = dst->ne[0];
  6637. const uint64_t ne21 = dst->ne[1];
  6638. // const uint64_t ne22 = dst->ne[2];
  6639. // const uint64_t ne23 = dst->ne[3];
  6640. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6641. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6642. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6643. 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);
  6644. vk_pipeline to_fp16_vk_0 = nullptr;
  6645. vk_pipeline to_fp16_vk_1 = nullptr;
  6646. if (x_non_contig) {
  6647. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6648. }
  6649. if (y_non_contig) {
  6650. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6651. } else {
  6652. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6653. }
  6654. // Check for mmq first
  6655. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, GGML_TYPE_Q8_1, ne20, ne00) : nullptr;
  6656. vk_pipeline to_q8_1 = nullptr;
  6657. if (dmmv == nullptr) {
  6658. // Fall back to f16 dequant mul mat
  6659. dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type, ne20, ne00);
  6660. quantize_y = false;
  6661. }
  6662. if (quantize_y) {
  6663. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6664. }
  6665. const bool qx_needs_dequant = x_non_contig;
  6666. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  6667. // Not implemented
  6668. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6669. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6670. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6671. GGML_ASSERT(dmmv != nullptr);
  6672. const uint64_t x_ne = ggml_nelements(src0);
  6673. const uint64_t y_ne = ggml_nelements(src1);
  6674. 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);
  6675. 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;
  6676. 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)) :
  6677. (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  6678. {
  6679. if (
  6680. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6681. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6682. GGML_ABORT("Requested preallocation size is too large");
  6683. }
  6684. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6685. ctx->prealloc_size_x = x_sz;
  6686. ggml_vk_preallocate_buffers(ctx, subctx);
  6687. }
  6688. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6689. ctx->prealloc_size_y = y_sz;
  6690. ggml_vk_preallocate_buffers(ctx, subctx);
  6691. }
  6692. // Request descriptor sets
  6693. if (qx_needs_dequant) {
  6694. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6695. }
  6696. if (qy_needs_dequant) {
  6697. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6698. }
  6699. if (quantize_y) {
  6700. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6701. }
  6702. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6703. }
  6704. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6705. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6706. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  6707. vk_subbuffer d_ids = ggml_vk_tensor_subbuffer(ctx, ids);
  6708. vk_subbuffer d_F0 = d_D;
  6709. vk_subbuffer d_X, d_Y;
  6710. if (qx_needs_dequant) {
  6711. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  6712. } else {
  6713. d_X = d_Qx;
  6714. }
  6715. if (qy_needs_dequant || quantize_y) {
  6716. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  6717. } else {
  6718. d_Y = d_Qy;
  6719. }
  6720. if (x_non_contig) {
  6721. if (ctx->prealloc_x_need_sync) {
  6722. ggml_vk_sync_buffers(ctx, subctx);
  6723. }
  6724. }
  6725. if (x_non_contig) {
  6726. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6727. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  6728. }
  6729. if (y_non_contig) {
  6730. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6731. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6732. ctx->prealloc_y_last_tensor_used != src1) {
  6733. if (ctx->prealloc_y_need_sync) {
  6734. ggml_vk_sync_buffers(ctx, subctx);
  6735. }
  6736. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  6737. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6738. ctx->prealloc_y_last_tensor_used = src1;
  6739. }
  6740. }
  6741. if (quantize_y) {
  6742. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6743. ctx->prealloc_y_last_tensor_used != src1) {
  6744. if (ctx->prealloc_y_need_sync) {
  6745. ggml_vk_sync_buffers(ctx, subctx);
  6746. }
  6747. ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne);
  6748. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6749. ctx->prealloc_y_last_tensor_used = src1;
  6750. }
  6751. }
  6752. uint32_t stride_batch_y = ne10*ne11;
  6753. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6754. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6755. }
  6756. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6757. uint32_t groups_x = ne01;
  6758. uint32_t groups_z = 1;
  6759. if (ne01 > max_groups_x) {
  6760. groups_z = 64;
  6761. groups_x = CEIL_DIV(groups_x, groups_z);
  6762. }
  6763. uint32_t fusion_flags = 0;
  6764. if (ctx->num_additional_fused_ops > 0) {
  6765. const ggml_tensor * bias = cgraph->nodes[node_idx + 1]->src[1];
  6766. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6767. if (cgraph->nodes[node_idx + 1]->op == GGML_OP_MUL) {
  6768. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE0;
  6769. } else {
  6770. GGML_ASSERT(cgraph->nodes[node_idx + 1]->op == GGML_OP_ADD_ID);
  6771. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6772. }
  6773. }
  6774. vk_subbuffer d_F1 = d_D;
  6775. if (ctx->num_additional_fused_ops > 1) {
  6776. const ggml_tensor * scale = cgraph->nodes[node_idx + 2]->src[1];
  6777. d_F1 = ggml_vk_tensor_subbuffer(ctx, scale);
  6778. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE1;
  6779. }
  6780. // compute
  6781. const vk_mat_vec_id_push_constants pc = {
  6782. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6783. (uint32_t)(ne00 * ne01), stride_batch_y, (uint32_t)(ne20 * ne21),
  6784. fusion_flags,
  6785. (uint32_t)nei0, (uint32_t)ne11,
  6786. };
  6787. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6788. {
  6789. d_X,
  6790. d_Y,
  6791. d_D,
  6792. d_F0,
  6793. d_F1,
  6794. d_ids,
  6795. },
  6796. pc, { groups_x, (uint32_t)nei0, groups_z });
  6797. if (x_non_contig) {
  6798. ctx->prealloc_x_need_sync = true;
  6799. }
  6800. if (y_non_contig || quantize_y) {
  6801. ctx->prealloc_y_need_sync = true;
  6802. }
  6803. }
  6804. static bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx) {
  6805. ggml_tensor * dst = cgraph->nodes[node_idx];
  6806. ggml_tensor * src0 = dst->src[0];
  6807. ggml_tensor * src2 = dst->src[2];
  6808. return src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type));
  6809. }
  6810. static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6811. ggml_tensor * dst = cgraph->nodes[node_idx];
  6812. ggml_tensor * src0 = dst->src[0];
  6813. ggml_tensor * src1 = dst->src[1];
  6814. ggml_tensor * src2 = dst->src[2];
  6815. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  6816. if (ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  6817. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, cgraph, node_idx);
  6818. } else {
  6819. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst);
  6820. }
  6821. }
  6822. static bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv) {
  6823. // Needs to be kept up to date on shader changes
  6824. GGML_UNUSED(hsv);
  6825. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6826. const uint32_t Br = get_fa_scalar_num_large_rows(hsk, hsv);
  6827. const uint32_t Bc = scalar_flash_attention_Bc;
  6828. const uint32_t tmpsh = wg_size * sizeof(float);
  6829. const uint32_t tmpshv4 = wg_size * 4 * sizeof(float);
  6830. const uint32_t masksh = Bc * Br * sizeof(float);
  6831. const uint32_t Qf = Br * (hsk / 4 + 2) * 4 * sizeof(float);
  6832. const uint32_t total_size = tmpsh + tmpshv4 + masksh + Qf;
  6833. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6834. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported);
  6835. return supported;
  6836. }
  6837. static bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool f32acc) {
  6838. // Needs to be kept up to date on shader changes
  6839. GGML_UNUSED(hsv);
  6840. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6841. const uint32_t Br = coopmat1_flash_attention_num_large_rows;
  6842. const uint32_t Bc = scalar_flash_attention_Bc;
  6843. const uint32_t hsk_pad = ROUNDUP_POW2(hsk, 16);
  6844. const uint32_t acctype = f32acc ? 4 : 2;
  6845. const uint32_t f16vec4 = 8;
  6846. const uint32_t tmpsh = wg_size * sizeof(float);
  6847. const uint32_t tmpshv4 = wg_size * 4 * acctype;
  6848. const uint32_t qstride = hsk_pad / 4 + 2;
  6849. const uint32_t Qf = Br * qstride * f16vec4;
  6850. const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br;
  6851. const uint32_t sfsh = Bc * sfshstride * acctype;
  6852. const uint32_t kshstride = hsk_pad / 4 + 2;
  6853. const uint32_t ksh = Bc * kshstride * f16vec4;
  6854. const uint32_t slope = Br * sizeof(float);
  6855. const uint32_t total_size = tmpsh + tmpshv4 + Qf + sfsh + ksh + slope;
  6856. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6857. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported);
  6858. return supported;
  6859. }
  6860. 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) {
  6861. 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];
  6862. 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];
  6863. 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];
  6864. 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];
  6865. if (sinks) {
  6866. 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];
  6867. }
  6868. std::cerr << "))");
  6869. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  6870. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  6871. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  6872. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  6873. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  6874. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  6875. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  6876. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  6877. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  6878. const uint32_t nem2 = mask ? mask->ne[2] : 0;
  6879. const uint32_t nem3 = mask ? mask->ne[3] : 0;
  6880. const uint32_t HSK = nek0;
  6881. const uint32_t HSV = nev0;
  6882. uint32_t N = neq1;
  6883. const uint32_t KV = nek1;
  6884. GGML_ASSERT(ne0 == HSV);
  6885. GGML_ASSERT(ne2 == N);
  6886. // input tensor rows must be contiguous
  6887. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  6888. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  6889. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  6890. GGML_ASSERT(neq0 == HSK);
  6891. GGML_ASSERT(neq1 == N);
  6892. GGML_ASSERT(nev1 == nek1);
  6893. // dst cannot be transposed or permuted
  6894. GGML_ASSERT(nb0 == sizeof(float));
  6895. GGML_ASSERT(nb0 <= nb1);
  6896. GGML_ASSERT(nb1 <= nb2);
  6897. GGML_ASSERT(nb2 <= nb3);
  6898. assert(dst->type == GGML_TYPE_F32);
  6899. assert(q->type == GGML_TYPE_F32);
  6900. assert(k->type == v->type);
  6901. FaCodePath path = ctx->device->coopmat2 ? FA_COOPMAT2 :
  6902. ctx->device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;
  6903. if (path == FA_COOPMAT1) {
  6904. const bool coopmat_shape_supported = (dst->op_params[3] == GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f32acc) ||
  6905. (dst->op_params[3] != GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f16acc);
  6906. const bool coopmat_shmem_supported = ggml_vk_flash_attn_coopmat_shmem_support(ctx->device, HSK, HSV, dst->op_params[3] == GGML_PREC_F32);
  6907. if (!coopmat_shape_supported || !coopmat_shmem_supported) {
  6908. path = FA_SCALAR;
  6909. }
  6910. }
  6911. uint32_t gqa_ratio = 1;
  6912. uint32_t qk_ratio = neq2 / nek2;
  6913. uint32_t workgroups_x = (uint32_t)neq1;
  6914. uint32_t workgroups_y = (uint32_t)neq2;
  6915. uint32_t workgroups_z = (uint32_t)neq3;
  6916. // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga.
  6917. // For coopmat2 FA, we always use the small size (which is still pretty large for gqa).
  6918. uint32_t max_gqa;
  6919. switch (path) {
  6920. case FA_SCALAR:
  6921. case FA_COOPMAT1:
  6922. // We may switch from coopmat1 to scalar, so use the scalar limit for both
  6923. max_gqa = get_fa_scalar_num_large_rows(HSK, HSV);
  6924. break;
  6925. case FA_COOPMAT2:
  6926. max_gqa = get_fa_num_small_rows(FA_COOPMAT2);
  6927. break;
  6928. default:
  6929. GGML_ASSERT(0);
  6930. }
  6931. if (N == 1 && qk_ratio > 1 && qk_ratio <= max_gqa &&
  6932. qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) {
  6933. // grouped query attention - make the N dimension equal to gqa_ratio, reduce
  6934. // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1
  6935. // and change addressing calculations to index Q's dimension 2.
  6936. gqa_ratio = qk_ratio;
  6937. N = gqa_ratio;
  6938. workgroups_y /= N;
  6939. }
  6940. bool small_rows = N <= get_fa_num_small_rows(path);
  6941. // coopmat1 does not actually support "small rows" (it needs 16 rows).
  6942. // So use scalar instead.
  6943. if (small_rows && path == FA_COOPMAT1) {
  6944. path = FA_SCALAR;
  6945. }
  6946. // scalar is faster than coopmat2 when N==1
  6947. if (N == 1 && path == FA_COOPMAT2) {
  6948. path = FA_SCALAR;
  6949. }
  6950. // with large hsk/hsv, scalar path may need to use small_rows to fit in shared memory
  6951. if (path == FA_SCALAR &&
  6952. !ggml_vk_flash_attn_scalar_shmem_support(ctx->device, HSK, HSV)) {
  6953. small_rows = true;
  6954. }
  6955. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  6956. uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  6957. uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  6958. // For F32, the shader treats it as a block of size 4 (for vec4 loads)
  6959. if (k->type == GGML_TYPE_F32) {
  6960. k_stride /= 4;
  6961. }
  6962. if (v->type == GGML_TYPE_F32) {
  6963. v_stride /= 4;
  6964. }
  6965. uint32_t alignment = fa_align(path, HSK, HSV, k->type, small_rows);
  6966. bool aligned = (KV % alignment) == 0 &&
  6967. // the "aligned" shader variant will forcibly align strides, for performance
  6968. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  6969. // Need to use the coopmat2 variant that clamps loads when HSK/HSV aren't sufficiently aligned.
  6970. if (((HSK | HSV) % 16) != 0 && path == FA_COOPMAT2) {
  6971. aligned = false;
  6972. }
  6973. bool f32acc = path == FA_SCALAR || dst->op_params[3] == GGML_PREC_F32;
  6974. vk_fa_pipeline_state fa_pipeline_state(HSK, HSV, small_rows, path, aligned, f32acc);
  6975. vk_pipeline pipeline = nullptr;
  6976. {
  6977. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  6978. auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16[k->type];
  6979. auto it = pipelines.find(fa_pipeline_state);
  6980. if (it != pipelines.end()) {
  6981. pipeline = it->second;
  6982. } else {
  6983. pipelines[fa_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  6984. }
  6985. }
  6986. assert(pipeline);
  6987. uint32_t split_kv = KV;
  6988. uint32_t split_k = 1;
  6989. // Use a placeholder core count if one isn't available. split_k is a big help for perf.
  6990. const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count : 16;
  6991. // Try to use split_k when KV is large enough to be worth the overhead
  6992. if (workgroups_x == 1 && shader_core_count > 0) {
  6993. // Try to run two workgroups per SM.
  6994. split_k = shader_core_count * 2 / (workgroups_y * workgroups_z);
  6995. if (split_k > 1) {
  6996. // Try to evenly split KV into split_k chunks, but it needs to be a multiple
  6997. // of "align", so recompute split_k based on that.
  6998. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment);
  6999. split_k = CEIL_DIV(KV, split_kv);
  7000. workgroups_x = split_k;
  7001. }
  7002. }
  7003. // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1)
  7004. // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows.
  7005. const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne3 : 0;
  7006. if (split_k_size > ctx->device->properties.limits.maxStorageBufferRange) {
  7007. GGML_ABORT("Requested preallocation size is too large");
  7008. }
  7009. if (ctx->prealloc_size_split_k < split_k_size) {
  7010. ctx->prealloc_size_split_k = split_k_size;
  7011. ggml_vk_preallocate_buffers(ctx, subctx);
  7012. }
  7013. {
  7014. // Request descriptor sets
  7015. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7016. if (split_k > 1) {
  7017. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1);
  7018. }
  7019. }
  7020. float scale = 1.0f;
  7021. float max_bias = 0.0f;
  7022. float logit_softcap = 0.0f;
  7023. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  7024. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  7025. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  7026. if (logit_softcap != 0) {
  7027. scale /= logit_softcap;
  7028. }
  7029. const uint32_t n_head_kv = neq2;
  7030. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  7031. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  7032. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  7033. vk_subbuffer q_buf = ggml_vk_tensor_subbuffer(ctx, q);
  7034. vk_subbuffer k_buf = ggml_vk_tensor_subbuffer(ctx, k);
  7035. vk_subbuffer v_buf = ggml_vk_tensor_subbuffer(ctx, v);
  7036. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  7037. vk_subbuffer mask_buf = mask ? ggml_vk_tensor_subbuffer(ctx, mask) : q_buf;
  7038. vk_subbuffer sinks_buf = sinks ? ggml_vk_tensor_subbuffer(ctx, sinks) : q_buf;
  7039. uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | ((mask != nullptr) << 16) | n_head_log2;
  7040. const vk_flash_attn_push_constants pc = { N, KV,
  7041. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  7042. (uint32_t)neq2, (uint32_t)neq3,
  7043. (uint32_t)nek2, (uint32_t)nek3,
  7044. (uint32_t)nev2, (uint32_t)nev3,
  7045. nem1, nem2, nem3,
  7046. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  7047. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  7048. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  7049. scale, max_bias, logit_softcap,
  7050. mask_n_head_log2, m0, m1,
  7051. gqa_ratio, split_kv, split_k };
  7052. if (split_k > 1) {
  7053. if (ctx->prealloc_split_k_need_sync) {
  7054. ggml_vk_sync_buffers(ctx, subctx);
  7055. }
  7056. vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  7057. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7058. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf},
  7059. // We only use split_k when group query attention is enabled, which means
  7060. // there's no more than one tile of rows (i.e. workgroups_x would have been
  7061. // one). We reuse workgroups_x to mean the number of splits, so we need to
  7062. // cancel out the divide by wg_denoms[0].
  7063. pc, { workgroups_x * pipeline->wg_denoms[0], workgroups_y, workgroups_z });
  7064. ggml_vk_sync_buffers(ctx, subctx);
  7065. const std::array<uint32_t, 5> pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne3, split_k, (sinks != nullptr) };
  7066. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce,
  7067. {split_k_buf, sinks_buf, dst_buf},
  7068. pc2, { (uint32_t)ne1, HSV, (uint32_t)ne3 });
  7069. ctx->prealloc_split_k_need_sync = true;
  7070. } else {
  7071. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7072. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf},
  7073. pc, { workgroups_x, workgroups_y, workgroups_z });
  7074. }
  7075. }
  7076. static vk_conv_shapes ggml_vk_conv_select_shape(ggml_backend_vk_context * ctx, uint32_t K, uint32_t NPQ) {
  7077. auto n_tiles = [&](vk_conv_shapes s) {
  7078. return CEIL_DIV(K, vk_conv_block_sizes[s].K)
  7079. * CEIL_DIV(NPQ, vk_conv_block_sizes[s].NPQ);
  7080. };
  7081. // We can't query number of shader cores on Intel, use 32 as a placeholder
  7082. // so small convolutions will still choose a smaller tile.
  7083. const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32;
  7084. if (K > 64 && n_tiles(CONV_SHAPE_128x128) >= shader_core_count * 2) {
  7085. return CONV_SHAPE_128x128;
  7086. } else if (K <= 32 && n_tiles(CONV_SHAPE_32x256) >= shader_core_count * 2) {
  7087. return CONV_SHAPE_32x256;
  7088. } else {
  7089. return CONV_SHAPE_64x32;
  7090. }
  7091. }
  7092. 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) {
  7093. switch (op) {
  7094. case GGML_OP_GET_ROWS:
  7095. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  7096. if (dst->type == GGML_TYPE_F16) {
  7097. return ctx->device->pipeline_get_rows[src0->type];
  7098. }
  7099. if (dst->type == GGML_TYPE_F32) {
  7100. return ctx->device->pipeline_get_rows_f32[src0->type];
  7101. }
  7102. return nullptr;
  7103. case GGML_OP_ACC:
  7104. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7105. return ctx->device->pipeline_acc_f32;
  7106. }
  7107. return nullptr;
  7108. case GGML_OP_ADD:
  7109. case GGML_OP_SUB:
  7110. case GGML_OP_MUL:
  7111. case GGML_OP_DIV:
  7112. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7113. (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
  7114. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
  7115. return nullptr;
  7116. }
  7117. switch (op) {
  7118. case GGML_OP_ADD:
  7119. {
  7120. if (ctx->num_additional_fused_ops > 0) {
  7121. if (ctx->do_add_rms_partials) {
  7122. return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops];
  7123. } else {
  7124. return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  7125. }
  7126. }
  7127. if (ctx->do_add_rms_partials) {
  7128. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_rms_norepeat : ctx->device->pipeline_add_rms;
  7129. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7130. } else {
  7131. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add;
  7132. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7133. }
  7134. }
  7135. case GGML_OP_SUB:
  7136. {
  7137. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub;
  7138. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7139. }
  7140. case GGML_OP_MUL:
  7141. {
  7142. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul;
  7143. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7144. }
  7145. case GGML_OP_DIV:
  7146. {
  7147. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div;
  7148. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  7149. }
  7150. default:
  7151. break;
  7152. }
  7153. return nullptr;
  7154. case GGML_OP_ADD_ID:
  7155. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) {
  7156. return ctx->device->pipeline_add_id_f32;
  7157. }
  7158. return nullptr;
  7159. case GGML_OP_CONCAT:
  7160. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7161. return ctx->device->pipeline_concat_f32;
  7162. }
  7163. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7164. return ctx->device->pipeline_concat_f16;
  7165. }
  7166. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  7167. return ctx->device->pipeline_concat_i32;
  7168. }
  7169. return nullptr;
  7170. case GGML_OP_UPSCALE:
  7171. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7172. ggml_scale_mode mode = (ggml_scale_mode)(ggml_get_op_params_i32(dst, 0) & 0xFF);
  7173. switch (mode) {
  7174. case GGML_SCALE_MODE_NEAREST:
  7175. return ctx->device->pipeline_upscale_nearest_f32;
  7176. case GGML_SCALE_MODE_BILINEAR:
  7177. return ctx->device->pipeline_upscale_bilinear_f32;
  7178. case GGML_SCALE_MODE_BICUBIC:
  7179. return ctx->device->pipeline_upscale_bicubic_f32;
  7180. default:
  7181. return nullptr;
  7182. }
  7183. }
  7184. return nullptr;
  7185. case GGML_OP_SCALE:
  7186. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7187. return ctx->device->pipeline_scale_f32;
  7188. }
  7189. return nullptr;
  7190. case GGML_OP_SQR:
  7191. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7192. return ctx->device->pipeline_sqr_f32;
  7193. }
  7194. return nullptr;
  7195. case GGML_OP_SQRT:
  7196. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7197. return ctx->device->pipeline_sqrt_f32;
  7198. }
  7199. return nullptr;
  7200. case GGML_OP_SIN:
  7201. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7202. return ctx->device->pipeline_sin_f32;
  7203. }
  7204. return nullptr;
  7205. case GGML_OP_COS:
  7206. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7207. return ctx->device->pipeline_cos_f32;
  7208. }
  7209. return nullptr;
  7210. case GGML_OP_LOG:
  7211. if (src0->type == dst->type &&
  7212. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7213. return ctx->device->pipeline_log[dst->type == GGML_TYPE_F16];
  7214. }
  7215. return nullptr;
  7216. case GGML_OP_TRI:
  7217. if (src0->type == dst->type &&
  7218. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7219. return ctx->device->pipeline_tri[dst->type == GGML_TYPE_F16];
  7220. }
  7221. return nullptr;
  7222. case GGML_OP_DIAG:
  7223. if (src0->type == dst->type &&
  7224. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7225. return ctx->device->pipeline_diag[dst->type == GGML_TYPE_F16];
  7226. }
  7227. return nullptr;
  7228. case GGML_OP_CLAMP:
  7229. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7230. return ctx->device->pipeline_clamp_f32;
  7231. }
  7232. return nullptr;
  7233. case GGML_OP_PAD:
  7234. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7235. return ctx->device->pipeline_pad_f32;
  7236. }
  7237. return nullptr;
  7238. case GGML_OP_ROLL:
  7239. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7240. return ctx->device->pipeline_roll_f32;
  7241. }
  7242. return nullptr;
  7243. case GGML_OP_REPEAT:
  7244. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  7245. return ctx->device->pipeline_repeat_f32;
  7246. }
  7247. return nullptr;
  7248. case GGML_OP_REPEAT_BACK:
  7249. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7250. return ctx->device->pipeline_repeat_back_f32;
  7251. }
  7252. return nullptr;
  7253. case GGML_OP_CPY:
  7254. case GGML_OP_CONT:
  7255. case GGML_OP_DUP:
  7256. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  7257. case GGML_OP_SET_ROWS:
  7258. if (src1->type == GGML_TYPE_I64) {
  7259. return ctx->device->pipeline_set_rows_i64[dst->type];
  7260. } else {
  7261. return ctx->device->pipeline_set_rows_i32[dst->type];
  7262. }
  7263. case GGML_OP_SILU_BACK:
  7264. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7265. return ctx->device->pipeline_silu_back_f32;
  7266. }
  7267. return nullptr;
  7268. case GGML_OP_NORM:
  7269. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7270. return ctx->device->pipeline_norm_f32;
  7271. }
  7272. return nullptr;
  7273. case GGML_OP_GROUP_NORM:
  7274. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7275. return ctx->device->pipeline_group_norm_f32;
  7276. }
  7277. return nullptr;
  7278. case GGML_OP_RMS_NORM:
  7279. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7280. if (ctx->do_add_rms_partials) {
  7281. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32;
  7282. } else {
  7283. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32;
  7284. }
  7285. }
  7286. return nullptr;
  7287. case GGML_OP_RMS_NORM_BACK:
  7288. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7289. return ctx->device->pipeline_rms_norm_back_f32;
  7290. }
  7291. return nullptr;
  7292. case GGML_OP_L2_NORM:
  7293. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7294. return ctx->device->pipeline_l2_norm_f32;
  7295. }
  7296. return nullptr;
  7297. case GGML_OP_UNARY:
  7298. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7299. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7300. (src0->type != dst->type)) {
  7301. return nullptr;
  7302. }
  7303. switch (ggml_get_unary_op(dst)) {
  7304. case GGML_UNARY_OP_EXP:
  7305. return ctx->device->pipeline_exp[dst->type == GGML_TYPE_F16];
  7306. case GGML_UNARY_OP_SILU:
  7307. return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16];
  7308. case GGML_UNARY_OP_GELU:
  7309. return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16];
  7310. case GGML_UNARY_OP_GELU_ERF:
  7311. return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16];
  7312. case GGML_UNARY_OP_GELU_QUICK:
  7313. return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16];
  7314. case GGML_UNARY_OP_RELU:
  7315. return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16];
  7316. case GGML_UNARY_OP_NEG:
  7317. return ctx->device->pipeline_neg[dst->type == GGML_TYPE_F16];
  7318. case GGML_UNARY_OP_TANH:
  7319. return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16];
  7320. case GGML_UNARY_OP_SIGMOID:
  7321. return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16];
  7322. case GGML_UNARY_OP_HARDSIGMOID:
  7323. return ctx->device->pipeline_hardsigmoid[dst->type == GGML_TYPE_F16];
  7324. case GGML_UNARY_OP_HARDSWISH:
  7325. return ctx->device->pipeline_hardswish[dst->type == GGML_TYPE_F16];
  7326. case GGML_UNARY_OP_ABS:
  7327. return ctx->device->pipeline_abs[dst->type == GGML_TYPE_F16];
  7328. case GGML_UNARY_OP_SOFTPLUS:
  7329. return ctx->device->pipeline_softplus[dst->type == GGML_TYPE_F16];
  7330. case GGML_UNARY_OP_STEP:
  7331. return ctx->device->pipeline_step[dst->type == GGML_TYPE_F16];
  7332. case GGML_UNARY_OP_ROUND:
  7333. return ctx->device->pipeline_round[dst->type == GGML_TYPE_F16];
  7334. case GGML_UNARY_OP_CEIL:
  7335. return ctx->device->pipeline_ceil[dst->type == GGML_TYPE_F16];
  7336. case GGML_UNARY_OP_FLOOR:
  7337. return ctx->device->pipeline_floor[dst->type == GGML_TYPE_F16];
  7338. case GGML_UNARY_OP_TRUNC:
  7339. return ctx->device->pipeline_trunc[dst->type == GGML_TYPE_F16];
  7340. default:
  7341. break;
  7342. }
  7343. return nullptr;
  7344. case GGML_OP_GLU:
  7345. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7346. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7347. (src0->type != dst->type)) {
  7348. return nullptr;
  7349. }
  7350. switch (ggml_get_glu_op(dst)) {
  7351. case GGML_GLU_OP_GEGLU:
  7352. return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16];
  7353. case GGML_GLU_OP_REGLU:
  7354. return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16];
  7355. case GGML_GLU_OP_SWIGLU:
  7356. return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16];
  7357. case GGML_GLU_OP_SWIGLU_OAI:
  7358. return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16];
  7359. case GGML_GLU_OP_GEGLU_ERF:
  7360. return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16];
  7361. case GGML_GLU_OP_GEGLU_QUICK:
  7362. return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16];
  7363. default:
  7364. break;
  7365. }
  7366. return nullptr;
  7367. case GGML_OP_DIAG_MASK_INF:
  7368. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7369. return ctx->device->pipeline_diag_mask_inf_f32;
  7370. }
  7371. return nullptr;
  7372. case GGML_OP_SOFT_MAX:
  7373. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  7374. GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32);
  7375. if (ctx->num_additional_fused_ops) {
  7376. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7377. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7378. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  7379. // use n_experts from push constant if it's not equal to the power of two spec constant
  7380. bool use_push = dst->ne[0] != (1u << idx);
  7381. return ctx->device->pipeline_topk_moe[idx][mode][use_push];
  7382. }
  7383. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  7384. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  7385. }
  7386. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7387. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  7388. }
  7389. return nullptr;
  7390. case GGML_OP_SOFT_MAX_BACK:
  7391. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7392. return ctx->device->pipeline_soft_max_back_f32;
  7393. }
  7394. return nullptr;
  7395. case GGML_OP_ROPE:
  7396. case GGML_OP_ROPE_BACK:
  7397. {
  7398. const ggml_tensor *rope = ctx->num_additional_fused_ops == 2 ? dst->src[0]->src[0] : dst;
  7399. const int mode = ((const int32_t *) rope->op_params)[2];
  7400. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  7401. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  7402. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  7403. if (is_neox) {
  7404. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7405. return ctx->device->pipeline_rope_neox_f32;
  7406. }
  7407. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7408. return ctx->device->pipeline_rope_neox_f32_f16;
  7409. }
  7410. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7411. return ctx->device->pipeline_rope_neox_f16;
  7412. }
  7413. } else if (is_mrope && !is_vision) {
  7414. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7415. return ctx->device->pipeline_rope_multi_f32;
  7416. }
  7417. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7418. return ctx->device->pipeline_rope_multi_f16;
  7419. }
  7420. } else if (is_vision) {
  7421. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7422. return ctx->device->pipeline_rope_vision_f32;
  7423. }
  7424. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7425. return ctx->device->pipeline_rope_vision_f16;
  7426. }
  7427. } else {
  7428. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7429. return ctx->device->pipeline_rope_norm_f32;
  7430. }
  7431. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7432. return ctx->device->pipeline_rope_norm_f32_f16;
  7433. }
  7434. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7435. return ctx->device->pipeline_rope_norm_f16;
  7436. }
  7437. }
  7438. return nullptr;
  7439. }
  7440. case GGML_OP_SUM:
  7441. case GGML_OP_SUM_ROWS:
  7442. case GGML_OP_MEAN:
  7443. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7444. return ctx->device->pipeline_sum_rows_f32;
  7445. }
  7446. return nullptr;
  7447. case GGML_OP_CUMSUM:
  7448. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7449. return ctx->device->pipeline_cumsum_f32;
  7450. }
  7451. return nullptr;
  7452. case GGML_OP_SOLVE_TRI:
  7453. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7454. vk_solve_tri_pipeline_state solve_tri_pipeline_state(src0->ne[0], src1->ne[0]);
  7455. vk_pipeline pipeline = nullptr;
  7456. {
  7457. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7458. auto it = ctx->device->pipeline_solve_tri_f32.find(solve_tri_pipeline_state);
  7459. if (it != ctx->device->pipeline_solve_tri_f32.end()) {
  7460. pipeline = it->second;
  7461. } else {
  7462. ctx->device->pipeline_solve_tri_f32[solve_tri_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7463. }
  7464. }
  7465. return pipeline;
  7466. }
  7467. return nullptr;
  7468. case GGML_OP_ARGMAX:
  7469. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7470. return ctx->device->pipeline_argmax_f32;
  7471. }
  7472. return nullptr;
  7473. case GGML_OP_COUNT_EQUAL:
  7474. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) {
  7475. return ctx->device->pipeline_count_equal_i32;
  7476. }
  7477. return nullptr;
  7478. case GGML_OP_IM2COL:
  7479. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7480. return ctx->device->pipeline_im2col_f32;
  7481. }
  7482. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7483. return ctx->device->pipeline_im2col_f32_f16;
  7484. }
  7485. return nullptr;
  7486. case GGML_OP_IM2COL_3D:
  7487. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7488. return ctx->device->pipeline_im2col_3d_f32;
  7489. }
  7490. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7491. return ctx->device->pipeline_im2col_3d_f32_f16;
  7492. }
  7493. return nullptr;
  7494. case GGML_OP_TIMESTEP_EMBEDDING:
  7495. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7496. return ctx->device->pipeline_timestep_embedding_f32;
  7497. }
  7498. return nullptr;
  7499. case GGML_OP_CONV_TRANSPOSE_1D:
  7500. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7501. return ctx->device->pipeline_conv_transpose_1d_f32;
  7502. }
  7503. return nullptr;
  7504. case GGML_OP_POOL_2D:
  7505. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7506. return ctx->device->pipeline_pool2d_f32;
  7507. }
  7508. return nullptr;
  7509. case GGML_OP_RWKV_WKV6:
  7510. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7511. return ctx->device->pipeline_rwkv_wkv6_f32;
  7512. }
  7513. return nullptr;
  7514. case GGML_OP_RWKV_WKV7:
  7515. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7516. return ctx->device->pipeline_rwkv_wkv7_f32;
  7517. }
  7518. return nullptr;
  7519. case GGML_OP_SSM_SCAN:
  7520. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7521. const uint32_t d_state = src0->ne[0];
  7522. if (d_state == 128) {
  7523. return ctx->device->pipeline_ssm_scan_f32_d128;
  7524. } else if (d_state == 256) {
  7525. return ctx->device->pipeline_ssm_scan_f32_d256;
  7526. }
  7527. }
  7528. return nullptr;
  7529. case GGML_OP_SSM_CONV:
  7530. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7531. return ctx->device->pipeline_ssm_conv_f32;
  7532. }
  7533. return nullptr;
  7534. case GGML_OP_OPT_STEP_ADAMW:
  7535. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7536. return ctx->device->pipeline_opt_step_adamw_f32;
  7537. }
  7538. return nullptr;
  7539. case GGML_OP_OPT_STEP_SGD:
  7540. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7541. return ctx->device->pipeline_opt_step_sgd_f32;
  7542. }
  7543. return nullptr;
  7544. case GGML_OP_LEAKY_RELU:
  7545. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7546. return ctx->device->pipeline_leaky_relu_f32;
  7547. }
  7548. return nullptr;
  7549. case GGML_OP_CONV_2D:
  7550. case GGML_OP_CONV_TRANSPOSE_2D:
  7551. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7552. uint32_t K = dst->ne[2]; // Cout
  7553. uint32_t NPQ = dst->ne[3] * dst->ne[1] * dst->ne[0]; // N * OH * OW
  7554. vk_conv_shapes shape = ggml_vk_conv_select_shape(ctx, K, NPQ);
  7555. bool transpose = dst->op == GGML_OP_CONV_TRANSPOSE_2D;
  7556. uint32_t KW = (uint32_t)src0->ne[0];
  7557. uint32_t KH = (uint32_t)src0->ne[1];
  7558. uint32_t s0 = (uint32_t)(ggml_get_op_params_i32(dst, 0));
  7559. uint32_t s1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 1) : s0;
  7560. uint32_t p0 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 2) : 0;
  7561. uint32_t p1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 3) : 0;
  7562. uint32_t d0 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 4) : 1;
  7563. uint32_t d1 = !transpose ? (uint32_t)ggml_get_op_params_i32(dst, 5) : 1;
  7564. vk_conv2d_pipeline_state conv2d_pipeline_state(s0, s1, p0, p1, d0, d1, KW, KH);
  7565. std::map<vk_conv2d_pipeline_state, vk_pipeline> *pipelines = nullptr;
  7566. if (op == GGML_OP_CONV_2D) {
  7567. if (src0->type == GGML_TYPE_F32) {
  7568. pipelines = &ctx->device->pipeline_conv2d_f32[shape];
  7569. } else if (src0->type == GGML_TYPE_F16) {
  7570. pipelines = &ctx->device->pipeline_conv2d_f16_f32[shape];
  7571. }
  7572. } else if (op == GGML_OP_CONV_TRANSPOSE_2D) {
  7573. if (src0->type == GGML_TYPE_F32) {
  7574. pipelines = &ctx->device->pipeline_conv_transpose_2d_f32[shape];
  7575. } else if (src0->type == GGML_TYPE_F16) {
  7576. pipelines = &ctx->device->pipeline_conv_transpose_2d_f16_f32[shape];
  7577. }
  7578. }
  7579. vk_pipeline pipeline = nullptr;
  7580. {
  7581. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7582. auto it = pipelines->find(conv2d_pipeline_state);
  7583. if (it != pipelines->end()) {
  7584. pipeline = it->second;
  7585. } else {
  7586. (*pipelines)[conv2d_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7587. }
  7588. }
  7589. return pipeline;
  7590. }
  7591. return nullptr;
  7592. case GGML_OP_CONV_2D_DW:
  7593. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7594. if (ggml_is_contiguous(src1)) {
  7595. return ctx->device->pipeline_conv2d_dw_whcn_f32;
  7596. } else if (ggml_is_contiguous_channels(src1)) {
  7597. return ctx->device->pipeline_conv2d_dw_cwhn_f32;
  7598. }
  7599. } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7600. if (ggml_is_contiguous(src1)) {
  7601. return ctx->device->pipeline_conv2d_dw_whcn_f16_f32;
  7602. } else if (ggml_is_contiguous_channels(src1)) {
  7603. return ctx->device->pipeline_conv2d_dw_cwhn_f16_f32;
  7604. }
  7605. }
  7606. return nullptr;
  7607. case GGML_OP_ADD1:
  7608. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7609. return ctx->device->pipeline_add1_f16_f16;
  7610. }
  7611. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7612. return ctx->device->pipeline_add1_f16_f32;
  7613. }
  7614. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7615. return ctx->device->pipeline_add1_f32_f32;
  7616. }
  7617. return nullptr;
  7618. case GGML_OP_ARANGE:
  7619. if (dst->type == GGML_TYPE_F32) {
  7620. return ctx->device->pipeline_arange_f32;
  7621. }
  7622. return nullptr;
  7623. case GGML_OP_FILL:
  7624. if (dst->type == GGML_TYPE_F32) {
  7625. return ctx->device->pipeline_fill_f32;
  7626. }
  7627. return nullptr;
  7628. default:
  7629. return nullptr;
  7630. }
  7631. GGML_UNUSED(src2);
  7632. }
  7633. 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) {
  7634. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7635. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7636. p.misalign_offsets = (a_offset << 16) | d_offset;
  7637. GGML_UNUSED(src1);
  7638. GGML_UNUSED(src2);
  7639. GGML_UNUSED(src3);
  7640. }
  7641. 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) {
  7642. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7643. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7644. p.misalign_offsets = (a_offset << 16) | d_offset;
  7645. GGML_UNUSED(src1);
  7646. GGML_UNUSED(src2);
  7647. GGML_UNUSED(src3);
  7648. }
  7649. 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) {
  7650. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7651. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7652. p.misalign_offsets = (a_offset << 16) | d_offset;
  7653. GGML_UNUSED(src1);
  7654. GGML_UNUSED(src2);
  7655. GGML_UNUSED(src3);
  7656. }
  7657. 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) {
  7658. const uint32_t a_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7659. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7660. p.misalign_offsets = (a_offset << 16) | d_offset;
  7661. GGML_UNUSED(src0);
  7662. GGML_UNUSED(src2);
  7663. GGML_UNUSED(src3);
  7664. }
  7665. 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) {
  7666. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7667. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7668. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7669. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  7670. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  7671. GGML_UNUSED(src2);
  7672. GGML_UNUSED(src3);
  7673. }
  7674. 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) {
  7675. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7676. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7677. p.a_offset = a_offset;
  7678. p.d_offset = d_offset;
  7679. GGML_UNUSED(src1);
  7680. GGML_UNUSED(src2);
  7681. GGML_UNUSED(src3);
  7682. }
  7683. template<typename PC>
  7684. 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) {
  7685. 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];
  7686. if (src1 != nullptr) {
  7687. 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];
  7688. }
  7689. if (src2 != nullptr) {
  7690. 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];
  7691. }
  7692. if (src3 != nullptr) {
  7693. 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];
  7694. }
  7695. 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];
  7696. std::cerr << "), " << ggml_op_name(op) << ")");
  7697. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  7698. GGML_ASSERT(dst->buffer != nullptr);
  7699. const uint64_t ne00 = src0->ne[0];
  7700. const uint64_t ne01 = src0->ne[1];
  7701. const uint64_t ne02 = src0->ne[2];
  7702. const uint64_t ne03 = src0->ne[3];
  7703. const bool use_src1 = src1 != nullptr;
  7704. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  7705. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  7706. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  7707. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  7708. const bool use_src2 = src2 != nullptr;
  7709. const bool use_src3 = src3 != nullptr;
  7710. init_pushconst_fastdiv(pc);
  7711. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  7712. if (pipeline == nullptr) {
  7713. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  7714. if (src1 != nullptr) {
  7715. std::cerr << " and " << ggml_type_name(src1->type);
  7716. }
  7717. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  7718. GGML_ABORT("fatal error");
  7719. }
  7720. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7721. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0, true);
  7722. vk_subbuffer src1_buf = use_src1 ? ggml_vk_tensor_subbuffer(ctx, src1, true) : vk_subbuffer{};
  7723. vk_subbuffer src2_buf = use_src2 ? ggml_vk_tensor_subbuffer(ctx, src2, true) : vk_subbuffer{};
  7724. vk_subbuffer src3_buf = use_src3 ? ggml_vk_tensor_subbuffer(ctx, src3, true) : vk_subbuffer{};
  7725. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true);
  7726. // Compute misalignment offset for descriptors and store it in in push constants.
  7727. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, src3, dst);
  7728. std::array<uint32_t, 3> elements;
  7729. switch (op) {
  7730. case GGML_OP_NORM:
  7731. case GGML_OP_RMS_NORM_BACK:
  7732. case GGML_OP_L2_NORM:
  7733. case GGML_OP_SOFT_MAX:
  7734. case GGML_OP_SOFT_MAX_BACK:
  7735. case GGML_OP_SUM_ROWS:
  7736. case GGML_OP_CUMSUM:
  7737. case GGML_OP_MEAN:
  7738. case GGML_OP_ARGMAX:
  7739. {
  7740. const uint32_t nr = ggml_nrows(src0);
  7741. if (nr > 262144) {
  7742. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7743. } else if (nr > 512) {
  7744. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7745. } else {
  7746. elements = { nr, 1, 1 };
  7747. }
  7748. } break;
  7749. case GGML_OP_SOLVE_TRI:
  7750. {
  7751. uint32_t nr = (uint32_t)(ne02 * ne03);
  7752. if (nr > 262144) {
  7753. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7754. } else if (nr > 512) {
  7755. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7756. } else {
  7757. elements = { nr, 1, 1 };
  7758. }
  7759. }
  7760. break;
  7761. case GGML_OP_RMS_NORM:
  7762. if (ctx->do_add_rms_partials) {
  7763. // Run one element per thread, 128 threads per workgroup
  7764. elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 };
  7765. } else {
  7766. elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 };
  7767. }
  7768. break;
  7769. case GGML_OP_SUM:
  7770. // We use GGML_OP_SUM_ROWS with 1 row.
  7771. elements = { 1, 1, 1 };
  7772. break;
  7773. case GGML_OP_GROUP_NORM:
  7774. {
  7775. const uint32_t num_groups = dst->op_params[0];
  7776. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  7777. } break;
  7778. case GGML_OP_DIAG_MASK_INF:
  7779. case GGML_OP_ROPE:
  7780. case GGML_OP_ROPE_BACK:
  7781. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  7782. break;
  7783. case GGML_OP_GET_ROWS:
  7784. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  7785. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7786. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7787. break;
  7788. case GGML_OP_ARGSORT:
  7789. GGML_ASSERT(0);
  7790. break;
  7791. case GGML_OP_IM2COL:
  7792. {
  7793. const bool is_2D = dst->op_params[6] == 1;
  7794. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  7795. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  7796. const uint32_t KW = src0->ne[0];
  7797. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  7798. const uint32_t OW = dst->ne[1];
  7799. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  7800. elements = { OW * KW * KH, OH, batch * IC };
  7801. } break;
  7802. case GGML_OP_IM2COL_3D:
  7803. {
  7804. const uint32_t IC = ((const uint32_t *)(dst->op_params))[9];
  7805. const uint32_t N = ne13 / IC;
  7806. const uint32_t KD = ne02;
  7807. const uint32_t KH = ne01;
  7808. const uint32_t KW = ne00;
  7809. const uint32_t OD = dst->ne[3] / N;
  7810. const uint32_t OH = dst->ne[2];
  7811. const uint32_t OW = dst->ne[1];
  7812. const uint32_t IC_KD_KH_KW = IC*KD*KH*KW;
  7813. const uint32_t N_OD_OH = N*OD*OH;
  7814. elements = { IC_KD_KH_KW, OW, N_OD_OH };
  7815. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7816. } break;
  7817. case GGML_OP_TIMESTEP_EMBEDDING:
  7818. {
  7819. const uint32_t dim = dst->op_params[0];
  7820. uint32_t half_ceil = (dim + 1) / 2;
  7821. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  7822. } break;
  7823. case GGML_OP_CONV_TRANSPOSE_1D:
  7824. {
  7825. elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1}
  7826. } break;
  7827. case GGML_OP_POOL_2D:
  7828. {
  7829. const uint32_t N = dst->ne[3];
  7830. const uint32_t OC = dst->ne[2];
  7831. const uint32_t OH = dst->ne[1];
  7832. const uint32_t OW = dst->ne[0];
  7833. elements = { N * OC * OH * OW, 1, 1};
  7834. } break;
  7835. case GGML_OP_CONV_2D:
  7836. case GGML_OP_CONV_TRANSPOSE_2D:
  7837. if constexpr (std::is_same_v<PC, vk_op_conv2d_push_constants>) {
  7838. const uint32_t NPQ = pc.N * pc.OH * pc.OW;
  7839. const vk_conv_shapes shape = ggml_vk_conv_select_shape(ctx, pc.Cout, NPQ);
  7840. const uint32_t NPQ_blocks = CEIL_DIV(NPQ, vk_conv_block_sizes[shape].NPQ);
  7841. elements = { pc.Cout, NPQ_blocks, 1 };
  7842. if (elements[1] > 512) {
  7843. elements[2] = CEIL_DIV(elements[1], 512);
  7844. elements[1] = 512;
  7845. }
  7846. } else {
  7847. GGML_ABORT("invalid push constant type for CONV_2D");
  7848. }
  7849. break;
  7850. case GGML_OP_ADD:
  7851. case GGML_OP_SUB:
  7852. case GGML_OP_DIV:
  7853. case GGML_OP_MUL:
  7854. case GGML_OP_ADD1:
  7855. case GGML_OP_ARANGE:
  7856. case GGML_OP_FILL:
  7857. case GGML_OP_SCALE:
  7858. case GGML_OP_SQR:
  7859. case GGML_OP_SQRT:
  7860. case GGML_OP_SIN:
  7861. case GGML_OP_COS:
  7862. case GGML_OP_LOG:
  7863. case GGML_OP_TRI:
  7864. case GGML_OP_DIAG:
  7865. case GGML_OP_CLAMP:
  7866. case GGML_OP_PAD:
  7867. case GGML_OP_ROLL:
  7868. case GGML_OP_REPEAT:
  7869. case GGML_OP_REPEAT_BACK:
  7870. case GGML_OP_CPY:
  7871. case GGML_OP_CONCAT:
  7872. case GGML_OP_UPSCALE:
  7873. case GGML_OP_UNARY:
  7874. case GGML_OP_GLU:
  7875. case GGML_OP_CONV_2D_DW:
  7876. {
  7877. uint32_t ne = ggml_nelements(dst);
  7878. if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7879. // Convert from number of logical elements to 2- or 4-byte units.
  7880. ne /= ggml_blck_size(src0->type);
  7881. if ((ggml_type_size(src0->type) % 4) == 0) {
  7882. ne *= ggml_type_size(src0->type) / 4;
  7883. } else {
  7884. ne *= ggml_type_size(src0->type) / 2;
  7885. }
  7886. }
  7887. // copy_to_quant has block size of 32, and each thread does QUANT_K elements.
  7888. // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements.
  7889. // So divide by block size here before splitting into 512x512 groups.
  7890. if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7891. ne = CEIL_DIV(ne, ggml_blck_size(dst->type));
  7892. }
  7893. if (ne > 262144) {
  7894. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7895. } else if (ne > 512) {
  7896. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7897. } else {
  7898. elements = { ne, 1, 1 };
  7899. }
  7900. if (pipeline == ctx->device->pipeline_cpy_transpose_32 ||
  7901. pipeline == ctx->device->pipeline_cpy_transpose_16) {
  7902. // 32x32 tiles
  7903. elements[0] = (uint32_t)CEIL_DIV(dst->ne[0], 32);
  7904. elements[1] = (uint32_t)CEIL_DIV(dst->ne[1], 32);
  7905. elements[2] = (uint32_t)(dst->ne[2]*dst->ne[3]);
  7906. elements[0] = std::min(elements[0], ctx->device->properties.limits.maxComputeWorkGroupCount[0]);
  7907. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7908. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7909. }
  7910. } break;
  7911. case GGML_OP_ADD_ID:
  7912. {
  7913. elements = { (uint32_t)ne01, (uint32_t)ne02, 1 };
  7914. } break;
  7915. case GGML_OP_SET_ROWS:
  7916. {
  7917. uint32_t ne = ggml_nelements(src0);
  7918. if (ggml_is_quantized(dst->type)) {
  7919. // quants run 32 threads each doing QUANT_K elements
  7920. ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type));
  7921. } else {
  7922. // scalar types do one element per thread, running 512 threads
  7923. ne = CEIL_DIV(ne, 512);
  7924. }
  7925. if (ne > 262144) {
  7926. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7927. } else if (ne > 512) {
  7928. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7929. } else {
  7930. elements = { ne, 1, 1 };
  7931. }
  7932. }
  7933. break;
  7934. case GGML_OP_SSM_CONV:
  7935. {
  7936. const uint32_t nr = src0->ne[1];
  7937. const uint32_t n_t = dst->ne[1];
  7938. const uint32_t n_s = dst->ne[2];
  7939. elements = { nr, n_t, n_s };
  7940. }
  7941. break;
  7942. default:
  7943. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  7944. break;
  7945. }
  7946. if (op == GGML_OP_ADD || op == GGML_OP_RMS_NORM) {
  7947. vk_subbuffer a_buf = src0_buf;
  7948. if (ctx->do_add_rms_partials) {
  7949. a_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset);
  7950. }
  7951. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7952. { src0_buf, src1_buf, dst_buf, a_buf }, pc, elements);
  7953. } else if (op == GGML_OP_GLU) {
  7954. // Empty src1 is possible in glu, but the shader needs a buffer
  7955. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  7956. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc, elements);
  7957. } else if (op == GGML_OP_SOFT_MAX) {
  7958. // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer
  7959. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  7960. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  7961. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, subbuf2, dst_buf }, pc, elements);
  7962. } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) {
  7963. // Empty src2 and src3 is possible in rope, but the shader needs a buffer
  7964. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  7965. vk_subbuffer subbuf3 = use_src3 ? src3_buf : src0_buf;
  7966. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, subbuf2, dst_buf, subbuf3 }, pc, elements);
  7967. } else if (op == GGML_OP_IM2COL || op == GGML_OP_IM2COL_3D) {
  7968. if (ctx->device->shader_int64 && ctx->device->buffer_device_address) {
  7969. // buffer device address path doesn't use dst buffer
  7970. dst_buf.size = 1;
  7971. }
  7972. // im2col uses only src1 and dst buffers
  7973. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src1_buf, dst_buf }, pc, elements);
  7974. } else if (op == GGML_OP_COUNT_EQUAL) {
  7975. // count_equal assumes that destination buffer is initialized with zeroes
  7976. ggml_vk_buffer_memset_async(subctx, dst_buf.buffer, dst_buf.offset, 0, dst_buf.size);
  7977. ggml_vk_sync_buffers(ctx, subctx);
  7978. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  7979. } else if (op == GGML_OP_OPT_STEP_SGD) {
  7980. // OPT_STEP_SGD works on src0, it does not need dst
  7981. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf }, pc, elements);
  7982. } else if (use_src3) {
  7983. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, src3_buf, dst_buf }, pc, elements);
  7984. } else if (use_src2) {
  7985. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, dst_buf }, pc, elements);
  7986. } else if (use_src1) {
  7987. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  7988. } else {
  7989. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, dst_buf }, pc, elements);
  7990. }
  7991. }
  7992. 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) {
  7993. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7994. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7995. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7996. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GET_ROWS, {
  7997. (uint32_t)ggml_nelements(src0),
  7998. (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,
  7999. (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,
  8000. (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,
  8001. 0,
  8002. 0.0f, 0.0f, 0,
  8003. });
  8004. }
  8005. static void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8006. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8007. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8008. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8009. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  8010. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  8011. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  8012. int offset = dst->op_params[3] / 4; // offset in bytes
  8013. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ACC, {
  8014. (uint32_t)ggml_nelements(src0),
  8015. (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,
  8016. (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,
  8017. (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,
  8018. 0,
  8019. 0.0f, 0.0f, offset,
  8020. });
  8021. }
  8022. static void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  8023. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  8024. const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  8025. // Make a list of all the tensors used by the op.
  8026. // Last element of the list is the dest tensor.
  8027. const ggml_tensor *tensors[MAX_PARAMETER_COUNT];
  8028. uint32_t num_srcs = ctx->num_additional_fused_ops + 2;
  8029. uint32_t num_tensors = num_srcs + 1;
  8030. GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT);
  8031. tensors[0] = first_node->src[0];
  8032. tensors[1] = first_node->src[1];
  8033. for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) {
  8034. // check whether the previous result is src[0] or src[1]
  8035. if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) {
  8036. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1];
  8037. } else {
  8038. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0];
  8039. }
  8040. }
  8041. tensors[num_srcs] = dst;
  8042. vk_op_multi_add_push_constants pc;
  8043. pc.ne20 = (uint32_t)dst->ne[0];
  8044. pc.ne21 = (uint32_t)dst->ne[1];
  8045. pc.ne22 = (uint32_t)dst->ne[2];
  8046. pc.ne23 = (uint32_t)dst->ne[3];
  8047. for (uint32_t i = 0; i < num_tensors; ++i) {
  8048. const ggml_tensor *t = tensors[i];
  8049. pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float);
  8050. pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float);
  8051. pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float);
  8052. pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float);
  8053. }
  8054. pc.rms_partials = ctx->do_add_rms_partials;
  8055. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, tensors[0], tensors[1], nullptr, dst, dst->op);
  8056. if (pipeline == nullptr) {
  8057. std::cerr << "ggml_vulkan: Error: Missing multi_add";
  8058. GGML_ABORT("fatal error");
  8059. }
  8060. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8061. ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT];
  8062. vk_buffer buf[MAX_PARAMETER_COUNT];
  8063. size_t offset[MAX_PARAMETER_COUNT];
  8064. bool uma[MAX_PARAMETER_COUNT];
  8065. for (uint32_t i = 0; i < num_tensors; ++i) {
  8066. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8067. buf[i] = nullptr;
  8068. offset[i] = 0;
  8069. uma[i] = false;
  8070. if (ctx->device->uma) {
  8071. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8072. uma[i] = buf[i] != nullptr;
  8073. }
  8074. if (!uma[i]) {
  8075. buf[i] = buf_ctx[i]->dev_buffer;
  8076. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8077. }
  8078. GGML_ASSERT(buf[i] != nullptr);
  8079. }
  8080. // If any remaining descriptors are unused, just point them at src[0]
  8081. for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) {
  8082. buf[i] = buf[0];
  8083. offset[i] = 0;
  8084. }
  8085. if (ctx->do_add_rms_partials) {
  8086. buf[num_tensors] = ctx->prealloc_add_rms_partials;
  8087. offset[num_tensors] = ctx->prealloc_size_add_rms_partials_offset;
  8088. }
  8089. std::array<uint32_t, 3> elements;
  8090. uint32_t ne = ggml_nelements(dst);
  8091. if (ne > 262144) {
  8092. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  8093. } else if (ne > 512) {
  8094. elements = { 512, CEIL_DIV(ne, 512), 1 };
  8095. } else {
  8096. elements = { ne, 1, 1 };
  8097. }
  8098. static_assert(MAX_PARAMETER_COUNT == 12);
  8099. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8100. {
  8101. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8102. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8103. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8104. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8105. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8106. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8107. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8108. ggml_vk_subbuffer(ctx, buf[7], offset[7]),
  8109. ggml_vk_subbuffer(ctx, buf[8], offset[8]),
  8110. ggml_vk_subbuffer(ctx, buf[9], offset[9]),
  8111. ggml_vk_subbuffer(ctx, buf[10], offset[10]),
  8112. ggml_vk_subbuffer(ctx, buf[11], offset[11]),
  8113. }, pc, elements);
  8114. }
  8115. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8116. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8117. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8118. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8119. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD, {
  8120. (uint32_t)ggml_nelements(src0),
  8121. (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,
  8122. (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,
  8123. (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,
  8124. 0,
  8125. 0.0f, 0.0f, ctx->do_add_rms_partials,
  8126. });
  8127. }
  8128. static void ggml_vk_sub(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8129. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8130. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8131. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8132. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SUB, {
  8133. (uint32_t)ggml_nelements(src0),
  8134. (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,
  8135. (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,
  8136. (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,
  8137. 0,
  8138. 0.0f, 0.0f, 0,
  8139. });
  8140. }
  8141. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8142. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8143. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8144. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8145. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_MUL, {
  8146. (uint32_t)ggml_nelements(src0),
  8147. (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,
  8148. (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,
  8149. (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,
  8150. 0,
  8151. 0.0f, 0.0f, 0,
  8152. });
  8153. }
  8154. static void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8155. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8156. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8157. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8158. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_DIV, {
  8159. (uint32_t)ggml_nelements(src0),
  8160. (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,
  8161. (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,
  8162. (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,
  8163. 0,
  8164. 0.0f, 0.0f, 0,
  8165. });
  8166. }
  8167. 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) {
  8168. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8169. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8170. const uint32_t src2_type_size = ggml_type_size(src2->type);
  8171. ggml_vk_op_f32<vk_op_add_id_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_ADD_ID, {
  8172. (uint32_t)dst->ne[0],
  8173. (uint32_t)dst->ne[1],
  8174. (uint32_t)src0->nb[1] / src0_type_size,
  8175. (uint32_t)src0->nb[2] / src0_type_size,
  8176. (uint32_t)src1->nb[1] / src1_type_size,
  8177. (uint32_t)src2->nb[1] / src2_type_size,
  8178. });
  8179. }
  8180. 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) {
  8181. GGML_ASSERT(version == 6 || version == 7);
  8182. int num_srcs = version == 6 ? 6 : 7;
  8183. for (int i = 0; i < num_srcs; i++) {
  8184. GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type));
  8185. }
  8186. GGML_ASSERT(dst->buffer != nullptr);
  8187. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op);
  8188. GGML_ASSERT(pipeline != nullptr);
  8189. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8190. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8191. vk_subbuffer src_buf[7] = {};
  8192. for (int i = 0; i < num_srcs; i++) {
  8193. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8194. }
  8195. std::array<uint32_t, 3> elements = {
  8196. (uint32_t)(pc.B * pc.H),
  8197. 1,
  8198. 1
  8199. };
  8200. if (version == 6) {
  8201. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8202. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf},
  8203. pc, elements);
  8204. } else if (version == 7) {
  8205. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8206. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8207. pc, elements);
  8208. } else {
  8209. // shouldn't happen
  8210. GGML_ASSERT(false);
  8211. }
  8212. }
  8213. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8214. const size_t seq_length = dst->src[0]->ne[2];
  8215. const size_t n_embed = dst->ne[0];
  8216. const size_t n_heads = dst->src[0]->ne[1];
  8217. const size_t n_seqs = dst->src[5]->ne[1];
  8218. ggml_vk_op_f32_wkv(
  8219. ctx, subctx, dst,
  8220. {
  8221. (uint32_t)n_seqs,
  8222. (uint32_t)seq_length,
  8223. (uint32_t)n_embed,
  8224. (uint32_t)n_heads,
  8225. },
  8226. 6
  8227. );
  8228. }
  8229. static void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8230. const size_t seq_length = dst->src[0]->ne[2];
  8231. const size_t n_embed = dst->ne[0];
  8232. const size_t n_heads = dst->src[0]->ne[1];
  8233. const size_t n_seqs = dst->src[6]->ne[1];
  8234. ggml_vk_op_f32_wkv(
  8235. ctx, subctx, dst,
  8236. {
  8237. (uint32_t)n_seqs,
  8238. (uint32_t)seq_length,
  8239. (uint32_t)n_embed,
  8240. (uint32_t)n_heads,
  8241. },
  8242. 7
  8243. );
  8244. }
  8245. static void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8246. const ggml_tensor * src0 = dst->src[0];
  8247. const ggml_tensor * src1 = dst->src[1];
  8248. const ggml_tensor * src2 = dst->src[2];
  8249. const ggml_tensor * src3 = dst->src[3];
  8250. const ggml_tensor * src4 = dst->src[4];
  8251. const ggml_tensor * src5 = dst->src[5];
  8252. GGML_ASSERT(dst->buffer != nullptr);
  8253. const uint32_t head_dim = src0->ne[1];
  8254. const uint32_t n_head = src1->ne[1];
  8255. const uint32_t n_group = src4->ne[1];
  8256. const uint32_t n_tok = src1->ne[2];
  8257. const uint32_t n_seq = src1->ne[3];
  8258. bool is_mamba2 = (src3->nb[1] == sizeof(float));
  8259. GGML_ASSERT(is_mamba2);
  8260. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op);
  8261. GGML_ASSERT(pipeline != nullptr);
  8262. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8263. const int64_t s_off = ggml_nelements(src1) * sizeof(float);
  8264. const vk_op_ssm_scan_push_constants pc = {
  8265. (uint32_t)src0->nb[2], (uint32_t)src0->nb[3],
  8266. (uint32_t)src1->nb[2], (uint32_t)src1->nb[3],
  8267. (uint32_t)src2->nb[1], (uint32_t)src2->nb[2],
  8268. (uint32_t)src3->nb[1],
  8269. (uint32_t)src4->nb[2], (uint32_t)src4->nb[3],
  8270. (uint32_t)src5->nb[2], (uint32_t)src5->nb[3],
  8271. (uint32_t)s_off,
  8272. n_head, head_dim, n_group, n_tok
  8273. };
  8274. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8275. vk_subbuffer src_buf[7] = {};
  8276. for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
  8277. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8278. }
  8279. std::array<uint32_t, 3> elements;
  8280. const int splitH = 16;
  8281. const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, splitH);
  8282. const uint32_t num_workgroups_y = n_seq;
  8283. elements = { num_workgroups_x, num_workgroups_y, 1 };
  8284. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8285. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8286. pc, elements);
  8287. }
  8288. static void ggml_vk_ssm_conv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8289. const ggml_tensor * src0 = dst->src[0];
  8290. const ggml_tensor * src1 = dst->src[1];
  8291. ggml_vk_op_f32<vk_op_ssm_conv_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SSM_CONV, {
  8292. (uint32_t)src0->nb[1], (uint32_t)src0->nb[2],
  8293. (uint32_t)src1->nb[1],
  8294. (uint32_t)dst->nb[0], (uint32_t)dst->nb[1], (uint32_t)dst->nb[2],
  8295. (uint32_t)src1->ne[0],
  8296. (uint32_t)src0->ne[0],
  8297. (uint32_t)src0->ne[1],
  8298. (uint32_t)dst->ne[1],
  8299. (uint32_t)dst->ne[2],
  8300. });
  8301. }
  8302. 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) {
  8303. const ggml_tensor * x = dst->src[0];
  8304. const ggml_tensor * g = dst->src[1];
  8305. const ggml_tensor * gm = dst->src[2];
  8306. const ggml_tensor * gv = dst->src[3];
  8307. const ggml_tensor * p = dst->src[4];
  8308. GGML_ASSERT(x->type == GGML_TYPE_F32);
  8309. GGML_ASSERT(g->type == GGML_TYPE_F32);
  8310. GGML_ASSERT(gm->type == GGML_TYPE_F32);
  8311. GGML_ASSERT(gv->type == GGML_TYPE_F32);
  8312. GGML_ASSERT(p->type == GGML_TYPE_F32);
  8313. GGML_ASSERT(dst->buffer != nullptr);
  8314. GGML_ASSERT(ggml_is_contiguous(x));
  8315. GGML_ASSERT(ggml_is_contiguous(g));
  8316. GGML_ASSERT(ggml_is_contiguous(gm));
  8317. GGML_ASSERT(ggml_is_contiguous(gv));
  8318. GGML_ASSERT(ggml_is_contiguous(p));
  8319. GGML_ASSERT(ggml_are_same_shape(x, g));
  8320. GGML_ASSERT(ggml_are_same_shape(x, gm));
  8321. GGML_ASSERT(ggml_are_same_shape(x, gv));
  8322. GGML_ASSERT(ggml_nelements(p) == 7);
  8323. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW);
  8324. GGML_ASSERT(pipeline != nullptr);
  8325. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8326. vk_subbuffer x_buf = ggml_vk_tensor_subbuffer(ctx, x);
  8327. vk_subbuffer g_buf = ggml_vk_tensor_subbuffer(ctx, g);
  8328. vk_subbuffer gm_buf = ggml_vk_tensor_subbuffer(ctx, gm);
  8329. vk_subbuffer gv_buf = ggml_vk_tensor_subbuffer(ctx, gv);
  8330. vk_subbuffer p_buf = ggml_vk_tensor_subbuffer(ctx, p);
  8331. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(x), 1, 1 };
  8332. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8333. {x_buf, g_buf, gm_buf, gv_buf, p_buf},
  8334. pc, elements);
  8335. }
  8336. static void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8337. const size_t n = ggml_nelements(dst->src[0]);
  8338. ggml_vk_op_f32_opt_step_adamw(
  8339. ctx, subctx, dst,
  8340. { (uint32_t)n, 0, 0.0f, 0.0f }
  8341. );
  8342. }
  8343. 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) {
  8344. const size_t n = ggml_nelements(dst->src[0]);
  8345. 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 });
  8346. }
  8347. static void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8348. int * op_params = (int *)dst->op_params;
  8349. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8350. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8351. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8352. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONCAT, {
  8353. (uint32_t)ggml_nelements(dst),
  8354. (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,
  8355. (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,
  8356. (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,
  8357. 0,
  8358. 0.0f, 0.0f, op_params[0],
  8359. });
  8360. }
  8361. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8362. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8363. const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0);
  8364. GGML_TENSOR_UNARY_OP_LOCALS
  8365. float sf0 = (float)ne0 / ne00;
  8366. float sf1 = (float)ne1 / ne01;
  8367. float sf2 = (float)ne2 / ne02;
  8368. float sf3 = (float)ne3 / ne03;
  8369. float pixel_offset = 0.5f;
  8370. if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) {
  8371. sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0;
  8372. sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1;
  8373. pixel_offset = 0.0f;
  8374. }
  8375. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  8376. (uint32_t)ggml_nelements(dst), 0, 0,
  8377. (uint32_t)ne00, (uint32_t)ne01,
  8378. (uint32_t)nb00 / src0_type_size, (uint32_t)nb01 / src0_type_size, (uint32_t)nb02 / src0_type_size, (uint32_t)nb03 / src0_type_size,
  8379. (uint32_t)ne0, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  8380. sf0, sf1, sf2, sf3, pixel_offset
  8381. });
  8382. }
  8383. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8384. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8385. p.param1 = ggml_get_op_params_f32(dst, 0);
  8386. p.param2 = ggml_get_op_params_f32(dst, 1);
  8387. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p));
  8388. }
  8389. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8390. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst));
  8391. }
  8392. static void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8393. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst));
  8394. }
  8395. static void ggml_vk_add1(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8396. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8397. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8398. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8399. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD1, {
  8400. (uint32_t)ggml_nelements(src0),
  8401. (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,
  8402. (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,
  8403. (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,
  8404. 0,
  8405. 0.0f, 0.0f, 0,
  8406. });
  8407. }
  8408. static void ggml_vk_arange(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8409. VK_LOG_DEBUG("ggml_vk_arange(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")");
  8410. vk_op_push_constants pc = {
  8411. (uint32_t)ggml_nelements(dst),
  8412. 1,
  8413. ggml_get_op_params_f32(dst, 0),
  8414. ggml_get_op_params_f32(dst, 2),
  8415. };
  8416. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_ARANGE);
  8417. GGML_ASSERT(pipeline != nullptr);
  8418. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8419. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
  8420. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(dst), 1, 1 };
  8421. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
  8422. }
  8423. static void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8424. VK_LOG_DEBUG("ggml_vk_fill(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")");
  8425. vk_op_push_constants pc = {
  8426. (uint32_t)ggml_nelements(dst),
  8427. 1,
  8428. ggml_get_op_params_f32(dst, 0),
  8429. 0.0f,
  8430. };
  8431. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_FILL);
  8432. GGML_ASSERT(pipeline != nullptr);
  8433. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8434. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
  8435. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(dst), 1, 1 };
  8436. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
  8437. }
  8438. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8439. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst));
  8440. }
  8441. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8442. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst));
  8443. }
  8444. static void ggml_vk_log(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8445. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_LOG, vk_op_unary_push_constants_init(src0, dst));
  8446. }
  8447. static void ggml_vk_tri(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8448. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8449. p.param1 = ggml_get_op_params_f32(dst, 0);
  8450. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TRI, std::move(p));
  8451. }
  8452. static void ggml_vk_diag(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8453. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8454. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_DIAG, std::move(p));
  8455. }
  8456. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8457. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8458. p.param1 = ggml_get_op_params_f32(dst, 0);
  8459. p.param2 = ggml_get_op_params_f32(dst, 1);
  8460. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p));
  8461. }
  8462. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8463. vk_op_pad_push_constants p = vk_op_pad_push_constants_init(src0, dst);
  8464. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p));
  8465. }
  8466. static void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8467. const int32_t s0 = ggml_get_op_params_i32(dst, 0);
  8468. const int32_t s1 = ggml_get_op_params_i32(dst, 1);
  8469. const int32_t s2 = ggml_get_op_params_i32(dst, 2);
  8470. const int32_t s3 = ggml_get_op_params_i32(dst, 3);
  8471. const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
  8472. const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
  8473. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8474. memcpy(&p.param1, &s01_packed, sizeof(float));
  8475. memcpy(&p.param2, &s23_packed, sizeof(float));
  8476. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p));
  8477. }
  8478. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8479. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8480. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p));
  8481. }
  8482. static void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8483. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8484. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p));
  8485. }
  8486. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8487. uint32_t ne = (uint32_t)ggml_nelements(src0);
  8488. if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8489. // Convert from number of logical elements to 2- or 4-byte units.
  8490. ne /= ggml_blck_size(src0->type);
  8491. if ((ggml_type_size(src0->type) % 4) == 0) {
  8492. ne *= ggml_type_size(src0->type) / 4;
  8493. } else {
  8494. ne *= ggml_type_size(src0->type) / 2;
  8495. }
  8496. }
  8497. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne);
  8498. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p));
  8499. }
  8500. 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) {
  8501. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8502. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8503. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8504. // Skip empty skip_rows operations. For most ops the empty check at the start
  8505. // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst
  8506. // with empty srcs.
  8507. if (ggml_is_empty(src0) || ggml_is_empty(src1)) {
  8508. return;
  8509. }
  8510. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SET_ROWS, {
  8511. (uint32_t)ggml_nelements(src0),
  8512. (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,
  8513. (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,
  8514. (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,
  8515. 0,
  8516. 0.0f, 0.0f, 0,
  8517. });
  8518. }
  8519. 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) {
  8520. 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 });
  8521. }
  8522. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8523. float * op_params = (float *)dst->op_params;
  8524. 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 });
  8525. }
  8526. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8527. const int * int_op_params = (const int *)dst->op_params;
  8528. const float * float_op_params = (const float *)dst->op_params;
  8529. const uint32_t num_groups = int_op_params[0];
  8530. const float eps = float_op_params[1];
  8531. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  8532. 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 });
  8533. }
  8534. static uint32_t ggml_vk_rms_num_partials(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8535. const uint32_t ne = (uint32_t)node->ne[0];
  8536. const uint32_t denom = ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0];
  8537. const uint32_t num_partials = CEIL_DIV(ne, denom);
  8538. return num_partials;
  8539. }
  8540. static uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8541. const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node);
  8542. const uint32_t num_bytes = ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment);
  8543. return num_bytes;
  8544. }
  8545. 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) {
  8546. const int n_dims = ((const int32_t *) dst->op_params)[1];
  8547. const int mode = ((const int32_t *) dst->op_params)[2];
  8548. // const int n_ctx = ((const int32_t *) dst->op_params)[3];
  8549. const int n_ctx_orig = ((const int32_t *) dst->op_params)[4];
  8550. const float freq_base = ((const float *) dst->op_params)[5];
  8551. const float freq_scale = ((const float *) dst->op_params)[6];
  8552. const float ext_factor = ((const float *) dst->op_params)[7];
  8553. const float attn_factor = ((const float *) dst->op_params)[8];
  8554. const float beta_fast = ((const float *) dst->op_params)[9];
  8555. const float beta_slow = ((const float *) dst->op_params)[10];
  8556. int sections[4] {};
  8557. if (mode & GGML_ROPE_TYPE_MROPE) {
  8558. memcpy(sections, (const int32_t *) dst->op_params + 11, sizeof(int)*4);
  8559. }
  8560. const bool is_imrope = mode == GGML_ROPE_TYPE_IMROPE;
  8561. float corr_dims[2];
  8562. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8563. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  8564. uint32_t nb01 = src0->nb[1] / ggml_type_size(src0->type);
  8565. uint32_t nb02 = src0->nb[2] / ggml_type_size(src0->type);
  8566. vk_op_rope_push_constants rope {
  8567. (uint32_t)mode, (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  8568. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  8569. has_ff, (uint32_t)src0->ne[2], nb01, nb02,
  8570. { sections[0], sections[1], sections[2], sections[3] }, is_imrope, backprop, set_rows_stride,
  8571. };
  8572. return rope;
  8573. }
  8574. 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) {
  8575. ggml_tensor * dst;
  8576. const ggml_tensor * src0;
  8577. const ggml_tensor * src1;
  8578. if (ctx->num_additional_fused_ops > 0) {
  8579. // fused rms_norm + mul
  8580. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8581. ggml_tensor *other_src = mul->src[0] == cgraph->nodes[node_idx + 0] ? mul->src[1] : mul->src[0];
  8582. dst = mul;
  8583. src0 = cgraph->nodes[node_idx]->src[0];
  8584. src1 = other_src;
  8585. } else {
  8586. dst = cgraph->nodes[node_idx];
  8587. src0 = src1 = dst->src[0];
  8588. }
  8589. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8590. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8591. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8592. uint32_t param3 = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0;
  8593. vk_op_binary_push_constants bin {
  8594. (uint32_t)ggml_nelements(src0),
  8595. (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,
  8596. (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,
  8597. (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,
  8598. 0,
  8599. op_params[0], 0.0f, (int32_t)param3,
  8600. };
  8601. // more than one fused op means rms_norm+mul+rope
  8602. if (ctx->num_additional_fused_ops > 1) {
  8603. static constexpr uint32_t max_tensors = 7;
  8604. const ggml_tensor *tensors[max_tensors] {};
  8605. ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  8606. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8607. ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  8608. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  8609. bool do_set_rows = ctx->num_additional_fused_ops == 4;
  8610. tensors[0] = rms->src[0];
  8611. tensors[1] = other_src;
  8612. tensors[2] = mul;
  8613. tensors[3] = rope->src[1]; // pos
  8614. tensors[4] = rope->src[2]; // ff
  8615. tensors[5] = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; // dst
  8616. tensors[6] = do_set_rows ? tensors[5]->src[1] : nullptr;
  8617. const uint32_t set_rows_stride = do_set_rows ? tensors[5]->nb[1] / ggml_type_size(tensors[5]->type) : 0;
  8618. vk_op_rms_norm_mul_rope_push_constants pc;
  8619. pc.bin = bin;
  8620. pc.rope = ggml_vk_make_rope_constants(rope, rope->src[0], tensors[4] != nullptr, false, set_rows_stride);
  8621. 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;
  8622. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8623. ggml_backend_vk_buffer_context * buf_ctx[max_tensors];
  8624. vk_buffer buf[max_tensors];
  8625. size_t offset[max_tensors];
  8626. bool uma[max_tensors];
  8627. for (uint32_t i = 0; i < max_tensors; ++i) {
  8628. if (!tensors[i]) {
  8629. // If any remaining descriptors are unused, just point them at src[0]
  8630. buf[i] = buf[0];
  8631. offset[i] = 0;
  8632. continue;
  8633. }
  8634. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8635. buf[i] = nullptr;
  8636. offset[i] = 0;
  8637. uma[i] = false;
  8638. if (ctx->device->uma) {
  8639. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8640. uma[i] = buf[i] != nullptr;
  8641. }
  8642. if (!uma[i]) {
  8643. buf[i] = buf_ctx[i]->dev_buffer;
  8644. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8645. }
  8646. GGML_ASSERT(buf[i] != nullptr);
  8647. }
  8648. std::array<uint32_t, 3> elements;
  8649. elements = { (uint32_t)rms->src[0]->ne[1], (uint32_t)rms->src[0]->ne[2], (uint32_t)rms->src[0]->ne[3] };
  8650. static_assert(max_tensors == 7);
  8651. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8652. {
  8653. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8654. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8655. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8656. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8657. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8658. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8659. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8660. }, pc, elements);
  8661. } else {
  8662. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM, std::move(bin));
  8663. }
  8664. if (ctx->do_add_rms_partials_offset_calculation) {
  8665. ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0);
  8666. ctx->do_add_rms_partials = false;
  8667. ctx->do_add_rms_partials_offset_calculation = false;
  8668. }
  8669. }
  8670. 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) {
  8671. float * op_params = (float *)dst->op_params;
  8672. 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 });
  8673. }
  8674. static void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8675. float * op_params = (float *)dst->op_params;
  8676. 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 });
  8677. }
  8678. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8679. 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 });
  8680. }
  8681. static void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8682. const float * op_params_f = (const float *)dst->op_params;
  8683. const bool swapped = (bool)dst->op_params[1];
  8684. const bool split = src1 != nullptr;
  8685. const float alpha = op_params_f[2];
  8686. const float limit = op_params_f[3];
  8687. GGML_ASSERT(ggml_is_contiguous(src0));
  8688. if (!split) {
  8689. GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]);
  8690. } else {
  8691. GGML_ASSERT(src0->ne[0] == src1->ne[0]);
  8692. GGML_ASSERT(src0->ne[0] == dst->ne[0]);
  8693. GGML_ASSERT(src0->type == src1->type);
  8694. }
  8695. const uint32_t mode = split ? 2 : (swapped ? 1 : 0);
  8696. ggml_vk_op_f32<vk_op_glu_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GLU,
  8697. {
  8698. (uint32_t)ggml_nelements(dst),
  8699. (uint32_t)src0->ne[0],
  8700. (uint32_t)dst->ne[0],
  8701. mode,
  8702. alpha,
  8703. limit
  8704. });
  8705. }
  8706. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8707. int32_t * op_params = (int32_t *)dst->op_params;
  8708. 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] });
  8709. }
  8710. 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) {
  8711. float * op_params = (float *)dst->op_params;
  8712. float scale = op_params[0];
  8713. float max_bias = op_params[1];
  8714. const uint32_t ncols = (uint32_t)src0->ne[0];
  8715. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  8716. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  8717. const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u;
  8718. const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u;
  8719. const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u;
  8720. const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u;
  8721. const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u;
  8722. const uint32_t n_head_kv = src0->ne[2];
  8723. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  8724. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  8725. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  8726. vk_op_soft_max_push_constants pc {
  8727. ncols,
  8728. src1 != nullptr ? nrows_y : (uint32_t)0,
  8729. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],
  8730. ne12, ne13,
  8731. nb11, nb12, nb13,
  8732. scale, max_bias,
  8733. m0, m1,
  8734. n_head_log2,
  8735. nrows_x,
  8736. src2 != nullptr
  8737. };
  8738. if (ncols <= 16384) {
  8739. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_SOFT_MAX, std::move(pc));
  8740. } else {
  8741. vk_subbuffer buf_a = ggml_vk_tensor_subbuffer(ctx, src0);
  8742. vk_subbuffer buf_b = src1 ? ggml_vk_tensor_subbuffer(ctx, src1) : buf_a;
  8743. vk_subbuffer buf_c = src2 ? ggml_vk_tensor_subbuffer(ctx, src2) : buf_a;
  8744. vk_subbuffer buf_d = ggml_vk_tensor_subbuffer(ctx, dst);
  8745. uint32_t elems_per_wg = 128 * 4;
  8746. uint32_t num_wgs = CEIL_DIV(ncols, elems_per_wg);
  8747. size_t tmp_size = num_wgs * nrows_x * sizeof(float);
  8748. if (ctx->prealloc_size_x < tmp_size) {
  8749. ctx->prealloc_size_x = tmp_size;
  8750. ggml_vk_preallocate_buffers(ctx, subctx);
  8751. }
  8752. if (ctx->prealloc_size_y < tmp_size) {
  8753. ctx->prealloc_size_y = tmp_size;
  8754. ggml_vk_preallocate_buffers(ctx, subctx);
  8755. }
  8756. if (ctx->prealloc_x_need_sync || ctx->prealloc_y_need_sync) {
  8757. ggml_vk_sync_buffers(ctx, subctx);
  8758. }
  8759. vk_subbuffer buf_x = { ctx->prealloc_x, 0, tmp_size };
  8760. vk_subbuffer buf_y = { ctx->prealloc_y, 0, tmp_size };
  8761. std::array<uint32_t, 3> elements = { num_wgs, nrows_x, 1 };
  8762. vk_pipeline pipeline1 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large1_f32_f16 : ctx->device->pipeline_soft_max_large1_f32;
  8763. vk_pipeline pipeline2 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large2_f32_f16 : ctx->device->pipeline_soft_max_large2_f32;
  8764. vk_pipeline pipeline3 = src1 && src1->type == GGML_TYPE_F16 ? ctx->device->pipeline_soft_max_large3_f32_f16 : ctx->device->pipeline_soft_max_large3_f32;
  8765. ggml_pipeline_request_descriptor_sets(ctx, pipeline1, 1);
  8766. ggml_pipeline_request_descriptor_sets(ctx, pipeline2, 1);
  8767. ggml_pipeline_request_descriptor_sets(ctx, pipeline3, 1);
  8768. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline1, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  8769. ggml_vk_sync_buffers(ctx, subctx);
  8770. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline2, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  8771. ggml_vk_sync_buffers(ctx, subctx);
  8772. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline3, { buf_a, buf_b, buf_c, buf_d, buf_x, buf_y }, pc, elements);
  8773. ctx->prealloc_x_need_sync = true;
  8774. ctx->prealloc_y_need_sync = true;
  8775. }
  8776. }
  8777. 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) {
  8778. float * op_params = (float *)dst->op_params;
  8779. 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] });
  8780. }
  8781. static void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  8782. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  8783. ggml_tensor * logits = cgraph->nodes[node_idx + 0]->src[0];
  8784. ggml_tensor * weights = (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) ? cgraph->nodes[node_idx + 9] :
  8785. (mode == TOPK_MOE_EARLY_SOFTMAX) ? cgraph->nodes[node_idx + 4] :
  8786. cgraph->nodes[node_idx + 5];
  8787. ggml_tensor * ids = (mode == TOPK_MOE_LATE_SOFTMAX) ? cgraph->nodes[node_idx + 1] : cgraph->nodes[node_idx + 3];
  8788. GGML_ASSERT(logits->type == GGML_TYPE_F32);
  8789. GGML_ASSERT(weights->type == GGML_TYPE_F32);
  8790. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  8791. const int n_experts = logits->ne[0];
  8792. const int n_rows = logits->ne[1];
  8793. const int n_expert_used = weights->ne[1];
  8794. GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) n_experts);
  8795. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, cgraph->nodes[node_idx], GGML_OP_SOFT_MAX);
  8796. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8797. vk_subbuffer logits_buf = ggml_vk_tensor_subbuffer(ctx, logits);
  8798. vk_subbuffer weights_buf = ggml_vk_tensor_subbuffer(ctx, weights);
  8799. vk_subbuffer ids_buf = ggml_vk_tensor_subbuffer(ctx, ids);
  8800. vk_op_topk_moe_push_constants pc {};
  8801. pc.n_rows = n_rows;
  8802. pc.n_experts_push = n_experts;
  8803. pc.n_expert_used = n_expert_used;
  8804. if (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) {
  8805. ggml_tensor * clamp = cgraph->nodes[node_idx + 7];
  8806. pc.clamp_min = ggml_get_op_params_f32(clamp, 0);
  8807. pc.clamp_max = ggml_get_op_params_f32(clamp, 1);
  8808. }
  8809. GGML_ASSERT(n_expert_used <= n_experts);
  8810. const uint32_t rows_per_block = 4;
  8811. std::array<uint32_t, 3> elements = { CEIL_DIV(n_rows, rows_per_block), 1, 1 };
  8812. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {logits_buf, weights_buf, ids_buf}, pc, elements);
  8813. }
  8814. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_cgraph * cgraph, int node_idx, bool backprop) {
  8815. ggml_tensor * dst = cgraph->nodes[node_idx];
  8816. const ggml_tensor * src0 = dst->src[0];
  8817. const ggml_tensor * src1 = dst->src[1];
  8818. const ggml_tensor * src2 = dst->src[2];
  8819. const ggml_tensor * src3 = nullptr;
  8820. const int n_dims = ((int32_t *) dst->op_params)[1];
  8821. const int mode = ((int32_t *) dst->op_params)[2];
  8822. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  8823. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  8824. const float freq_base = ((float *) dst->op_params)[5];
  8825. const float beta_fast = ((float *) dst->op_params)[9];
  8826. const float beta_slow = ((float *) dst->op_params)[10];
  8827. int sections[4] {};
  8828. if (mode & GGML_ROPE_TYPE_MROPE) {
  8829. memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4);
  8830. }
  8831. float corr_dims[2];
  8832. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8833. uint32_t set_rows_stride = 0;
  8834. // Fused rope + view + set_rows passes the set_rows destination stride in set_rows_stride
  8835. // and overrides the dst and sets src3=row_indices
  8836. if (ctx->num_additional_fused_ops > 0) {
  8837. set_rows_stride = cgraph->nodes[node_idx + 2]->nb[1] / ggml_type_size(cgraph->nodes[node_idx + 2]->type);
  8838. src3 = cgraph->nodes[node_idx + 2]->src[1];
  8839. dst = cgraph->nodes[node_idx + 2];
  8840. }
  8841. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, src3, dst, GGML_OP_ROPE,
  8842. ggml_vk_make_rope_constants(cgraph->nodes[node_idx], src0, src2 != nullptr, backprop, set_rows_stride));
  8843. }
  8844. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8845. const uint32_t * op_params = (const uint32_t *)dst->op_params;
  8846. uint32_t ncols = src0->ne[0];
  8847. uint32_t nrows = ggml_nrows(src0);
  8848. uint32_t ncols_pad_log2 = (uint32_t)ceilf(log2f(float(ncols)));
  8849. uint32_t ncolsp2 = 1 << ncols_pad_log2;
  8850. vk_op_argsort_push_constants pc { ncols, ncolsp2, ncols_pad_log2, nrows, op_params[0], 0, 0, 0, 0, };
  8851. // Pick the largest workgroup size <= ncolsp2
  8852. uint32_t pipeline_idx = std::min(ncols_pad_log2, num_argsort_pipelines - 1);
  8853. // Use the "small" argsort shader if the whole sort can be done by a single workgroup.
  8854. bool use_small = ncols_pad_log2 <= ctx->device->max_workgroup_size_log2 &&
  8855. ctx->device->pipeline_argsort_f32[pipeline_idx] != nullptr;
  8856. vk_pipeline pipeline = use_small ? ctx->device->pipeline_argsort_f32[pipeline_idx]
  8857. : ctx->device->pipeline_argsort_large_f32[pipeline_idx];
  8858. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  8859. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8860. vk_subbuffer subbuf1 = dst_buf;
  8861. // Reserve space for ivec2 per element, with rows padded to a power of two
  8862. if (!use_small) {
  8863. const size_t x_sz = size_t{ncolsp2} * nrows * 2 * sizeof(int);
  8864. if (ctx->prealloc_size_x < x_sz) {
  8865. ctx->prealloc_size_x = x_sz;
  8866. ggml_vk_preallocate_buffers(ctx, subctx);
  8867. }
  8868. if (ctx->prealloc_x_need_sync) {
  8869. ggml_vk_sync_buffers(ctx, subctx);
  8870. }
  8871. subbuf1 = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  8872. }
  8873. std::array<uint32_t, 3> elements;
  8874. elements[0] = ncolsp2;
  8875. elements[1] = std::min((uint32_t)ggml_nrows(src0), ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  8876. elements[2] = 1;
  8877. // First dispatch initializes tmp_idx and does the first N passes where
  8878. // there is only communication between threads in the same workgroup.
  8879. {
  8880. vk_op_argsort_push_constants pc2 = pc;
  8881. pc2.outer_start = 0;
  8882. pc2.outer_end = std::min(ncols_pad_log2, ctx->device->max_workgroup_size_log2);
  8883. pc2.inner_start = 0;
  8884. pc2.inner_end = 100;
  8885. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8886. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements);
  8887. }
  8888. if (!use_small) {
  8889. ggml_vk_sync_buffers(ctx, subctx);
  8890. // Loop over outer/inner passes, synchronizing between each pass.
  8891. for (uint32_t outer = ctx->device->max_workgroup_size_log2; outer < ncols_pad_log2; ++outer) {
  8892. for (uint32_t inner = 0; inner < outer + 1; ++inner) {
  8893. vk_op_argsort_push_constants pc2 = pc;
  8894. pc2.outer_start = outer;
  8895. pc2.outer_end = outer + 1;
  8896. pc2.inner_start = inner;
  8897. pc2.inner_end = inner + 1;
  8898. // When the inner idx is large enough, there's only communication
  8899. // within a workgroup. So the remaining inner iterations can all
  8900. // run in the same dispatch.
  8901. if (outer - inner < pipeline_idx) {
  8902. pc2.inner_end = 100;
  8903. inner = outer;
  8904. pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx];
  8905. } else {
  8906. // Smaller workgroup empirically seems to perform better
  8907. pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx - 2];
  8908. }
  8909. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8910. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements);
  8911. ggml_vk_sync_buffers(ctx, subctx);
  8912. }
  8913. }
  8914. ctx->prealloc_x_need_sync = true;
  8915. }
  8916. }
  8917. static void ggml_vk_topk(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8918. uint32_t ncols = src0->ne[0];
  8919. uint32_t nrows = ggml_nrows(src0);
  8920. uint32_t k = dst->ne[0];
  8921. vk_op_topk_push_constants pc { ncols, ncols, ncols, k, nrows, 0, 0 };
  8922. if (ctx->prealloc_x_need_sync) {
  8923. ggml_vk_sync_buffers(ctx, subctx);
  8924. }
  8925. std::array<uint32_t, 3> elements;
  8926. elements[1] = std::min(nrows, ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  8927. elements[2] = 1;
  8928. uint32_t num_elements = ncols;
  8929. // Each iteration reduces a workgroup's worth of elements down to the K
  8930. // largest elements. Repeat until we have the top K elements.
  8931. // Need to do at least one iteration to write out the results.
  8932. bool done_one_iter = false;
  8933. uint32_t dbl_buf_index = 0;
  8934. size_t dbl_buf_size;
  8935. while (num_elements > k || !done_one_iter) {
  8936. // Prefer going as small as num_topk_pipelines - 3 for perf reasons.
  8937. // But if K is larger, then we need a larger workgroup
  8938. uint32_t max_pipeline = num_topk_pipelines - 1;
  8939. uint32_t preferred_pipeline = std::max(num_topk_pipelines - 3, (uint32_t)log2f(float(k)) + 2);
  8940. max_pipeline = std::min(preferred_pipeline, max_pipeline);
  8941. uint32_t min_pipeline = (uint32_t)log2f(float(k)) + 1;
  8942. // require full subgroup
  8943. min_pipeline = std::max(min_pipeline, ctx->device->subgroup_size_log2);
  8944. uint32_t pipeline_idx = (uint32_t)ceilf(log2f(float(num_elements)));
  8945. pipeline_idx = std::min(pipeline_idx, max_pipeline);
  8946. pipeline_idx = std::max(pipeline_idx, min_pipeline);
  8947. if (num_elements > (1u << pipeline_idx)) {
  8948. // If we could finish on this loop iteration (i.e. a single workgroup)
  8949. // then do so. It's better than the overhead of another pass.
  8950. for (uint32_t i = pipeline_idx; i < num_topk_pipelines; ++i) {
  8951. if (num_elements <= (1u << i)) {
  8952. pipeline_idx = i;
  8953. break;
  8954. }
  8955. }
  8956. }
  8957. vk_pipeline pipeline = ctx->device->pipeline_topk_f32[pipeline_idx];
  8958. // If the device doesn't support a pipeline this large, use smaller
  8959. while (!pipeline) {
  8960. pipeline_idx--;
  8961. GGML_ASSERT(pipeline_idx >= min_pipeline);
  8962. pipeline = ctx->device->pipeline_topk_f32[pipeline_idx];
  8963. }
  8964. vk_op_topk_push_constants pc2 = pc;
  8965. pc2.ncols_input = num_elements;
  8966. // Number of elements remaining after this pass
  8967. uint32_t num_dst_elements = (num_elements / pipeline->wg_denoms[0]) * k + std::min(k, num_elements % pipeline->wg_denoms[0]);
  8968. pc2.ncols_output = num_dst_elements;
  8969. if (!done_one_iter) {
  8970. // Reserve space for ivec2 per element, double buffered
  8971. // K per workgroup per row
  8972. dbl_buf_size = num_dst_elements * nrows * 2 * sizeof(int);
  8973. dbl_buf_size = ROUNDUP_POW2(dbl_buf_size, ctx->device->properties.limits.minStorageBufferOffsetAlignment);
  8974. const size_t x_sz = dbl_buf_size * 2;
  8975. if (ctx->prealloc_size_x < x_sz) {
  8976. ctx->prealloc_size_x = x_sz;
  8977. ggml_vk_preallocate_buffers(ctx, subctx);
  8978. }
  8979. }
  8980. vk_subbuffer src_buf;
  8981. vk_subbuffer dst_buf;
  8982. if (num_elements == ncols) {
  8983. pc2.first_pass = 1;
  8984. src_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  8985. } else {
  8986. src_buf = { ctx->prealloc_x, dbl_buf_index * dbl_buf_size, dbl_buf_size };
  8987. }
  8988. if (num_dst_elements == k) {
  8989. pc2.last_pass = 1;
  8990. dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8991. } else {
  8992. dst_buf = { ctx->prealloc_x, (dbl_buf_index ^ 1) * dbl_buf_size, dbl_buf_size };
  8993. }
  8994. elements[0] = num_elements;
  8995. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8996. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src_buf, dst_buf }, pc2, elements);
  8997. num_elements = num_dst_elements;
  8998. dbl_buf_index ^= 1;
  8999. if (num_elements > k) {
  9000. ggml_vk_sync_buffers(ctx, subctx);
  9001. }
  9002. done_one_iter = true;
  9003. }
  9004. ctx->prealloc_x_need_sync = true;
  9005. }
  9006. static void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9007. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, ggml_nelements(src0));
  9008. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM, p);
  9009. }
  9010. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9011. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9012. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, p);
  9013. }
  9014. static void ggml_vk_mean(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9015. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9016. p.weight = 1.0f / (float)src0->ne[0];
  9017. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_MEAN, p);
  9018. }
  9019. static void ggml_vk_cumsum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9020. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  9021. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CUMSUM, p);
  9022. }
  9023. static void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9024. 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 });
  9025. }
  9026. 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) {
  9027. 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 });
  9028. }
  9029. 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) {
  9030. const uint32_t src0_type_size = ggml_type_size(src0->type);
  9031. const uint32_t src1_type_size = ggml_type_size(src1->type);
  9032. const uint32_t dst_type_size = ggml_type_size(dst->type);
  9033. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SOLVE_TRI, {
  9034. (uint32_t)ggml_nelements(src0),
  9035. (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,
  9036. (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,
  9037. (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,
  9038. 0,
  9039. 0.0f, 0.0f, 0,
  9040. });
  9041. }
  9042. static void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  9043. const int32_t s0 = dst->op_params[0];
  9044. const int32_t s1 = dst->op_params[1];
  9045. const int32_t p0 = dst->op_params[2];
  9046. const int32_t p1 = dst->op_params[3];
  9047. const int32_t d0 = dst->op_params[4];
  9048. const int32_t d1 = dst->op_params[5];
  9049. const bool is_2D = dst->op_params[6] == 1;
  9050. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  9051. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  9052. const uint32_t IW = src1->ne[0];
  9053. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  9054. const uint32_t KW = src0->ne[0];
  9055. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  9056. const uint32_t OW = dst->ne[1];
  9057. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  9058. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  9059. const uint32_t pelements = OW * KW * KH;
  9060. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  9061. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  9062. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  9063. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL, {
  9064. dst_addr,
  9065. batch_offset, offset_delta,
  9066. IC, IW, IH, OW, OH, KW, KH,
  9067. pelements,
  9068. IC * KH * KW,
  9069. s0, s1, p0, p1, d0, d1,
  9070. });
  9071. }
  9072. 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) {
  9073. GGML_TENSOR_BINARY_OP_LOCALS
  9074. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  9075. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  9076. const int32_t s2 = ((const int32_t *)(dst->op_params))[2];
  9077. const int32_t p0 = ((const int32_t *)(dst->op_params))[3];
  9078. const int32_t p1 = ((const int32_t *)(dst->op_params))[4];
  9079. const int32_t p2 = ((const int32_t *)(dst->op_params))[5];
  9080. const int32_t d0 = ((const int32_t *)(dst->op_params))[6];
  9081. const int32_t d1 = ((const int32_t *)(dst->op_params))[7];
  9082. const int32_t d2 = ((const int32_t *)(dst->op_params))[8];
  9083. const int32_t IC = ((const int32_t *)(dst->op_params))[9];
  9084. const int64_t N = ne13 / IC;
  9085. const int64_t ID = ne12;
  9086. const int64_t IH = ne11;
  9087. const int64_t IW = ne10;
  9088. const int64_t KD = ne02;
  9089. const int64_t KH = ne01;
  9090. const int64_t KW = ne00;
  9091. const int64_t OD = ne3 / N;
  9092. const int64_t OH = ne2;
  9093. const int64_t OW = ne1;
  9094. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  9095. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  9096. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  9097. vk_op_im2col_3d_push_constants pc {};
  9098. pc.dst_addr = dst_addr;
  9099. pc.nb10 = nb10 / ggml_type_size(src1->type);
  9100. pc.nb11 = nb11 / ggml_type_size(src1->type);
  9101. pc.nb12 = nb12 / ggml_type_size(src1->type);
  9102. pc.nb13 = nb13 / ggml_type_size(src1->type);
  9103. pc.s0 = s0;
  9104. pc.s1 = s1;
  9105. pc.s2 = s2;
  9106. pc.p0 = p0;
  9107. pc.p1 = p1;
  9108. pc.p2 = p2;
  9109. pc.d0 = d0;
  9110. pc.d1 = d1;
  9111. pc.d2 = d2;
  9112. pc.IW = IW;
  9113. pc.IH = IH;
  9114. pc.ID = ID;
  9115. pc.IC = IC;
  9116. pc.KW = KW;
  9117. pc.OH = OH;
  9118. pc.KD_KH_KW = KD*KH*KW;
  9119. pc.KH_KW = KH*KW;
  9120. pc.IC_KD_KH_KW = IC*KD*KH*KW;
  9121. pc.N_OD_OH = N*OD*OH;
  9122. pc.OD_OH = OD*OH;
  9123. pc.OD_OH_OW_IC_KD_KH_KW = OD*OH*OW*IC*KD*KH*KW;
  9124. pc.OH_OW_IC_KD_KH_KW = OH*OW*IC*KD*KH*KW;
  9125. pc.OW_IC_KD_KH_KW = OW*IC*KD*KH*KW;
  9126. ggml_vk_op_f32<vk_op_im2col_3d_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL_3D, std::move(pc));
  9127. }
  9128. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9129. const uint32_t dim = dst->op_params[0];
  9130. const uint32_t max_period = dst->op_params[1];
  9131. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  9132. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  9133. nb1, dim, max_period,
  9134. });
  9135. }
  9136. 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) {
  9137. // src0: (K, Cout, Cin, 1) -- kernel
  9138. // src1: (L, Cin, 1, 1) -- input
  9139. // dst: (*, Cout, 1, 1)
  9140. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  9141. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  9142. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  9143. GGML_TENSOR_BINARY_OP_LOCALS
  9144. GGML_ASSERT(nb00 == sizeof(float));
  9145. GGML_ASSERT(nb10 == sizeof(float));
  9146. const int32_t s0 = dst->op_params[0];
  9147. vk_op_conv_transpose_1d_push_constants p{};
  9148. p.Cout = static_cast<uint32_t>(ne01);
  9149. p.Cin = static_cast<uint32_t>(ne02);
  9150. p.K = static_cast<uint32_t>(ne00);
  9151. p.L = static_cast<uint32_t>(ne10);
  9152. p.KL = static_cast<uint32_t>(ne0);
  9153. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  9154. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  9155. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  9156. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  9157. p.s0 = static_cast<uint32_t>(s0);
  9158. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p));
  9159. }
  9160. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9161. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  9162. const int32_t k1 = dst->op_params[1];
  9163. const int32_t k0 = dst->op_params[2];
  9164. const int32_t s1 = dst->op_params[3];
  9165. const int32_t s0 = dst->op_params[4];
  9166. const int32_t p1 = dst->op_params[5];
  9167. const int32_t p0 = dst->op_params[6];
  9168. const uint32_t IH = src0->ne[1];
  9169. const uint32_t IW = src0->ne[0];
  9170. const uint32_t N = dst->ne[3];
  9171. const uint32_t OC = dst->ne[2];
  9172. const uint32_t OH = dst->ne[1];
  9173. const uint32_t OW = dst->ne[0];
  9174. const uint32_t parallel_elements = N * OC * OH * OW;
  9175. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  9176. IW, IH, OW, OH, OC,
  9177. parallel_elements,
  9178. op,
  9179. k0, k1, s0, s1, p0, p1,
  9180. });
  9181. }
  9182. static void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  9183. const ggml_tensor * src1, ggml_tensor * dst) {
  9184. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  9185. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  9186. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  9187. GGML_TENSOR_BINARY_OP_LOCALS
  9188. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  9189. GGML_ASSERT(nb10 == sizeof(float));
  9190. GGML_ASSERT(nb0 == sizeof(float));
  9191. bool transpose = dst->op == GGML_OP_CONV_TRANSPOSE_2D;
  9192. vk_op_conv2d_push_constants p{};
  9193. p.Cout = static_cast<uint32_t>(!transpose ? ne03 : ne02);
  9194. p.Cin = static_cast<uint32_t>(!transpose ? ne02 : ne03);
  9195. p.N = static_cast<uint32_t>(ne13);
  9196. GGML_ASSERT(p.Cout == ne2);
  9197. GGML_ASSERT(p.Cin == ne12);
  9198. p.W = static_cast<uint32_t>(ne10);
  9199. p.H = static_cast<uint32_t>(ne11);
  9200. p.OW = static_cast<uint32_t>(ne0);
  9201. p.OH = static_cast<uint32_t>(ne1);
  9202. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  9203. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  9204. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  9205. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  9206. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  9207. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  9208. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  9209. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  9210. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  9211. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, dst->op, std::move(p));
  9212. }
  9213. 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) {
  9214. vk_op_conv2d_dw_push_constants p{};
  9215. p.ne = ggml_nelements(dst);
  9216. p.channels = dst->ne[2];
  9217. p.batches = dst->ne[3];
  9218. p.dst_w = dst->ne[0];
  9219. p.dst_h = dst->ne[1];
  9220. p.src_w = src1->ne[0];
  9221. p.src_h = src1->ne[1];
  9222. p.knl_w = src0->ne[0];
  9223. p.knl_h = src0->ne[1];
  9224. p.stride_x = dst->op_params[0];
  9225. p.stride_y = dst->op_params[1];
  9226. p.pad_x = dst->op_params[2];
  9227. p.pad_y = dst->op_params[3];
  9228. p.dilation_x = dst->op_params[4];
  9229. p.dilation_y = dst->op_params[5];
  9230. GGML_ASSERT(src0->ne[3] == p.channels);
  9231. GGML_ASSERT(src1->ne[3] == p.batches);
  9232. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p));
  9233. }
  9234. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  9235. const float * op_params = (const float *)dst->op_params;
  9236. 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 });
  9237. }
  9238. #ifdef GGML_VULKAN_RUN_TESTS
  9239. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  9240. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  9241. return;
  9242. }
  9243. i0 = std::max(i0, 5);
  9244. i1 = std::max(i1, 5);
  9245. i2 = std::max(i2, 0);
  9246. fprintf(stderr, " ");
  9247. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9248. fprintf(stderr, "%7d ", idx1);
  9249. }
  9250. fprintf(stderr, "\n");
  9251. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9252. fprintf(stderr, "%7d: ", idx0);
  9253. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9254. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  9255. float val;
  9256. if (type == GGML_TYPE_F32) {
  9257. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  9258. } else if (type == GGML_TYPE_F16) {
  9259. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  9260. } else {
  9261. GGML_ABORT("fatal error");
  9262. }
  9263. fprintf(stderr, "% 7.2f ", val);
  9264. } else {
  9265. fprintf(stderr, " ");
  9266. }
  9267. }
  9268. fprintf(stderr, "\n");
  9269. }
  9270. }
  9271. template <typename X_TYPE, typename Y_TYPE>
  9272. 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) {
  9273. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  9274. const size_t x_ne = m * k * batch;
  9275. const size_t y_ne = k * n * batch;
  9276. const size_t d_ne = m * n * batch;
  9277. vk_pipeline p;
  9278. std::string shname;
  9279. if (shader_size == 0) {
  9280. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9281. p = ctx->device->pipeline_matmul_f32->a_s;
  9282. shname = "F32_ALIGNED_S";
  9283. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9284. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  9285. shname = "F32_F16_ALIGNED_S";
  9286. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9287. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  9288. shname = "F16_F32_ALIGNED_S";
  9289. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9290. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  9291. shname = "F16_ALIGNED_S";
  9292. } else {
  9293. GGML_ABORT("fatal error");
  9294. }
  9295. } else if (shader_size == 1) {
  9296. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9297. p = ctx->device->pipeline_matmul_f32->a_m;
  9298. shname = "F32_ALIGNED_M";
  9299. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9300. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  9301. shname = "F32_F16_ALIGNED_M";
  9302. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9303. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  9304. shname = "F16_F32_ALIGNED_M";
  9305. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9306. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  9307. shname = "F16_ALIGNED_M";
  9308. } else {
  9309. GGML_ABORT("fatal error");
  9310. }
  9311. } else if (shader_size == 2) {
  9312. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9313. p = ctx->device->pipeline_matmul_f32->a_l;
  9314. shname = "F32_ALIGNED_L";
  9315. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9316. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  9317. shname = "F32_F16_ALIGNED_L";
  9318. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9319. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  9320. shname = "F16_F32_ALIGNED_L";
  9321. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9322. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  9323. shname = "F16_ALIGNED_L";
  9324. } else {
  9325. GGML_ABORT("fatal error");
  9326. }
  9327. } else {
  9328. GGML_ASSERT(0);
  9329. }
  9330. const size_t kpad = ggml_vk_align_size(k, p->align);
  9331. if (k != kpad) {
  9332. if (shader_size == 0) {
  9333. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9334. p = ctx->device->pipeline_matmul_f32->s;
  9335. shname = "F32_S";
  9336. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9337. p = ctx->device->pipeline_matmul_f32_f16->s;
  9338. shname = "F32_F16_S";
  9339. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9340. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  9341. shname = "F16_F32_S";
  9342. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9343. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  9344. shname = "F16_S";
  9345. }
  9346. } else if (shader_size == 1) {
  9347. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9348. p = ctx->device->pipeline_matmul_f32->m;
  9349. shname = "F32_M";
  9350. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9351. p = ctx->device->pipeline_matmul_f32_f16->m;
  9352. shname = "F32_F16_M";
  9353. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9354. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  9355. shname = "F16_F32_M";
  9356. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9357. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  9358. shname = "F16_M";
  9359. }
  9360. } else if (shader_size == 2) {
  9361. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9362. p = ctx->device->pipeline_matmul_f32->l;
  9363. shname = "F32_L";
  9364. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9365. p = ctx->device->pipeline_matmul_f32_f16->l;
  9366. shname = "F32_F16_L";
  9367. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9368. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  9369. shname = "F16_F32_L";
  9370. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9371. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  9372. shname = "F16_L";
  9373. }
  9374. }
  9375. }
  9376. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9377. if (split_k > 1) {
  9378. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9379. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9380. // Resize buffer
  9381. if (ctx->prealloc_split_k != nullptr) {
  9382. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9383. }
  9384. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9385. }
  9386. }
  9387. ggml_pipeline_allocate_descriptor_sets(ctx);
  9388. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9389. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9390. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9391. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  9392. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  9393. float* d = (float *) malloc(sizeof(float) * d_ne);
  9394. for (size_t i = 0; i < x_ne; i++) {
  9395. if (std::is_same<float, X_TYPE>()) {
  9396. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9397. // x[i] = 1.0f;
  9398. // x[i] = i + 1;
  9399. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9400. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9401. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9402. // x[i] = ggml_fp32_to_fp16(1.0f);
  9403. // x[i] = ggml_fp32_to_fp16(i + 1);
  9404. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9405. } else {
  9406. GGML_ABORT("fatal error");
  9407. }
  9408. }
  9409. for (size_t i = 0; i < y_ne; i++) {
  9410. if (std::is_same<float, Y_TYPE>()) {
  9411. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9412. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9413. // y[i] = i + 1;
  9414. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9415. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9416. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9417. // y[i] = ggml_fp32_to_fp16(i + 1);
  9418. } else {
  9419. GGML_ABORT("fatal error");
  9420. }
  9421. }
  9422. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  9423. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  9424. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9425. ggml_vk_ctx_begin(ctx->device, subctx);
  9426. for (size_t i = 0; i < num_it; i++) {
  9427. ggml_vk_matmul(
  9428. 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),
  9429. m, n, k,
  9430. k, k, m, k*m, k*n, m*n,
  9431. split_k, batch, batch, batch, 1, 1, n
  9432. );
  9433. }
  9434. ggml_vk_ctx_end(subctx);
  9435. auto begin = std::chrono::high_resolution_clock::now();
  9436. ggml_vk_submit(subctx, ctx->fence);
  9437. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  9438. ctx->device->device.resetFences({ ctx->fence });
  9439. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9440. auto end = std::chrono::high_resolution_clock::now();
  9441. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9442. // copy dst to host
  9443. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  9444. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  9445. ggml_init_params iparams = {
  9446. /*.mem_size =*/ 1024*1024*1024,
  9447. /*.mem_buffer =*/ NULL,
  9448. /*.no_alloc =*/ true,
  9449. };
  9450. ggml_context * ggml_ctx = ggml_init(iparams);
  9451. ggml_type src0_type;
  9452. ggml_type src1_type;
  9453. if (std::is_same<float, X_TYPE>()) {
  9454. src0_type = GGML_TYPE_F32;
  9455. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9456. src0_type = GGML_TYPE_F16;
  9457. } else {
  9458. GGML_ABORT("fatal error");
  9459. }
  9460. if (std::is_same<float, Y_TYPE>()) {
  9461. src1_type = GGML_TYPE_F32;
  9462. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9463. src1_type = GGML_TYPE_F16;
  9464. } else {
  9465. GGML_ABORT("fatal error");
  9466. }
  9467. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  9468. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  9469. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9470. src0_ggml->data = x;
  9471. src1_ggml->data = y;
  9472. tensor_ggml->data = d_chk;
  9473. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9474. ggml_build_forward_expand(cgraph, tensor_ggml);
  9475. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9476. ggml_free(ggml_ctx);
  9477. double avg_err = 0.0;
  9478. int first_err_n = -1;
  9479. int first_err_m = -1;
  9480. int first_err_b = -1;
  9481. for (size_t i = 0; i < m*n*batch; i++) {
  9482. double err = std::fabs(d[i] - d_chk[i]);
  9483. avg_err += err;
  9484. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9485. first_err_b = i / (m * n);
  9486. first_err_n = (i % (m * n)) / m;
  9487. first_err_m = (i % (m * n)) % m;
  9488. }
  9489. }
  9490. avg_err /= m * n;
  9491. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9492. 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;
  9493. if (avg_err > 0.1 || std::isnan(avg_err)) {
  9494. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9495. std::cerr << "Actual result: " << std::endl << std::endl;
  9496. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9497. std::cerr << "Expected result: " << std::endl << std::endl;
  9498. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9499. if (split_k > 1) {
  9500. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9501. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9502. std::cerr << "d_buf0: " << std::endl << std::endl;
  9503. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9504. std::cerr << "d_buf1: " << std::endl << std::endl;
  9505. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9506. std::cerr << "d_buf2: " << std::endl << std::endl;
  9507. 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);
  9508. std::cerr << "d_buf3: " << std::endl << std::endl;
  9509. 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);
  9510. free(split_k_buf);
  9511. }
  9512. }
  9513. free(d_chk);
  9514. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  9515. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  9516. ggml_vk_destroy_buffer(d_X);
  9517. ggml_vk_destroy_buffer(d_Y);
  9518. ggml_vk_destroy_buffer(d_D);
  9519. free(x);
  9520. free(y);
  9521. free(d);
  9522. }
  9523. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  9524. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  9525. return;
  9526. }
  9527. i0 = std::max(i0, 5);
  9528. i1 = std::max(i1, 5);
  9529. i2 = std::max(i2, 0);
  9530. i3 = std::max(i3, 0);
  9531. fprintf(stderr, " ");
  9532. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9533. fprintf(stderr, "%7d ", idx1);
  9534. }
  9535. fprintf(stderr, "\n");
  9536. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9537. fprintf(stderr, "%7d: ", idx0);
  9538. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9539. 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]) {
  9540. float val;
  9541. if (tensor->type == GGML_TYPE_F32) {
  9542. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  9543. } else if (tensor->type == GGML_TYPE_F16) {
  9544. 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]));
  9545. } else {
  9546. GGML_ABORT("fatal error");
  9547. }
  9548. fprintf(stderr, "% 7.2f ", val);
  9549. } else {
  9550. fprintf(stderr, " ");
  9551. }
  9552. }
  9553. fprintf(stderr, "\n");
  9554. }
  9555. }
  9556. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  9557. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  9558. }
  9559. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  9560. if (quant == GGML_TYPE_F32) {
  9561. memcpy(to, from, sizeof(float) * ne);
  9562. return;
  9563. }
  9564. const auto * tt = ggml_get_type_traits(quant);
  9565. ggml_to_float_t dequant_fn = tt->to_float;
  9566. dequant_fn(from, to, ne);
  9567. }
  9568. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9569. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  9570. const size_t x_sz = sizeof(float) * ne;
  9571. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  9572. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9573. float * x = (float *) malloc(x_sz);
  9574. void * qx = malloc(qx_sz);
  9575. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9576. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9577. float * x_ref = (float *) malloc(x_sz);
  9578. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  9579. for (size_t i = 0; i < ne; i++) {
  9580. x[i] = rand() / (float)RAND_MAX;
  9581. }
  9582. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  9583. ggml_vk_quantize_data(x, qx, ne, quant);
  9584. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  9585. ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9586. ggml_pipeline_allocate_descriptor_sets(ctx);
  9587. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9588. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9589. ggml_vk_ctx_begin(ctx->device, subctx);
  9590. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  9591. 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});
  9592. ggml_vk_ctx_end(subctx);
  9593. auto begin = std::chrono::high_resolution_clock::now();
  9594. ggml_vk_submit(subctx, ctx->fence);
  9595. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9596. ctx->device->device.resetFences({ ctx->fence });
  9597. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9598. auto end = std::chrono::high_resolution_clock::now();
  9599. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9600. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  9601. int first_err = -1;
  9602. double avg_err = 0.0;
  9603. for (size_t i = 0; i < ne; i++) {
  9604. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  9605. avg_err += error;
  9606. if (first_err < 0 && error > 0.05) {
  9607. first_err = i;
  9608. }
  9609. }
  9610. avg_err /= ne;
  9611. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  9612. if (avg_err > 0.1) {
  9613. std::cerr << "first_error = " << first_err << std::endl;
  9614. std::cerr << "Actual result: " << std::endl << std::endl;
  9615. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9616. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  9617. }
  9618. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  9619. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9620. std::cerr << x_ref[i] << ", ";
  9621. }
  9622. std::cerr << std::endl;
  9623. }
  9624. ggml_vk_destroy_buffer(x_buf);
  9625. ggml_vk_destroy_buffer(qx_buf);
  9626. free(x);
  9627. free(qx);
  9628. free(x_ref);
  9629. free(x_chk);
  9630. }
  9631. // This does not work without ggml q8_1 quantization support
  9632. //
  9633. // typedef uint16_t ggml_half;
  9634. // typedef uint32_t ggml_half2;
  9635. //
  9636. // #define QK8_1 32
  9637. // typedef struct {
  9638. // union {
  9639. // struct {
  9640. // ggml_half d; // delta
  9641. // ggml_half s; // d * sum(qs[i])
  9642. // } GGML_COMMON_AGGR_S;
  9643. // ggml_half2 ds;
  9644. // } GGML_COMMON_AGGR_U;
  9645. // int8_t qs[QK8_1]; // quants
  9646. // } block_q8_1;
  9647. //
  9648. // static void ggml_vk_test_quantize(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9649. // VK_LOG_DEBUG("ggml_vk_test_quantize(" << ne << ")");
  9650. // GGML_ASSERT(quant == GGML_TYPE_Q8_1);
  9651. //
  9652. // const size_t x_sz = sizeof(float) * ne;
  9653. // const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9654. // float * x = (float *) malloc(x_sz);
  9655. // block_q8_1 * qx = (block_q8_1 *)malloc(qx_sz);
  9656. // block_q8_1 * qx_res = (block_q8_1 *)malloc(qx_sz);
  9657. // vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9658. // vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9659. //
  9660. // for (size_t i = 0; i < ne; i++) {
  9661. // x[i] = rand() / (float)RAND_MAX;
  9662. // }
  9663. //
  9664. // vk_pipeline p = ggml_vk_get_quantize_pipeline(ctx, quant);
  9665. //
  9666. // ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9667. //
  9668. // ggml_pipeline_allocate_descriptor_sets(ctx);
  9669. //
  9670. // ggml_vk_buffer_write(x_buf, 0, x, x_sz);
  9671. //
  9672. // vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9673. // ggml_vk_ctx_begin(ctx->device, subctx);
  9674. // ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, x_buf), ggml_vk_subbuffer(ctx, qx_buf), ne);
  9675. // ggml_vk_ctx_end(subctx);
  9676. //
  9677. // auto begin = std::chrono::high_resolution_clock::now();
  9678. //
  9679. // ggml_vk_submit(subctx, ctx->fence);
  9680. // VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_quantize waitForFences");
  9681. // ctx->device->device.resetFences({ ctx->fence });
  9682. // ggml_vk_queue_command_pools_cleanup(ctx->device);
  9683. //
  9684. // auto end = std::chrono::high_resolution_clock::now();
  9685. //
  9686. // double ms_quant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9687. // ggml_vk_buffer_read(qx_buf, 0, qx, qx_sz);
  9688. //
  9689. // ggml_vk_quantize_data(x, qx_res, ne, quant);
  9690. //
  9691. // int first_err = -1;
  9692. //
  9693. // for (size_t i = 0; i < ne / 32; i++) {
  9694. // 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));
  9695. //
  9696. // if (first_err < 0 && error > 0.1) {
  9697. // first_err = i;
  9698. // }
  9699. //
  9700. // 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));
  9701. //
  9702. // if (first_err < 0 && error > 0.1) {
  9703. // first_err = i;
  9704. // }
  9705. //
  9706. // for (size_t j = 0; j < 32; j++) {
  9707. // uint64_t error = std::abs(qx_res[i].qs[j] - qx[i].qs[j]);
  9708. //
  9709. // if (first_err < 0 && error > 1) {
  9710. // first_err = i;
  9711. // }
  9712. // }
  9713. // }
  9714. //
  9715. // std::cerr << "TEST QUANTIZE " << ggml_type_name(quant) << " time=" << ms_quant << "ms " << (first_err == -1 ? "CORRECT" : "INCORRECT") << std::endl;
  9716. //
  9717. // if (first_err != -1) {
  9718. // std::cerr << "first_error = " << first_err << std::endl;
  9719. // std::cerr << "Actual result: " << std::endl << std::endl;
  9720. // 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) << " ";
  9721. // for (size_t j = 0; j < 32; j++) {
  9722. // std::cout << " qs" << j << "=" << (uint32_t)qx[first_err].qs[j] << " ";
  9723. // }
  9724. // std::cerr << std::endl << std::endl << "Expected result: " << std::endl << std::endl;
  9725. // 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) << " ";
  9726. // for (size_t j = 0; j < 32; j++) {
  9727. // std::cout << " qs" << j << "=" << (uint32_t)qx_res[first_err].qs[j] << " ";
  9728. // }
  9729. // std::cerr << std::endl;
  9730. // }
  9731. //
  9732. // ggml_vk_destroy_buffer(x_buf);
  9733. // ggml_vk_destroy_buffer(qx_buf);
  9734. //
  9735. // free(x);
  9736. // free(qx);
  9737. // free(qx_res);
  9738. // }
  9739. 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) {
  9740. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  9741. const size_t x_ne = m * k * batch;
  9742. const size_t y_ne = k * n * batch;
  9743. const size_t d_ne = m * n * batch;
  9744. vk_matmul_pipeline2 * pipelines;
  9745. if (mmq) {
  9746. pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1;
  9747. } else {
  9748. pipelines = ctx->device->pipeline_dequant_mul_mat_mat;
  9749. }
  9750. const bool fp16acc = ctx->device->fp16;
  9751. vk_pipeline p;
  9752. std::string shname;
  9753. if (shader_size == 0) {
  9754. p = fp16acc ? pipelines[quant].f16acc->a_s : pipelines[quant].f32acc->a_s;
  9755. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  9756. } else if (shader_size == 1) {
  9757. p = fp16acc ? pipelines[quant].f16acc->a_m : pipelines[quant].f32acc->a_m;
  9758. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  9759. } else if (shader_size == 2) {
  9760. p = fp16acc ? pipelines[quant].f16acc->a_l : pipelines[quant].f32acc->a_l;
  9761. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  9762. } else {
  9763. GGML_ASSERT(0);
  9764. }
  9765. const size_t kpad = mmq ? 0 : ggml_vk_align_size(k, p->align);
  9766. if (mmq || k != kpad) {
  9767. if (shader_size == 0) {
  9768. p = fp16acc ? pipelines[quant].f16acc->s : pipelines[quant].f32acc->s;
  9769. shname = std::string(ggml_type_name(quant)) + "_S";
  9770. } else if (shader_size == 1) {
  9771. p = fp16acc ? pipelines[quant].f16acc->m : pipelines[quant].f32acc->m;
  9772. shname = std::string(ggml_type_name(quant)) + "_M";
  9773. } else if (shader_size == 2) {
  9774. p = fp16acc ? pipelines[quant].f16acc->l : pipelines[quant].f32acc->l;
  9775. shname = std::string(ggml_type_name(quant)) + "_L";
  9776. } else {
  9777. GGML_ASSERT(0);
  9778. }
  9779. }
  9780. if (p == nullptr) {
  9781. std::cerr << "error: no pipeline for ggml_vk_test_dequant_matmul " << ggml_type_name(quant) << std::endl;
  9782. return;
  9783. }
  9784. const size_t x_sz = sizeof(float) * x_ne;
  9785. const size_t y_sz = sizeof(float) * y_ne;
  9786. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9787. const size_t qy_sz = mmq ? y_ne * ggml_type_size(GGML_TYPE_Q8_1)/ggml_blck_size(GGML_TYPE_Q8_1) : y_sz;
  9788. const size_t d_sz = sizeof(float) * d_ne;
  9789. float * x = (float *) malloc(x_sz);
  9790. float * y = (float *) malloc(y_sz);
  9791. void * qx = malloc(qx_sz);
  9792. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9793. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9794. vk_buffer qy_buf = ggml_vk_create_buffer_check(ctx->device, qy_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9795. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9796. float * d = (float *) malloc(d_sz);
  9797. float * d_chk = (float *) malloc(d_sz);
  9798. for (size_t i = 0; i < x_ne; i++) {
  9799. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9800. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9801. // x[i] = i % k;
  9802. }
  9803. ggml_vk_quantize_data(x, qx, x_ne, quant);
  9804. for (size_t i = 0; i < y_ne; i++) {
  9805. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9806. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9807. // y[i] = i % k;
  9808. }
  9809. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9810. if (split_k > 1) {
  9811. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9812. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9813. // Resize buffer
  9814. if (ctx->prealloc_split_k != nullptr) {
  9815. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9816. }
  9817. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9818. }
  9819. }
  9820. if (mmq) {
  9821. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_quantize_q8_1, num_it);
  9822. }
  9823. ggml_pipeline_allocate_descriptor_sets(ctx);
  9824. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9825. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  9826. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9827. ggml_vk_ctx_begin(ctx->device, subctx);
  9828. if (mmq) {
  9829. for (size_t i = 0; i < num_it; i++) {
  9830. ggml_vk_quantize_q8_1(ctx, subctx, { y_buf, 0, y_sz }, { qy_buf, 0, qy_sz }, y_ne);
  9831. ggml_vk_matmul(
  9832. 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 },
  9833. m, n, k,
  9834. k, k, m, k*m, k*n, m*n,
  9835. split_k, batch, batch, batch, 1, 1, n
  9836. );
  9837. }
  9838. } else {
  9839. for (size_t i = 0; i < num_it; i++) {
  9840. ggml_vk_matmul(
  9841. 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 },
  9842. m, n, k,
  9843. k, k, m, k*m, k*n, m*n,
  9844. split_k, batch, batch, batch, 1, 1, n
  9845. );
  9846. }
  9847. }
  9848. ggml_vk_ctx_end(subctx);
  9849. auto begin = std::chrono::high_resolution_clock::now();
  9850. ggml_vk_submit(subctx, ctx->fence);
  9851. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9852. ctx->device->device.resetFences({ ctx->fence });
  9853. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9854. auto end = std::chrono::high_resolution_clock::now();
  9855. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9856. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  9857. ggml_init_params iparams = {
  9858. /*.mem_size =*/ 1024*1024*1024,
  9859. /*.mem_buffer =*/ NULL,
  9860. /*.no_alloc =*/ true,
  9861. };
  9862. ggml_context * ggml_ctx = ggml_init(iparams);
  9863. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  9864. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  9865. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9866. src0_ggml->data = qx;
  9867. src1_ggml->data = y;
  9868. tensor_ggml->data = d_chk;
  9869. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9870. ggml_build_forward_expand(cgraph, tensor_ggml);
  9871. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9872. ggml_free(ggml_ctx);
  9873. double avg_err = 0.0;
  9874. int first_err_n = -1;
  9875. int first_err_m = -1;
  9876. int first_err_b = -1;
  9877. for (size_t i = 0; i < m*n*batch; i++) {
  9878. double err = std::fabs(d[i] - d_chk[i]);
  9879. avg_err += err;
  9880. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9881. first_err_b = i / (m * n);
  9882. first_err_n = (i % (m * n)) / m;
  9883. first_err_m = (i % (m * n)) % m;
  9884. }
  9885. }
  9886. avg_err /= m * n;
  9887. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9888. std::cerr << "TEST dequant matmul " << shname;
  9889. if (mmq) {
  9890. std::cerr << " mmq";
  9891. }
  9892. 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;
  9893. if (avg_err > 0.01 || std::isnan(avg_err)) {
  9894. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9895. std::cerr << "Actual result: " << std::endl << std::endl;
  9896. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9897. std::cerr << std::endl;
  9898. std::cerr << "Expected result: " << std::endl << std::endl;
  9899. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9900. std::cerr << "src0: " << std::endl << std::endl;
  9901. ggml_vk_print_matrix_area(x, GGML_TYPE_F32, k, m, first_err_m, first_err_n, first_err_b);
  9902. std::cerr << std::endl;
  9903. std::cerr << "src1: " << std::endl << std::endl;
  9904. ggml_vk_print_matrix_area(y, GGML_TYPE_F32, k, n, first_err_m, first_err_n, first_err_b);
  9905. if (split_k > 1) {
  9906. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9907. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9908. std::cerr << "d_buf0: " << std::endl << std::endl;
  9909. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9910. std::cerr << "d_buf1: " << std::endl << std::endl;
  9911. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9912. std::cerr << "d_buf2: " << std::endl << std::endl;
  9913. 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);
  9914. std::cerr << "d_buf3: " << std::endl << std::endl;
  9915. 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);
  9916. free(split_k_buf);
  9917. }
  9918. }
  9919. ggml_vk_destroy_buffer(qx_buf);
  9920. ggml_vk_destroy_buffer(y_buf);
  9921. ggml_vk_destroy_buffer(qy_buf);
  9922. ggml_vk_destroy_buffer(d_buf);
  9923. free(x);
  9924. free(qx);
  9925. free(y);
  9926. free(d);
  9927. free(d_chk);
  9928. }
  9929. #endif
  9930. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx) {
  9931. #if defined(GGML_VULKAN_RUN_TESTS)
  9932. const std::vector<size_t> vals {
  9933. 512, 512, 128,
  9934. 128, 512, 512,
  9935. 4096, 512, 4096,
  9936. 11008, 512, 4096,
  9937. 4096, 512, 11008,
  9938. 32000, 512, 4096,
  9939. 8, 8, 8,
  9940. 100, 46, 576,
  9941. 623, 111, 128,
  9942. 100, 46, 558,
  9943. 512, 1, 256,
  9944. 128, 110, 622,
  9945. 511, 511, 127,
  9946. 511, 511, 7,
  9947. 511, 511, 17,
  9948. 49, 49, 128,
  9949. 128, 49, 49,
  9950. 4096, 49, 4096,
  9951. };
  9952. const size_t num_it = 100;
  9953. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9954. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9955. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9956. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true);
  9957. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true);
  9958. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true);
  9959. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0);
  9960. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0);
  9961. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0);
  9962. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true);
  9963. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true);
  9964. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true);
  9965. abort();
  9966. for (size_t i = 0; i < vals.size(); i += 3) {
  9967. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  9968. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  9969. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  9970. std::cerr << '\n';
  9971. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  9972. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  9973. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  9974. std::cerr << '\n';
  9975. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  9976. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  9977. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  9978. std::cerr << '\n' << std::endl;
  9979. if (vals[i + 2] % 32 == 0) {
  9980. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9981. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9982. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9983. std::cerr << '\n';
  9984. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  9985. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  9986. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  9987. std::cerr << '\n';
  9988. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  9989. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  9990. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  9991. std::cerr << '\n' << std::endl;
  9992. }
  9993. if (vals[i + 2] % 256 == 0) {
  9994. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  9995. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  9996. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  9997. std::cerr << '\n';
  9998. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  9999. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  10000. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  10001. std::cerr << '\n';
  10002. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  10003. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  10004. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  10005. std::cerr << '\n' << std::endl;
  10006. }
  10007. }
  10008. GGML_ABORT("fatal error");
  10009. #endif
  10010. if (subctx) {
  10011. // Submit and wait for any pending work before reallocating the buffers
  10012. ggml_vk_ctx_end(subctx);
  10013. ggml_vk_submit(subctx, {});
  10014. ctx->submit_pending = true;
  10015. ggml_vk_synchronize(ctx);
  10016. ggml_vk_ctx_begin(ctx->device, subctx);
  10017. }
  10018. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  10019. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  10020. // Resize buffer
  10021. if (ctx->prealloc_x != nullptr) {
  10022. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10023. }
  10024. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  10025. }
  10026. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  10027. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  10028. // Resize buffer
  10029. if (ctx->prealloc_y != nullptr) {
  10030. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10031. }
  10032. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  10033. }
  10034. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  10035. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  10036. // Resize buffer
  10037. if (ctx->prealloc_split_k != nullptr) {
  10038. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10039. }
  10040. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  10041. }
  10042. 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)) {
  10043. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")");
  10044. // Resize buffer
  10045. if (ctx->prealloc_add_rms_partials != nullptr) {
  10046. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  10047. }
  10048. ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials);
  10049. }
  10050. }
  10051. static void ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_cgraph * cgraph, ggml_tensor* tensor, int tensor_idx, bool almost_ready);
  10052. // Returns true if node has enqueued work into the queue, false otherwise
  10053. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  10054. 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){
  10055. ggml_tensor * node = cgraph->nodes[node_idx];
  10056. if (ggml_is_empty(node) || ggml_op_is_empty(node->op) || !node->buffer) {
  10057. return false;
  10058. }
  10059. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  10060. ctx->semaphore_idx = 0;
  10061. ggml_tensor * src0 = node->src[0];
  10062. ggml_tensor * src1 = node->src[1];
  10063. ggml_tensor * src2 = node->src[2];
  10064. ggml_tensor * src3 = node->src[3];
  10065. if (node->op == GGML_OP_ADD) {
  10066. int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops;
  10067. if (next_node_idx < cgraph->n_nodes &&
  10068. cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM &&
  10069. cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] &&
  10070. ggml_nrows(cgraph->nodes[next_node_idx]) == 1 &&
  10071. ctx->device->add_rms_fusion) {
  10072. uint32_t size = ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]);
  10073. ctx->do_add_rms_partials_offset_calculation = true;
  10074. if (ctx->prealloc_size_add_rms_partials_offset + size <= ctx->prealloc_size_add_rms_partials) {
  10075. ctx->do_add_rms_partials = true;
  10076. }
  10077. }
  10078. }
  10079. vk_context compute_ctx;
  10080. if (ctx->compute_ctx.expired()) {
  10081. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10082. ctx->compute_ctx = compute_ctx;
  10083. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10084. } else {
  10085. compute_ctx = ctx->compute_ctx.lock();
  10086. }
  10087. {
  10088. // This logic detects dependencies between modes in the graph and calls ggml_vk_sync_buffers
  10089. // to synchronize them. This handles most "normal" synchronization when computing the graph, and when
  10090. // there is no auxiliary memory use, it shouldn't be necessary to call ggml_vk_sync_buffers
  10091. // outside of this logic. When a node uses one of the prealloc buffers for something like
  10092. // dequantization or split_k, additional synchronization is needed between those passes.
  10093. bool need_sync = false;
  10094. // Check whether "node" requires synchronization. The node requires synchronization if it
  10095. // overlaps in memory with another unsynchronized node and at least one of them is a write.
  10096. // Destination nodes are checked against both the written/read lists. Source nodes are only
  10097. // checked against the written list. Two nodes overlap in memory if they come from the same
  10098. // buffer and the tensor or view ranges overlap.
  10099. auto const &overlaps_unsynced = [&](const ggml_tensor *node, const std::vector<const ggml_tensor *> &unsynced_nodes) -> bool {
  10100. if (unsynced_nodes.size() == 0) {
  10101. return false;
  10102. }
  10103. auto n_base = vk_tensor_offset(node) + node->view_offs;
  10104. auto n_size = ggml_nbytes(node);
  10105. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context;
  10106. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  10107. for (auto &other : unsynced_nodes) {
  10108. ggml_backend_vk_buffer_context * o_buf_ctx = (ggml_backend_vk_buffer_context *)other->buffer->context;
  10109. vk_buffer o_buf = o_buf_ctx->dev_buffer;
  10110. if (a_buf == o_buf) {
  10111. auto o_base = vk_tensor_offset(other) + other->view_offs;
  10112. auto o_size = ggml_nbytes(other);
  10113. if ((o_base <= n_base && n_base < o_base + o_size) ||
  10114. (n_base <= o_base && o_base < n_base + n_size)) {
  10115. return true;
  10116. }
  10117. }
  10118. }
  10119. return false;
  10120. };
  10121. // For all fused ops, check if the destination node or any of the source
  10122. // nodes require synchronization.
  10123. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) {
  10124. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  10125. // If the node actually writes to memory, then check if it needs to sync
  10126. if (ctx->fused_ops_write_mask & (1 << i)) {
  10127. if (overlaps_unsynced(cur_node, ctx->unsynced_nodes_read) || overlaps_unsynced(cur_node, ctx->unsynced_nodes_written)) {
  10128. need_sync = true;
  10129. break;
  10130. }
  10131. }
  10132. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  10133. if (!cur_node->src[j]) {
  10134. continue;
  10135. }
  10136. if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) {
  10137. need_sync = true;
  10138. break;
  10139. }
  10140. }
  10141. }
  10142. #define ENABLE_SYNC_LOGGING 0
  10143. if (need_sync) {
  10144. #if ENABLE_SYNC_LOGGING
  10145. std::cerr << "sync" << std::endl;
  10146. #endif
  10147. ctx->unsynced_nodes_written.clear();
  10148. ctx->unsynced_nodes_read.clear();
  10149. ggml_vk_sync_buffers(ctx, compute_ctx);
  10150. }
  10151. // Add all fused nodes to the unsynchronized lists.
  10152. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  10153. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  10154. // Multiple outputs could be written, e.g. in topk_moe. Add them all to the list.
  10155. if (ctx->fused_ops_write_mask & (1 << i)) {
  10156. ctx->unsynced_nodes_written.push_back(cur_node);
  10157. }
  10158. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  10159. if (!cur_node->src[j]) {
  10160. continue;
  10161. }
  10162. ctx->unsynced_nodes_read.push_back(cur_node->src[j]);
  10163. }
  10164. }
  10165. }
  10166. #if ENABLE_SYNC_LOGGING
  10167. for (int i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  10168. auto *n = cgraph->nodes[node_idx + i];
  10169. std::cerr << node_idx + i << " " << ggml_op_name(n->op) << " " << n->name;
  10170. if (n->op == GGML_OP_GLU) {
  10171. std::cerr << " " << ggml_glu_op_name(ggml_get_glu_op(n)) << " " << (n->src[1] ? "split" : "single") << " ";
  10172. }
  10173. if (n->op == GGML_OP_ROPE) {
  10174. const int mode = ((const int32_t *) n->op_params)[2];
  10175. std::cerr << " rope mode: " << mode;
  10176. }
  10177. std::cerr << std::endl;
  10178. }
  10179. #endif
  10180. switch (node->op) {
  10181. case GGML_OP_REPEAT:
  10182. ggml_vk_repeat(ctx, compute_ctx, src0, node);
  10183. break;
  10184. case GGML_OP_REPEAT_BACK:
  10185. ggml_vk_repeat_back(ctx, compute_ctx, src0, node);
  10186. break;
  10187. case GGML_OP_ACC:
  10188. ggml_vk_acc(ctx, compute_ctx, src0, src1, node);
  10189. break;
  10190. case GGML_OP_GET_ROWS:
  10191. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node);
  10192. break;
  10193. case GGML_OP_ADD:
  10194. if (ctx->num_additional_fused_ops) {
  10195. ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx);
  10196. } else {
  10197. ggml_vk_add(ctx, compute_ctx, src0, src1, node);
  10198. }
  10199. break;
  10200. case GGML_OP_SUB:
  10201. ggml_vk_sub(ctx, compute_ctx, src0, src1, node);
  10202. break;
  10203. case GGML_OP_MUL:
  10204. ggml_vk_mul(ctx, compute_ctx, src0, src1, node);
  10205. break;
  10206. case GGML_OP_DIV:
  10207. ggml_vk_div(ctx, compute_ctx, src0, src1, node);
  10208. break;
  10209. case GGML_OP_ADD_ID:
  10210. ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node);
  10211. break;
  10212. case GGML_OP_CONCAT:
  10213. ggml_vk_concat(ctx, compute_ctx, src0, src1, node);
  10214. break;
  10215. case GGML_OP_UPSCALE:
  10216. ggml_vk_upscale(ctx, compute_ctx, src0, node);
  10217. break;
  10218. case GGML_OP_ADD1:
  10219. ggml_vk_add1(ctx, compute_ctx, src0, src1, node);
  10220. break;
  10221. case GGML_OP_ARANGE:
  10222. ggml_vk_arange(ctx, compute_ctx, node);
  10223. break;
  10224. case GGML_OP_FILL:
  10225. ggml_vk_fill(ctx, compute_ctx, node);
  10226. break;
  10227. case GGML_OP_SCALE:
  10228. ggml_vk_scale(ctx, compute_ctx, src0, node);
  10229. break;
  10230. case GGML_OP_SQR:
  10231. ggml_vk_sqr(ctx, compute_ctx, src0, node);
  10232. break;
  10233. case GGML_OP_SQRT:
  10234. ggml_vk_sqrt(ctx, compute_ctx, src0, node);
  10235. break;
  10236. case GGML_OP_SIN:
  10237. ggml_vk_sin(ctx, compute_ctx, src0, node);
  10238. break;
  10239. case GGML_OP_COS:
  10240. ggml_vk_cos(ctx, compute_ctx, src0, node);
  10241. break;
  10242. case GGML_OP_LOG:
  10243. ggml_vk_log(ctx, compute_ctx, src0, node);
  10244. break;
  10245. case GGML_OP_TRI:
  10246. ggml_vk_tri(ctx, compute_ctx, src0, node);
  10247. break;
  10248. case GGML_OP_DIAG:
  10249. ggml_vk_diag(ctx, compute_ctx, src0, node);
  10250. break;
  10251. case GGML_OP_CLAMP:
  10252. ggml_vk_clamp(ctx, compute_ctx, src0, node);
  10253. break;
  10254. case GGML_OP_PAD:
  10255. ggml_vk_pad(ctx, compute_ctx, src0, node);
  10256. break;
  10257. case GGML_OP_ROLL:
  10258. ggml_vk_roll(ctx, compute_ctx, src0, node);
  10259. break;
  10260. case GGML_OP_CPY:
  10261. case GGML_OP_CONT:
  10262. case GGML_OP_DUP:
  10263. ggml_vk_cpy(ctx, compute_ctx, src0, node);
  10264. break;
  10265. case GGML_OP_SET_ROWS:
  10266. ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node);
  10267. break;
  10268. case GGML_OP_SILU_BACK:
  10269. ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node);
  10270. break;
  10271. case GGML_OP_NORM:
  10272. ggml_vk_norm(ctx, compute_ctx, src0, node);
  10273. break;
  10274. case GGML_OP_GROUP_NORM:
  10275. ggml_vk_group_norm(ctx, compute_ctx, src0, node);
  10276. break;
  10277. case GGML_OP_RMS_NORM:
  10278. ggml_vk_rms_norm(ctx, compute_ctx, cgraph, node_idx, (float *)node->op_params);
  10279. break;
  10280. case GGML_OP_RMS_NORM_BACK:
  10281. ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node);
  10282. break;
  10283. case GGML_OP_L2_NORM:
  10284. ggml_vk_l2_norm(ctx, compute_ctx, src0, node);
  10285. break;
  10286. case GGML_OP_UNARY:
  10287. switch (ggml_get_unary_op(node)) {
  10288. case GGML_UNARY_OP_EXP:
  10289. case GGML_UNARY_OP_SILU:
  10290. case GGML_UNARY_OP_GELU:
  10291. case GGML_UNARY_OP_GELU_ERF:
  10292. case GGML_UNARY_OP_GELU_QUICK:
  10293. case GGML_UNARY_OP_RELU:
  10294. case GGML_UNARY_OP_NEG:
  10295. case GGML_UNARY_OP_TANH:
  10296. case GGML_UNARY_OP_SIGMOID:
  10297. case GGML_UNARY_OP_HARDSIGMOID:
  10298. case GGML_UNARY_OP_HARDSWISH:
  10299. case GGML_UNARY_OP_ABS:
  10300. case GGML_UNARY_OP_SOFTPLUS:
  10301. case GGML_UNARY_OP_STEP:
  10302. case GGML_UNARY_OP_ROUND:
  10303. case GGML_UNARY_OP_CEIL:
  10304. case GGML_UNARY_OP_FLOOR:
  10305. case GGML_UNARY_OP_TRUNC:
  10306. ggml_vk_unary(ctx, compute_ctx, src0, node);
  10307. break;
  10308. default:
  10309. return false;
  10310. }
  10311. break;
  10312. case GGML_OP_GLU:
  10313. switch (ggml_get_glu_op(node)) {
  10314. case GGML_GLU_OP_GEGLU:
  10315. case GGML_GLU_OP_REGLU:
  10316. case GGML_GLU_OP_SWIGLU:
  10317. case GGML_GLU_OP_SWIGLU_OAI:
  10318. case GGML_GLU_OP_GEGLU_ERF:
  10319. case GGML_GLU_OP_GEGLU_QUICK:
  10320. ggml_vk_glu(ctx, compute_ctx, src0, src1, node);
  10321. break;
  10322. default:
  10323. return false;
  10324. }
  10325. break;
  10326. case GGML_OP_DIAG_MASK_INF:
  10327. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node);
  10328. break;
  10329. case GGML_OP_SOFT_MAX:
  10330. if (ctx->num_additional_fused_ops) {
  10331. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10332. } else {
  10333. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node);
  10334. }
  10335. break;
  10336. case GGML_OP_SOFT_MAX_BACK:
  10337. ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node);
  10338. break;
  10339. case GGML_OP_ROPE:
  10340. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, false);
  10341. break;
  10342. case GGML_OP_ROPE_BACK:
  10343. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, true);
  10344. break;
  10345. case GGML_OP_ARGSORT:
  10346. if (ctx->num_additional_fused_ops) {
  10347. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10348. } else {
  10349. ggml_vk_argsort(ctx, compute_ctx, src0, node);
  10350. }
  10351. break;
  10352. case GGML_OP_TOP_K:
  10353. ggml_vk_topk(ctx, compute_ctx, src0, node);
  10354. break;
  10355. case GGML_OP_SUM:
  10356. ggml_vk_sum(ctx, compute_ctx, src0, node);
  10357. break;
  10358. case GGML_OP_SUM_ROWS:
  10359. ggml_vk_sum_rows(ctx, compute_ctx, src0, node);
  10360. break;
  10361. case GGML_OP_CUMSUM:
  10362. ggml_vk_cumsum(ctx, compute_ctx, src0, node);
  10363. break;
  10364. case GGML_OP_MEAN:
  10365. ggml_vk_mean(ctx, compute_ctx, src0, node);
  10366. break;
  10367. case GGML_OP_ARGMAX:
  10368. ggml_vk_argmax(ctx, compute_ctx, src0, node);
  10369. break;
  10370. case GGML_OP_COUNT_EQUAL:
  10371. ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node);
  10372. break;
  10373. case GGML_OP_SOLVE_TRI:
  10374. ggml_vk_solve_tri(ctx, compute_ctx, src0, src1, node);
  10375. break;
  10376. case GGML_OP_IM2COL:
  10377. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node);
  10378. break;
  10379. case GGML_OP_IM2COL_3D:
  10380. ggml_vk_im2col_3d(ctx, compute_ctx, src0, src1, node);
  10381. break;
  10382. case GGML_OP_TIMESTEP_EMBEDDING:
  10383. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node);
  10384. break;
  10385. case GGML_OP_CONV_TRANSPOSE_1D:
  10386. ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node);
  10387. break;
  10388. case GGML_OP_POOL_2D:
  10389. ggml_vk_pool_2d(ctx, compute_ctx, src0, node);
  10390. break;
  10391. case GGML_OP_CONV_2D:
  10392. case GGML_OP_CONV_TRANSPOSE_2D:
  10393. ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node);
  10394. break;
  10395. case GGML_OP_CONV_2D_DW:
  10396. ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node);
  10397. break;
  10398. case GGML_OP_LEAKY_RELU:
  10399. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node);
  10400. break;
  10401. case GGML_OP_MUL_MAT:
  10402. ggml_vk_mul_mat(ctx, compute_ctx, cgraph, node_idx);
  10403. break;
  10404. case GGML_OP_MUL_MAT_ID:
  10405. ggml_vk_mul_mat_id(ctx, compute_ctx, cgraph, node_idx);
  10406. break;
  10407. case GGML_OP_FLASH_ATTN_EXT:
  10408. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node);
  10409. break;
  10410. case GGML_OP_RWKV_WKV6:
  10411. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node);
  10412. break;
  10413. case GGML_OP_RWKV_WKV7:
  10414. ggml_vk_rwkv_wkv7(ctx, compute_ctx, node);
  10415. break;
  10416. case GGML_OP_SSM_SCAN:
  10417. ggml_vk_ssm_scan(ctx, compute_ctx, node);
  10418. break;
  10419. case GGML_OP_SSM_CONV:
  10420. ggml_vk_ssm_conv(ctx, compute_ctx, node);
  10421. break;
  10422. case GGML_OP_OPT_STEP_ADAMW:
  10423. ggml_vk_opt_step_adamw(ctx, compute_ctx, node);
  10424. break;
  10425. case GGML_OP_OPT_STEP_SGD:
  10426. ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node);
  10427. break;
  10428. default:
  10429. return false;
  10430. }
  10431. ctx->tensor_ctxs[node_idx] = compute_ctx;
  10432. #if defined(GGML_VULKAN_CHECK_RESULTS)
  10433. // Force context reset on each node so that each tensor ends up in its own context
  10434. // and can be run and compared to its CPU equivalent separately
  10435. last_node = true;
  10436. #endif
  10437. if (submit || last_node) {
  10438. ggml_vk_ctx_end(compute_ctx);
  10439. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  10440. if (last_node) {
  10441. compute_ctx->exit_tensor_idx = node_idx_begin;
  10442. }
  10443. else {
  10444. compute_ctx->exit_tensor_idx = -1;
  10445. }
  10446. ctx->compute_ctx.reset();
  10447. ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, almost_ready);
  10448. }
  10449. return true;
  10450. }
  10451. static void ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, ggml_tensor * tensor, int tensor_idx, bool almost_ready = false) {
  10452. GGML_UNUSED(cgraph);
  10453. GGML_UNUSED(tensor);
  10454. 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 << ")");
  10455. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  10456. // Only run if ctx hasn't been submitted yet
  10457. if (!subctx->seqs.empty()) {
  10458. #ifdef GGML_VULKAN_CHECK_RESULTS
  10459. ggml_vk_check_results_0(ctx, cgraph, tensor_idx);
  10460. #endif
  10461. // Do staging buffer copies
  10462. for (auto& cpy : subctx->in_memcpys) {
  10463. memcpy(cpy.dst, cpy.src, cpy.n);
  10464. }
  10465. for (auto& mset : subctx->memsets) {
  10466. memset(mset.dst, mset.val, mset.n);
  10467. }
  10468. if (almost_ready && !ctx->almost_ready_fence_pending) {
  10469. ggml_vk_submit(subctx, ctx->almost_ready_fence);
  10470. ctx->almost_ready_fence_pending = true;
  10471. } else {
  10472. ggml_vk_submit(subctx, {});
  10473. }
  10474. ctx->submit_pending = true;
  10475. #ifdef GGML_VULKAN_CHECK_RESULTS
  10476. ggml_vk_synchronize(ctx);
  10477. ggml_vk_check_results_1(ctx, cgraph, tensor_idx);
  10478. #endif
  10479. }
  10480. if (tensor_idx == subctx->exit_tensor_idx) {
  10481. // Do staging buffer copies
  10482. for (auto& cpy : subctx->out_memcpys) {
  10483. memcpy(cpy.dst, cpy.src, cpy.n);
  10484. }
  10485. subctx->in_memcpys.clear();
  10486. subctx->out_memcpys.clear();
  10487. subctx->memsets.clear();
  10488. }
  10489. }
  10490. // Clean up after graph processing is done
  10491. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  10492. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  10493. ctx->prealloc_y_last_pipeline_used = {};
  10494. ctx->unsynced_nodes_written.clear();
  10495. ctx->unsynced_nodes_read.clear();
  10496. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  10497. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  10498. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  10499. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  10500. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  10501. }
  10502. ctx->gc.semaphores.clear();
  10503. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  10504. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  10505. }
  10506. ctx->gc.tl_semaphores.clear();
  10507. ctx->semaphore_idx = 0;
  10508. ctx->event_idx = 0;
  10509. for (auto& event : ctx->gc.events) {
  10510. ctx->device->device.resetEvent(event);
  10511. }
  10512. ctx->tensor_ctxs.clear();
  10513. ctx->gc.contexts.clear();
  10514. ctx->pipeline_descriptor_set_requirements = 0;
  10515. ctx->descriptor_set_idx = 0;
  10516. }
  10517. // Clean up on backend free
  10518. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  10519. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  10520. // discard any unsubmitted command buffers
  10521. ctx->transfer_ctx.reset();
  10522. // wait for any pending command buffers to finish
  10523. ggml_vk_synchronize(ctx);
  10524. ggml_vk_graph_cleanup(ctx);
  10525. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10526. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10527. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10528. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  10529. ggml_vk_destroy_buffer(ctx->sync_staging);
  10530. ctx->prealloc_y_last_pipeline_used = nullptr;
  10531. ctx->prealloc_size_x = 0;
  10532. ctx->prealloc_size_y = 0;
  10533. ctx->prealloc_size_split_k = 0;
  10534. for (auto& event : ctx->gc.events) {
  10535. ctx->device->device.destroyEvent(event);
  10536. }
  10537. ctx->gc.events.clear();
  10538. ctx->device->device.destroyFence(ctx->fence);
  10539. ctx->device->device.destroyFence(ctx->almost_ready_fence);
  10540. for (auto& pool : ctx->descriptor_pools) {
  10541. ctx->device->device.destroyDescriptorPool(pool);
  10542. }
  10543. ctx->descriptor_pools.clear();
  10544. ctx->descriptor_sets.clear();
  10545. ctx->compute_cmd_pool.destroy(ctx->device->device);
  10546. ctx->transfer_cmd_pool.destroy(ctx->device->device);
  10547. if (vk_perf_logger_enabled) {
  10548. ctx->perf_logger->print_timings(true);
  10549. }
  10550. }
  10551. static int ggml_vk_get_device_count() {
  10552. ggml_vk_instance_init();
  10553. return vk_instance.device_indices.size();
  10554. }
  10555. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  10556. ggml_vk_instance_init();
  10557. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  10558. vk::PhysicalDeviceProperties props;
  10559. devices[device].getProperties(&props);
  10560. snprintf(description, description_size, "%s", props.deviceName.data());
  10561. }
  10562. // backend interface
  10563. #define UNUSED GGML_UNUSED
  10564. // device backend
  10565. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  10566. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  10567. }
  10568. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10569. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  10570. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10571. ggml_vk_destroy_buffer(ctx->dev_buffer);
  10572. delete ctx;
  10573. }
  10574. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  10575. return vk_ptr_base;
  10576. UNUSED(buffer);
  10577. }
  10578. static enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  10579. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  10580. if (tensor->view_src != nullptr) {
  10581. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  10582. }
  10583. return GGML_STATUS_SUCCESS;
  10584. }
  10585. 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) {
  10586. VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")");
  10587. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10588. vk_buffer buf = buf_ctx->dev_buffer;
  10589. uint32_t val32 = (uint32_t)value * 0x01010101;
  10590. ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size);
  10591. }
  10592. 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) {
  10593. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10594. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10595. vk_buffer buf = buf_ctx->dev_buffer;
  10596. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10597. }
  10598. 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) {
  10599. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10600. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10601. vk_buffer buf = buf_ctx->dev_buffer;
  10602. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10603. }
  10604. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  10605. if (ggml_backend_buffer_is_vk(src->buffer)) {
  10606. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10607. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10608. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10609. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10610. 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));
  10611. return true;
  10612. }
  10613. return false;
  10614. UNUSED(buffer);
  10615. }
  10616. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  10617. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10618. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  10619. }
  10620. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  10621. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  10622. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  10623. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  10624. /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor,
  10625. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  10626. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  10627. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  10628. /* .clear = */ ggml_backend_vk_buffer_clear,
  10629. /* .reset = */ NULL,
  10630. };
  10631. // vk buffer type
  10632. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10633. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  10634. return ctx->name.c_str();
  10635. }
  10636. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10637. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  10638. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10639. vk_buffer dev_buffer = nullptr;
  10640. try {
  10641. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  10642. } catch (const vk::SystemError& e) {
  10643. return nullptr;
  10644. }
  10645. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  10646. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  10647. }
  10648. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10649. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10650. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  10651. }
  10652. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10653. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10654. return ctx->device->suballocation_block_size;
  10655. }
  10656. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  10657. return ggml_nbytes(tensor);
  10658. UNUSED(buft);
  10659. }
  10660. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  10661. ggml_vk_instance_init();
  10662. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  10663. vk_device dev = ggml_vk_get_device(dev_num);
  10664. return &dev->buffer_type;
  10665. }
  10666. // host buffer type
  10667. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10668. return GGML_VK_NAME "_Host";
  10669. UNUSED(buft);
  10670. }
  10671. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  10672. return GGML_VK_NAME "_Host";
  10673. UNUSED(buffer);
  10674. }
  10675. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10676. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  10677. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  10678. }
  10679. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10680. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  10681. size += 32; // Behave like the CPU buffer type
  10682. void * ptr = nullptr;
  10683. try {
  10684. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  10685. } catch (vk::SystemError& e) {
  10686. GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory (%s)\n", e.what());
  10687. // fallback to cpu buffer
  10688. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  10689. }
  10690. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  10691. buffer->buft = buft;
  10692. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  10693. return buffer;
  10694. UNUSED(buft);
  10695. }
  10696. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10697. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  10698. UNUSED(buft);
  10699. }
  10700. static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10701. return vk_instance.devices[0]->suballocation_block_size;
  10702. UNUSED(buft);
  10703. }
  10704. // Should be changed to return device-specific host buffer type
  10705. // but that probably requires changes in llama.cpp
  10706. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  10707. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  10708. /* .iface = */ {
  10709. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  10710. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  10711. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  10712. /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size,
  10713. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  10714. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  10715. },
  10716. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  10717. /* .context = */ nullptr,
  10718. };
  10719. // Make sure device 0 is initialized
  10720. ggml_vk_instance_init();
  10721. ggml_vk_get_device(0);
  10722. return &ggml_backend_vk_buffer_type_host;
  10723. }
  10724. // backend
  10725. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  10726. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10727. return ctx->name.c_str();
  10728. }
  10729. static void ggml_backend_vk_free(ggml_backend_t backend) {
  10730. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10731. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  10732. ggml_vk_cleanup(ctx);
  10733. delete ctx;
  10734. delete backend;
  10735. }
  10736. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  10737. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10738. return &ctx->device->buffer_type;
  10739. }
  10740. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  10741. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  10742. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10743. 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");
  10744. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10745. vk_context transfer_ctx;
  10746. if (ctx->transfer_ctx.expired()) {
  10747. // Initialize new transfer context
  10748. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10749. ctx->transfer_ctx = transfer_ctx;
  10750. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10751. } else {
  10752. transfer_ctx = ctx->transfer_ctx.lock();
  10753. }
  10754. vk_buffer buf = buf_ctx->dev_buffer;
  10755. ggml_vk_buffer_write_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10756. }
  10757. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  10758. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  10759. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10760. 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");
  10761. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10762. vk_context transfer_ctx;
  10763. if (ctx->transfer_ctx.expired()) {
  10764. // Initialize new transfer context
  10765. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10766. ctx->transfer_ctx = transfer_ctx;
  10767. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10768. } else {
  10769. transfer_ctx = ctx->transfer_ctx.lock();
  10770. }
  10771. vk_buffer buf = buf_ctx->dev_buffer;
  10772. auto src_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset;
  10773. bool ret = ggml_vk_buffer_read_async(transfer_ctx, buf, src_offset, data, size);
  10774. // If that failed, copy synchronously through a staging buffer
  10775. if (!ret) {
  10776. ggml_vk_ensure_sync_staging_buffer(ctx, size);
  10777. ggml_vk_sync_buffers(nullptr, transfer_ctx);
  10778. vk::BufferCopy buffer_cpy;
  10779. buffer_cpy.srcOffset = src_offset;
  10780. buffer_cpy.dstOffset = 0;
  10781. buffer_cpy.size = size;
  10782. transfer_ctx->s->buffer.copyBuffer(buf->buffer, ctx->sync_staging->buffer, { buffer_cpy });
  10783. deferred_memcpy(data, ctx->sync_staging->ptr, size, &transfer_ctx->out_memcpys);
  10784. ggml_vk_synchronize(ctx);
  10785. }
  10786. }
  10787. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  10788. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  10789. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10790. 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)) {
  10791. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10792. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10793. vk_context transfer_ctx;
  10794. if (ctx->transfer_ctx.expired()) {
  10795. // Initialize new transfer context
  10796. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10797. ctx->transfer_ctx = transfer_ctx;
  10798. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10799. } else {
  10800. transfer_ctx = ctx->transfer_ctx.lock();
  10801. }
  10802. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10803. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10804. 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));
  10805. return true;
  10806. }
  10807. return false;
  10808. }
  10809. static void ggml_vk_synchronize(ggml_backend_vk_context * ctx) {
  10810. VK_LOG_DEBUG("ggml_vk_synchronize()");
  10811. bool do_transfer = !ctx->transfer_ctx.expired();
  10812. vk_context transfer_ctx;
  10813. if (do_transfer) {
  10814. transfer_ctx = ctx->transfer_ctx.lock();
  10815. ggml_vk_ctx_end(transfer_ctx);
  10816. for (auto& cpy : transfer_ctx->in_memcpys) {
  10817. memcpy(cpy.dst, cpy.src, cpy.n);
  10818. }
  10819. ggml_vk_submit(transfer_ctx, {});
  10820. ctx->submit_pending = true;
  10821. }
  10822. if (ctx->submit_pending) {
  10823. {
  10824. std::lock_guard<std::mutex> guard(queue_mutex);
  10825. ctx->device->compute_queue.queue.submit({}, ctx->fence);
  10826. }
  10827. ggml_vk_wait_for_fence(ctx);
  10828. ctx->submit_pending = false;
  10829. }
  10830. if (do_transfer) {
  10831. for (auto& cpy : transfer_ctx->out_memcpys) {
  10832. memcpy(cpy.dst, cpy.src, cpy.n);
  10833. }
  10834. ctx->transfer_ctx.reset();
  10835. }
  10836. }
  10837. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  10838. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  10839. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10840. ggml_vk_synchronize(ctx);
  10841. ggml_vk_graph_cleanup(ctx);
  10842. }
  10843. static bool ggml_vk_is_empty(ggml_tensor * node) {
  10844. 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;
  10845. }
  10846. 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) {
  10847. if (!ggml_can_fuse(cgraph, node_idx, ops)) {
  10848. return false;
  10849. }
  10850. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
  10851. // additional constraints specific to this fusion
  10852. const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
  10853. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10854. GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
  10855. GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
  10856. // rms_norm only supports f32
  10857. if (mul->src[0]->type != GGML_TYPE_F32 ||
  10858. mul->src[1]->type != GGML_TYPE_F32 ||
  10859. mul->type != GGML_TYPE_F32) {
  10860. return false;
  10861. }
  10862. // if rms_norm is the B operand, then we don't handle broadcast
  10863. if (rms_norm == mul->src[1] &&
  10864. !ggml_are_same_shape(mul->src[0], rms_norm)) {
  10865. return false;
  10866. }
  10867. // rms_norm shader assumes contiguous rows
  10868. if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
  10869. return false;
  10870. }
  10871. }
  10872. auto const &mm_add_ok = [&](const ggml_tensor *mul, const ggml_tensor *add) {
  10873. const ggml_tensor *bias = add->src[0] == mul ? add->src[1] : add->src[0];
  10874. // mat-vec only
  10875. if (ggml_nrows(mul) != 1) {
  10876. return false;
  10877. }
  10878. // shaders assume the types match
  10879. if (mul->type != bias->type) {
  10880. return false;
  10881. }
  10882. // shaders reuse the D shape for bias
  10883. if (!ggml_are_same_shape(mul, bias) ||
  10884. !ggml_are_same_stride(mul, bias)) {
  10885. return false;
  10886. }
  10887. // unaligned bias isn't handled
  10888. if (get_misalign_bytes(ctx, bias) != 0) {
  10889. return false;
  10890. }
  10891. return true;
  10892. };
  10893. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT && ops.begin()[1] == GGML_OP_ADD) {
  10894. // additional constraints specific to this fusion
  10895. const ggml_tensor *mul = cgraph->nodes[node_idx];
  10896. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  10897. if (!mm_add_ok(mul, add)) {
  10898. return false;
  10899. }
  10900. if (ops.size() == 3) {
  10901. if (ops.begin()[2] != GGML_OP_ADD) {
  10902. return false;
  10903. }
  10904. if (!mm_add_ok(add, cgraph->nodes[node_idx + 2])) {
  10905. return false;
  10906. }
  10907. }
  10908. }
  10909. auto const &mmid_mul_ok = [&](const ggml_tensor *mmid, const ggml_tensor *mul) {
  10910. const ggml_tensor *scale = mul->src[1];
  10911. if (mmid != mul->src[0]) {
  10912. return false;
  10913. }
  10914. // mat-vec only
  10915. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  10916. return false;
  10917. }
  10918. // shaders assume the types match
  10919. if (mmid->type != scale->type) {
  10920. return false;
  10921. }
  10922. // shaders assume the bias is contiguous
  10923. if (!ggml_is_contiguous(scale)) {
  10924. return false;
  10925. }
  10926. // unaligned bias isn't handled
  10927. if (get_misalign_bytes(ctx, scale) != 0) {
  10928. return false;
  10929. }
  10930. // shader only indexes by expert index
  10931. if (scale->ne[0] != 1 ||
  10932. scale->ne[1] != mul->ne[1] ||
  10933. scale->ne[2] != 1 ||
  10934. scale->ne[3] != 1) {
  10935. return false;
  10936. }
  10937. return true;
  10938. };
  10939. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_ADD_ID) {
  10940. // additional constraints specific to this fusion
  10941. const ggml_tensor *mul = cgraph->nodes[node_idx];
  10942. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  10943. const ggml_tensor *bias = add->src[1];
  10944. if (mul != add->src[0]) {
  10945. return false;
  10946. }
  10947. // mat-vec only
  10948. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  10949. return false;
  10950. }
  10951. // shaders assume the types match
  10952. if (mul->type != bias->type) {
  10953. return false;
  10954. }
  10955. // shaders assume the bias is contiguous
  10956. if (!ggml_is_contiguous(bias)) {
  10957. return false;
  10958. }
  10959. // the ID tensor must be the same for mul_mat_id and add_id
  10960. if (mul->src[2] != add->src[2]) {
  10961. return false;
  10962. }
  10963. // unaligned bias isn't handled
  10964. if (get_misalign_bytes(ctx, bias) != 0) {
  10965. return false;
  10966. }
  10967. if (ops.size() == 3) {
  10968. if (ops.begin()[2] != GGML_OP_MUL) {
  10969. return false;
  10970. }
  10971. const ggml_tensor *mul = cgraph->nodes[node_idx + 2];
  10972. return mmid_mul_ok(add, mul);
  10973. }
  10974. }
  10975. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_MUL) {
  10976. // additional constraints specific to this fusion
  10977. const ggml_tensor *mmid = cgraph->nodes[node_idx];
  10978. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10979. if (!mmid_mul_ok(mmid, mul)) {
  10980. return false;
  10981. }
  10982. }
  10983. return true;
  10984. }
  10985. static bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10986. int node_idx, topk_moe_mode mode) {
  10987. const ggml_tensor * softmax;
  10988. const ggml_tensor * weights;
  10989. switch (mode) {
  10990. case TOPK_MOE_EARLY_SOFTMAX_NORM:
  10991. softmax = cgraph->nodes[node_idx + 0];
  10992. weights = cgraph->nodes[node_idx + 9];
  10993. break;
  10994. case TOPK_MOE_EARLY_SOFTMAX:
  10995. softmax = cgraph->nodes[node_idx + 0];
  10996. weights = cgraph->nodes[node_idx + 4];
  10997. break;
  10998. case TOPK_MOE_LATE_SOFTMAX:
  10999. softmax = cgraph->nodes[node_idx + 4];
  11000. weights = cgraph->nodes[node_idx + 5];
  11001. break;
  11002. default:
  11003. return false;
  11004. }
  11005. const float * op_params = (const float *)softmax->op_params;
  11006. float scale = op_params[0];
  11007. float max_bias = op_params[1];
  11008. if (!ggml_is_contiguous(softmax->src[0]) || !ggml_is_contiguous(weights)) {
  11009. return false;
  11010. }
  11011. if (scale != 1.0f || max_bias != 0.0f) {
  11012. return false;
  11013. }
  11014. // don't fuse when masks or sinks are present
  11015. if (softmax->src[1] || softmax->src[2]) {
  11016. return false;
  11017. }
  11018. const int n_expert = softmax->ne[0];
  11019. if (n_expert > (1 << (num_topk_moe_pipelines-1))) {
  11020. return false;
  11021. }
  11022. if (!ctx->device->subgroup_arithmetic ||
  11023. !ctx->device->subgroup_shuffle ||
  11024. !ctx->device->subgroup_require_full_support ||
  11025. ctx->device->disable_fusion) {
  11026. return false;
  11027. }
  11028. return true;
  11029. }
  11030. static bool ggml_vk_can_fuse_rope_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11031. int node_idx) {
  11032. GGML_UNUSED(ctx);
  11033. const ggml_tensor *rope = cgraph->nodes[node_idx + 0];
  11034. const ggml_tensor *view = cgraph->nodes[node_idx + 1];
  11035. const ggml_tensor *set_rows = cgraph->nodes[node_idx + 2];
  11036. // ne3 not tested
  11037. if (rope->src[0]->ne[3] != 1) {
  11038. return false;
  11039. }
  11040. if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) {
  11041. return false;
  11042. }
  11043. if (set_rows->src[1]->type != GGML_TYPE_I64) {
  11044. return false;
  11045. }
  11046. // The view should flatten two dims of rope into one dim
  11047. if (!ggml_is_contiguous(view) ||
  11048. view->ne[0] != rope->ne[0] * rope->ne[1]) {
  11049. return false;
  11050. }
  11051. // Only norm/neox shaders have the fusion code
  11052. const int mode = ((const int32_t *) rope->op_params)[2];
  11053. if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX) {
  11054. return false;
  11055. }
  11056. return true;
  11057. }
  11058. // Check whether the tensors overlap in memory but are not equal.
  11059. // Fusions can potenitally overwrite src tensors in ways that are not prevented
  11060. // by ggml-alloc. If the fusion is entirely elementwise, then it's OK for them
  11061. // to overlap if they are exactly equal.
  11062. // XXX TODO this check is probably missing from several fusion optimizations.
  11063. static bool ggml_vk_tensors_overlap_but_not_equal(const ggml_tensor * a, const ggml_tensor * b) {
  11064. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)a->buffer->context;
  11065. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  11066. ggml_backend_vk_buffer_context * b_buf_ctx = (ggml_backend_vk_buffer_context *)b->buffer->context;
  11067. vk_buffer b_buf = b_buf_ctx->dev_buffer;
  11068. if (a_buf == b_buf) {
  11069. auto a_base = vk_tensor_offset(a) + a->view_offs;
  11070. auto a_size = ggml_nbytes(a);
  11071. auto b_base = vk_tensor_offset(b) + b->view_offs;
  11072. auto b_size = ggml_nbytes(b);
  11073. if (a_base == b_base && a_size == b_size) {
  11074. return false;
  11075. }
  11076. if ((b_base <= a_base && a_base < b_base + b_size) ||
  11077. (a_base <= b_base && b_base < a_base + a_size)) {
  11078. return true;
  11079. }
  11080. }
  11081. return false;
  11082. }
  11083. static bool ggml_vk_can_fuse_rms_norm_mul_rope(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11084. int node_idx) {
  11085. GGML_UNUSED(ctx);
  11086. const ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  11087. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  11088. const ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  11089. const int mode = ((const int32_t *) rope->op_params)[2];
  11090. // noncontig tensors aren't tested, and don't seem common in practice
  11091. if (!ggml_is_contiguous(rms) ||
  11092. !ggml_is_contiguous(mul) ||
  11093. !ggml_is_contiguous(rope)) {
  11094. return false;
  11095. }
  11096. // only norm/neox are handled in the shader
  11097. if (mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_NORMAL) {
  11098. return false;
  11099. }
  11100. // shared memory size for passing data from mul->rope
  11101. if (mul->ne[0] > 1024) {
  11102. return false;
  11103. }
  11104. // must not overwrite srcs in a way that's not elementwise
  11105. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  11106. if (ggml_vk_tensors_overlap_but_not_equal(rms->src[0], rope) ||
  11107. ggml_vk_tensors_overlap_but_not_equal(other_src, rope)) {
  11108. return false;
  11109. }
  11110. // conditions for pipeline creation
  11111. if (!(ctx->device->float_controls_rte_fp16 &&
  11112. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= ctx->device->properties.limits.maxPushConstantsSize)) {
  11113. return false;
  11114. }
  11115. return true;
  11116. }
  11117. static uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) {
  11118. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  11119. if (first_node->op != GGML_OP_ADD) {
  11120. return 0;
  11121. }
  11122. if (!ctx->device->multi_add) {
  11123. return 0;
  11124. }
  11125. int32_t num_adds = 1;
  11126. while (node_idx + num_adds < cgraph->n_nodes &&
  11127. cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD &&
  11128. num_adds < MAX_FUSED_ADDS) {
  11129. num_adds++;
  11130. }
  11131. // The shader currently requires same shapes (but different strides are allowed),
  11132. // everything f32, and no misalignment
  11133. for (int32_t i = 0; i < num_adds; ++i) {
  11134. const ggml_tensor *next_node = cgraph->nodes[node_idx + i];
  11135. if (!ggml_are_same_shape(first_node, next_node->src[0]) ||
  11136. !ggml_are_same_shape(first_node, next_node->src[1]) ||
  11137. next_node->type != GGML_TYPE_F32 ||
  11138. next_node->src[0]->type != GGML_TYPE_F32 ||
  11139. next_node->src[1]->type != GGML_TYPE_F32 ||
  11140. get_misalign_bytes(ctx, next_node) ||
  11141. get_misalign_bytes(ctx, next_node->src[0]) ||
  11142. get_misalign_bytes(ctx, next_node->src[1])) {
  11143. num_adds = i;
  11144. }
  11145. }
  11146. // Verify we can fuse these
  11147. ggml_op adds[MAX_FUSED_ADDS];
  11148. for (int32_t i = 0; i < num_adds; ++i) {
  11149. adds[i] = GGML_OP_ADD;
  11150. }
  11151. // decrease num_adds if they can't all be fused
  11152. while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) {
  11153. num_adds--;
  11154. }
  11155. // a single add is not "fused", so just return zero
  11156. if (num_adds == 1) {
  11157. return 0;
  11158. }
  11159. return num_adds;
  11160. }
  11161. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  11162. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  11163. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11164. if (vk_instance.debug_utils_support) {
  11165. vk::DebugUtilsLabelEXT dul = {};
  11166. dul.pLabelName = "ggml_backend_vk_graph_compute";
  11167. dul.color = std::array<float,4>{1.0f, 1.0f, 1.0f, 1.0f};
  11168. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(ctx->device->compute_queue.queue, reinterpret_cast<VkDebugUtilsLabelEXT*>(&dul));
  11169. }
  11170. ctx->prealloc_size_add_rms_partials_offset = 0;
  11171. ctx->do_add_rms_partials = false;
  11172. ctx->do_add_rms_partials_offset_calculation = false;
  11173. int last_node = cgraph->n_nodes - 1;
  11174. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  11175. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  11176. last_node -= 1;
  11177. }
  11178. // Reserve tensor context space for all nodes
  11179. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  11180. bool first_node_in_batch = true; // true if next node will be first node in a batch
  11181. int submit_node_idx = 0; // index to first node in a batch
  11182. vk_context compute_ctx;
  11183. if (vk_perf_logger_enabled) {
  11184. // allocate/resize the query pool
  11185. if (ctx->num_queries < cgraph->n_nodes + 1) {
  11186. if (ctx->query_pool) {
  11187. ctx->device->device.destroyQueryPool(ctx->query_pool);
  11188. }
  11189. vk::QueryPoolCreateInfo query_create_info;
  11190. query_create_info.queryType = vk::QueryType::eTimestamp;
  11191. query_create_info.queryCount = cgraph->n_nodes + 100;
  11192. ctx->query_pool = ctx->device->device.createQueryPool(query_create_info);
  11193. ctx->num_queries = query_create_info.queryCount;
  11194. ctx->query_fusion_names.resize(ctx->num_queries);
  11195. ctx->query_nodes.resize(ctx->num_queries);
  11196. }
  11197. ctx->device->device.resetQueryPool(ctx->query_pool, 0, cgraph->n_nodes+1);
  11198. std::fill(ctx->query_fusion_names.begin(), ctx->query_fusion_names.end(), nullptr);
  11199. std::fill(ctx->query_nodes.begin(), ctx->query_nodes.end(), nullptr);
  11200. GGML_ASSERT(ctx->compute_ctx.expired());
  11201. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11202. ctx->compute_ctx = compute_ctx;
  11203. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11204. ctx->query_idx = 0;
  11205. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  11206. }
  11207. ctx->prealloc_y_last_pipeline_used = nullptr;
  11208. ctx->prealloc_y_last_tensor_used = nullptr;
  11209. if (ctx->prealloc_size_add_rms_partials) {
  11210. ggml_vk_preallocate_buffers(ctx, nullptr);
  11211. if (ctx->compute_ctx.expired()) {
  11212. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11213. ctx->compute_ctx = compute_ctx;
  11214. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11215. } else {
  11216. compute_ctx = ctx->compute_ctx.lock();
  11217. }
  11218. // initialize partial sums to zero.
  11219. ggml_vk_buffer_memset_async(compute_ctx, ctx->prealloc_add_rms_partials, 0, 0, ctx->prealloc_size_add_rms_partials);
  11220. ggml_vk_sync_buffers(ctx, compute_ctx);
  11221. }
  11222. // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution.
  11223. // Estimate the amount of matmul work by looking at the weight matrix size, and submit every 100MB
  11224. // (and scaled down based on model size, so smaller models submit earlier).
  11225. // Also submit at least every 100 nodes, in case there are workloads without as much matmul.
  11226. int nodes_per_submit = 100;
  11227. int submitted_nodes = 0;
  11228. int submit_count = 0;
  11229. uint64_t mul_mat_bytes = 0;
  11230. uint64_t total_mul_mat_bytes = 0;
  11231. uint64_t mul_mat_bytes_per_submit = std::min(uint64_t(100*1000*1000), ctx->last_total_mul_mat_bytes / 40u);
  11232. for (int i = 0; i < cgraph->n_nodes; i++) {
  11233. if (first_node_in_batch) {
  11234. submit_node_idx = i;
  11235. }
  11236. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  11237. auto bytes = ggml_nbytes(cgraph->nodes[i]->src[0]);
  11238. mul_mat_bytes += bytes;
  11239. total_mul_mat_bytes += bytes;
  11240. }
  11241. const char *fusion_string {};
  11242. if (!ctx->device->disable_fusion) {
  11243. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  11244. if (num_adds) {
  11245. ctx->num_additional_fused_ops = num_adds - 1;
  11246. fusion_string = "MULTI_ADD";
  11247. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_ADD })) {
  11248. ctx->num_additional_fused_ops = 2;
  11249. fusion_string = "MUL_MAT_ADD_ADD";
  11250. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD })) {
  11251. ctx->num_additional_fused_ops = 1;
  11252. fusion_string = "MUL_MAT_ADD";
  11253. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_MUL })) {
  11254. ctx->num_additional_fused_ops = 2;
  11255. fusion_string = "MUL_MAT_ID_ADD_ID_MUL";
  11256. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID })) {
  11257. ctx->num_additional_fused_ops = 1;
  11258. fusion_string = "MUL_MAT_ID_ADD_ID";
  11259. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_MUL })) {
  11260. ctx->num_additional_fused_ops = 1;
  11261. fusion_string = "MUL_MAT_ID_MUL";
  11262. } 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 }) &&
  11263. ggml_check_edges(cgraph, i, rms_norm_mul_rope_view_set_rows_edges) &&
  11264. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i) &&
  11265. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i + 2)) {
  11266. ctx->num_additional_fused_ops = 4;
  11267. fusion_string = "RMS_NORM_MUL_ROPE_VIEW_SET_ROWS";
  11268. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE })&&
  11269. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i)) {
  11270. ctx->num_additional_fused_ops = 2;
  11271. fusion_string = "RMS_NORM_MUL_ROPE";
  11272. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  11273. ctx->num_additional_fused_ops = 1;
  11274. fusion_string = "RMS_NORM_MUL";
  11275. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 2 }) &&
  11276. ggml_check_edges(cgraph, i, rope_view_set_rows_edges) &&
  11277. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i)) {
  11278. ctx->num_additional_fused_ops = 2;
  11279. fusion_string = "ROPE_VIEW_SET_ROWS";
  11280. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax_norm, { i + 3, i + 9 }) &&
  11281. ggml_check_edges(cgraph, i, topk_moe_early_softmax_norm_edges) &&
  11282. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX_NORM)) {
  11283. ctx->num_additional_fused_ops = topk_moe_early_softmax_norm.size() - 1;
  11284. // view of argsort writes to memory
  11285. ctx->fused_ops_write_mask |= 1 << 3;
  11286. fusion_string = "TOPK_MOE_EARLY_SOFTMAX_NORM";
  11287. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax, { i + 3, i + 4 }) &&
  11288. ggml_check_edges(cgraph, i, topk_moe_early_softmax_edges) &&
  11289. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX)) {
  11290. ctx->num_additional_fused_ops = topk_moe_early_softmax.size() - 1;
  11291. // view of argsort writes to memory
  11292. ctx->fused_ops_write_mask |= 1 << 3;
  11293. fusion_string = "TOPK_MOE_EARLY_SOFTMAX";
  11294. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_late_softmax, { i + 1, i + 5 }) &&
  11295. ggml_check_edges(cgraph, i, topk_moe_late_softmax_edges) &&
  11296. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_LATE_SOFTMAX)) {
  11297. ctx->num_additional_fused_ops = topk_moe_late_softmax.size() - 1;
  11298. // view of argsort writes to memory
  11299. ctx->fused_ops_write_mask |= 1 << 1;
  11300. fusion_string = "TOPK_MOE_LATE_SOFTMAX";
  11301. }
  11302. }
  11303. ctx->fused_ops_write_mask |= 1 << ctx->num_additional_fused_ops;
  11304. // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining)
  11305. bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5;
  11306. bool submit = (submitted_nodes >= nodes_per_submit) ||
  11307. (mul_mat_bytes_per_submit != 0 && mul_mat_bytes >= mul_mat_bytes_per_submit) ||
  11308. (i + ctx->num_additional_fused_ops >= last_node) ||
  11309. (almost_ready && !ctx->almost_ready_fence_pending);
  11310. 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);
  11311. if (vk_perf_logger_enabled && enqueued) {
  11312. if (ctx->compute_ctx.expired()) {
  11313. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11314. ctx->compute_ctx = compute_ctx;
  11315. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11316. } else {
  11317. compute_ctx = ctx->compute_ctx.lock();
  11318. }
  11319. ctx->query_nodes[ctx->query_idx] = cgraph->nodes[i];
  11320. ctx->query_fusion_names[ctx->query_idx] = fusion_string;
  11321. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->query_pool, ctx->query_idx++);
  11322. }
  11323. if (enqueued) {
  11324. ++submitted_nodes;
  11325. #ifndef GGML_VULKAN_CHECK_RESULTS
  11326. if (first_node_in_batch) {
  11327. first_node_in_batch = false;
  11328. }
  11329. #endif
  11330. }
  11331. if (submit && enqueued) {
  11332. first_node_in_batch = true;
  11333. submitted_nodes = 0;
  11334. mul_mat_bytes = 0;
  11335. if (submit_count < 3) {
  11336. mul_mat_bytes_per_submit *= 2;
  11337. }
  11338. submit_count++;
  11339. }
  11340. i += ctx->num_additional_fused_ops;
  11341. ctx->num_additional_fused_ops = 0;
  11342. ctx->fused_ops_write_mask = 0;
  11343. }
  11344. ctx->last_total_mul_mat_bytes = total_mul_mat_bytes;
  11345. if (vk_perf_logger_enabled) {
  11346. // End the command buffer and submit/wait
  11347. GGML_ASSERT(!ctx->compute_ctx.expired());
  11348. compute_ctx = ctx->compute_ctx.lock();
  11349. ggml_vk_ctx_end(compute_ctx);
  11350. ggml_vk_submit(compute_ctx, ctx->device->fence);
  11351. VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences");
  11352. ctx->device->device.resetFences({ ctx->device->fence });
  11353. // Get the results and pass them to the logger
  11354. std::vector<uint64_t> timestamps(cgraph->n_nodes + 1);
  11355. 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");
  11356. for (int i = 1; i < ctx->query_idx; i++) {
  11357. auto node = ctx->query_nodes[i];
  11358. auto name = ctx->query_fusion_names[i];
  11359. ctx->perf_logger->log_timing(node, name, uint64_t((timestamps[i] - timestamps[i-1]) * ctx->device->properties.limits.timestampPeriod));
  11360. }
  11361. ctx->perf_logger->print_timings();
  11362. }
  11363. if (!ctx->device->support_async) {
  11364. ggml_vk_synchronize(ctx);
  11365. }
  11366. return GGML_STATUS_SUCCESS;
  11367. UNUSED(backend);
  11368. }
  11369. // Sort the graph for improved parallelism.
  11370. static void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph)
  11371. {
  11372. VK_LOG_DEBUG("ggml_vk_graph_optimize(" << graph->n_nodes << " nodes)");
  11373. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11374. if (ctx->device->disable_graph_optimize) {
  11375. return;
  11376. }
  11377. auto const &is_empty = [](ggml_tensor * node) -> bool {
  11378. 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;
  11379. };
  11380. auto const &is_src_of = [](const ggml_tensor *dst, const ggml_tensor *src) -> bool {
  11381. for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) {
  11382. if (dst->src[s] == src) {
  11383. return true;
  11384. }
  11385. }
  11386. // implicit dependency if they view the same tensor
  11387. const ggml_tensor *dst2 = dst->view_src ? dst->view_src : dst;
  11388. const ggml_tensor *src2 = src->view_src ? src->view_src : src;
  11389. if (dst2 == src2) {
  11390. return true;
  11391. }
  11392. return false;
  11393. };
  11394. std::vector<ggml_tensor *> new_order;
  11395. std::vector<bool> used(graph->n_nodes, false);
  11396. std::set<ggml_tensor *> used_node_set;
  11397. int first_unused = 0;
  11398. while (first_unused < graph->n_nodes) {
  11399. std::vector<int> current_set;
  11400. // Check for fusion patterns and avoid reordering them
  11401. auto const &match_pattern = [&](const std::initializer_list<ggml_op> &pattern, int start) -> bool {
  11402. if (start + (int)pattern.size() <= graph->n_nodes) {
  11403. bool is_pattern = true;
  11404. for (size_t j = 0; j < pattern.size(); ++j) {
  11405. if (graph->nodes[start + j]->op != pattern.begin()[j] || used[start + j]) {
  11406. is_pattern = false;
  11407. }
  11408. }
  11409. return is_pattern;
  11410. }
  11411. return false;
  11412. };
  11413. auto const &keep_pattern = [&](const std::initializer_list<ggml_op> &pattern) -> bool {
  11414. if (match_pattern(pattern, first_unused)) {
  11415. for (size_t j = 0; j < pattern.size(); ++j) {
  11416. new_order.push_back(graph->nodes[first_unused + j]);
  11417. used_node_set.insert(graph->nodes[first_unused + j]);
  11418. used[first_unused + j] = true;
  11419. }
  11420. while (first_unused < graph->n_nodes && used[first_unused]) {
  11421. first_unused++;
  11422. }
  11423. return true;
  11424. }
  11425. return false;
  11426. };
  11427. if (keep_pattern(topk_moe_early_softmax_norm)) {
  11428. continue;
  11429. }
  11430. if (keep_pattern(topk_moe_early_softmax)) {
  11431. continue;
  11432. }
  11433. if (keep_pattern(topk_moe_late_softmax)) {
  11434. continue;
  11435. }
  11436. // First, grab the next unused node.
  11437. current_set.push_back(first_unused);
  11438. // Loop through the next N nodes. Grab any that don't depend on other nodes that
  11439. // haven't already been run. Nodes that have already been run have used[i] set
  11440. // to true. Allow nodes that depend on the previous node if it's a fusion pattern
  11441. // that we support (e.g. RMS_NORM + MUL).
  11442. // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes.
  11443. // The goal is to not interleave real and view nodes in a way that breaks fusion.
  11444. const int NUM_TO_CHECK = 20;
  11445. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11446. if (used[j]) {
  11447. continue;
  11448. }
  11449. if (is_empty(graph->nodes[j])) {
  11450. continue;
  11451. }
  11452. // Don't pull forward nodes from fusion patterns
  11453. if (match_pattern(topk_moe_early_softmax_norm, j) ||
  11454. match_pattern(topk_moe_early_softmax, j) ||
  11455. match_pattern(topk_moe_late_softmax, j)) {
  11456. continue;
  11457. }
  11458. bool ok = true;
  11459. for (int c = first_unused; c < j; ++c) {
  11460. if (!used[c] &&
  11461. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11462. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL) &&
  11463. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT && graph->nodes[j]->op == GGML_OP_ADD) &&
  11464. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_ADD_ID) &&
  11465. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_MUL)) {
  11466. ok = false;
  11467. break;
  11468. }
  11469. }
  11470. if (ok) {
  11471. current_set.push_back(j);
  11472. int rope_idx = j;
  11473. // When we've found RMS_NORM + MUL, try to find a ROPE that uses it
  11474. if (j > 0 &&
  11475. graph->nodes[j]->op == GGML_OP_MUL &&
  11476. graph->nodes[j-1]->op == GGML_OP_RMS_NORM) {
  11477. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11478. if (graph->nodes[k]->op == GGML_OP_ROPE &&
  11479. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11480. // Check that other srcs are already valid
  11481. graph->nodes[k]->src[1]->op == GGML_OP_NONE &&
  11482. (graph->nodes[k]->src[2] == nullptr || graph->nodes[k]->src[2]->op == GGML_OP_NONE)) {
  11483. rope_idx = k;
  11484. current_set.push_back(rope_idx);
  11485. used[rope_idx] = true;
  11486. break;
  11487. }
  11488. }
  11489. }
  11490. // Look for ROPE + VIEW + SET_ROWS and make them consecutive
  11491. if (graph->nodes[rope_idx]->op == GGML_OP_ROPE) {
  11492. int view_idx = -1;
  11493. int set_rows_idx = -1;
  11494. for (int k = rope_idx+1; k < std::min(rope_idx + 10, graph->n_nodes); ++k) {
  11495. if (view_idx == -1 &&
  11496. graph->nodes[k]->op == GGML_OP_VIEW &&
  11497. graph->nodes[k]->src[0] == graph->nodes[rope_idx]) {
  11498. view_idx = k;
  11499. continue;
  11500. }
  11501. if (view_idx != -1 &&
  11502. set_rows_idx == -1 &&
  11503. graph->nodes[k]->op == GGML_OP_SET_ROWS &&
  11504. graph->nodes[k]->src[0] == graph->nodes[view_idx]) {
  11505. set_rows_idx = k;
  11506. break;
  11507. }
  11508. }
  11509. if (set_rows_idx != -1) {
  11510. current_set.push_back(view_idx);
  11511. current_set.push_back(set_rows_idx);
  11512. used[view_idx] = true;
  11513. used[set_rows_idx] = true;
  11514. }
  11515. }
  11516. // Look for MUL_MAT_ID + ADD_ID + MUL
  11517. if (j > 0 &&
  11518. graph->nodes[j]->op == GGML_OP_ADD_ID &&
  11519. graph->nodes[j-1]->op == GGML_OP_MUL_MAT_ID) {
  11520. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11521. if (graph->nodes[k]->op == GGML_OP_MUL &&
  11522. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11523. // src1 must either be weights or already processed
  11524. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  11525. current_set.push_back(k);
  11526. used[k] = true;
  11527. break;
  11528. }
  11529. }
  11530. }
  11531. // Look for MUL_MAT + ADD + ADD
  11532. if (j > 0 &&
  11533. graph->nodes[j]->op == GGML_OP_ADD &&
  11534. graph->nodes[j-1]->op == GGML_OP_MUL_MAT) {
  11535. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11536. if (graph->nodes[k]->op == GGML_OP_ADD &&
  11537. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11538. // src1 must either be weights or already processed
  11539. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  11540. current_set.push_back(k);
  11541. used[k] = true;
  11542. break;
  11543. }
  11544. }
  11545. }
  11546. }
  11547. }
  11548. // Second pass grabs view nodes.
  11549. // Skip this if it would break a fusion optimization (don't split up add->rms_norm or add->add).
  11550. if (graph->nodes[current_set.back()]->op != GGML_OP_ADD) {
  11551. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11552. if (used[j]) {
  11553. continue;
  11554. }
  11555. if (!is_empty(graph->nodes[j])) {
  11556. continue;
  11557. }
  11558. bool ok = true;
  11559. for (int c = first_unused; c < j; ++c) {
  11560. bool c_in_current_set = std::find(current_set.begin(), current_set.end(), c) != current_set.end();
  11561. // skip views whose srcs haven't been processed.
  11562. if (!used[c] &&
  11563. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11564. !c_in_current_set) {
  11565. ok = false;
  11566. break;
  11567. }
  11568. }
  11569. if (ok) {
  11570. current_set.push_back(j);
  11571. }
  11572. }
  11573. }
  11574. // Push the current set into new_order
  11575. for (auto c : current_set) {
  11576. new_order.push_back(graph->nodes[c]);
  11577. used_node_set.insert(graph->nodes[c]);
  11578. used[c] = true;
  11579. }
  11580. while (first_unused < graph->n_nodes && used[first_unused]) {
  11581. first_unused++;
  11582. }
  11583. }
  11584. // Replace the graph with the new order.
  11585. for (int i = 0; i < graph->n_nodes; ++i) {
  11586. graph->nodes[i] = new_order[i];
  11587. }
  11588. }
  11589. // TODO: enable async and synchronize
  11590. static ggml_backend_i ggml_backend_vk_interface = {
  11591. /* .get_name = */ ggml_backend_vk_name,
  11592. /* .free = */ ggml_backend_vk_free,
  11593. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  11594. /* .get_tensor_async = */ ggml_backend_vk_get_tensor_async,
  11595. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  11596. /* .synchronize = */ ggml_backend_vk_synchronize,
  11597. /* .graph_plan_create = */ NULL,
  11598. /* .graph_plan_free = */ NULL,
  11599. /* .graph_plan_update = */ NULL,
  11600. /* .graph_plan_compute = */ NULL,
  11601. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  11602. /* .event_record = */ NULL,
  11603. /* .event_wait = */ NULL,
  11604. /* .graph_optimize = */ ggml_vk_graph_optimize,
  11605. };
  11606. static ggml_guid_t ggml_backend_vk_guid() {
  11607. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  11608. return &guid;
  11609. }
  11610. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  11611. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  11612. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  11613. ggml_vk_init(ctx, dev_num);
  11614. ggml_backend_t vk_backend = new ggml_backend {
  11615. /* .guid = */ ggml_backend_vk_guid(),
  11616. /* .iface = */ ggml_backend_vk_interface,
  11617. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  11618. /* .context = */ ctx,
  11619. };
  11620. if (!ctx->device->support_async) {
  11621. vk_backend->iface.get_tensor_async = nullptr;
  11622. }
  11623. return vk_backend;
  11624. }
  11625. bool ggml_backend_is_vk(ggml_backend_t backend) {
  11626. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  11627. }
  11628. int ggml_backend_vk_get_device_count() {
  11629. return ggml_vk_get_device_count();
  11630. }
  11631. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  11632. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11633. int dev_idx = vk_instance.device_indices[device];
  11634. ggml_vk_get_device_description(dev_idx, description, description_size);
  11635. }
  11636. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  11637. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11638. GGML_ASSERT(device < (int) vk_instance.device_supports_membudget.size());
  11639. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  11640. vk::PhysicalDeviceMemoryBudgetPropertiesEXT budgetprops;
  11641. vk::PhysicalDeviceMemoryProperties2 memprops = {};
  11642. const bool membudget_supported = vk_instance.device_supports_membudget[device];
  11643. const bool is_integrated_gpu = vkdev.getProperties().deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  11644. if (membudget_supported) {
  11645. memprops.pNext = &budgetprops;
  11646. }
  11647. vkdev.getMemoryProperties2(&memprops);
  11648. *total = 0;
  11649. *free = 0;
  11650. for (uint32_t i = 0; i < memprops.memoryProperties.memoryHeapCount; ++i) {
  11651. const vk::MemoryHeap & heap = memprops.memoryProperties.memoryHeaps[i];
  11652. if (is_integrated_gpu || (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal)) {
  11653. *total += heap.size;
  11654. if (membudget_supported && i < budgetprops.heapUsage.size()) {
  11655. *free += budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
  11656. } else {
  11657. *free += heap.size;
  11658. }
  11659. }
  11660. }
  11661. }
  11662. static vk::PhysicalDeviceType ggml_backend_vk_get_device_type(int device_idx) {
  11663. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11664. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11665. vk::PhysicalDeviceProperties2 props = {};
  11666. device.getProperties2(&props);
  11667. return props.properties.deviceType;
  11668. }
  11669. static std::string ggml_backend_vk_get_device_pci_id(int device_idx) {
  11670. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11671. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11672. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  11673. bool ext_support = false;
  11674. for (const auto& properties : ext_props) {
  11675. if (strcmp("VK_EXT_pci_bus_info", properties.extensionName) == 0) {
  11676. ext_support = true;
  11677. break;
  11678. }
  11679. }
  11680. if (!ext_support) {
  11681. return "";
  11682. }
  11683. vk::PhysicalDeviceProperties2 props = {};
  11684. vk::PhysicalDevicePCIBusInfoPropertiesEXT pci_bus_info = {};
  11685. props.pNext = &pci_bus_info;
  11686. device.getProperties2(&props);
  11687. const uint32_t pci_domain = pci_bus_info.pciDomain;
  11688. const uint32_t pci_bus = pci_bus_info.pciBus;
  11689. const uint32_t pci_device = pci_bus_info.pciDevice;
  11690. const uint8_t pci_function = (uint8_t) pci_bus_info.pciFunction; // pci function is between 0 and 7, prevent printf overflow warning
  11691. char pci_bus_id[16] = {};
  11692. snprintf(pci_bus_id, sizeof(pci_bus_id), "%04x:%02x:%02x.%x", pci_domain, pci_bus, pci_device, pci_function);
  11693. return std::string(pci_bus_id);
  11694. }
  11695. //////////////////////////
  11696. struct ggml_backend_vk_device_context {
  11697. size_t device;
  11698. std::string name;
  11699. std::string description;
  11700. bool is_integrated_gpu;
  11701. std::string pci_bus_id;
  11702. };
  11703. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  11704. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11705. return ctx->name.c_str();
  11706. }
  11707. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  11708. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11709. return ctx->description.c_str();
  11710. }
  11711. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  11712. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  11713. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  11714. }
  11715. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  11716. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11717. return ggml_backend_vk_buffer_type(ctx->device);
  11718. }
  11719. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  11720. UNUSED(dev);
  11721. return ggml_backend_vk_host_buffer_type();
  11722. }
  11723. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  11724. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11725. return ctx->is_integrated_gpu ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
  11726. }
  11727. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  11728. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11729. props->name = ggml_backend_vk_device_get_name(dev);
  11730. props->description = ggml_backend_vk_device_get_description(dev);
  11731. props->type = ggml_backend_vk_device_get_type(dev);
  11732. props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str();
  11733. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  11734. props->caps = {
  11735. /* .async = */ false,
  11736. /* .host_buffer = */ true,
  11737. /* .buffer_from_host_ptr = */ false,
  11738. /* .events = */ false,
  11739. };
  11740. }
  11741. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  11742. UNUSED(params);
  11743. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11744. return ggml_backend_vk_init(ctx->device);
  11745. }
  11746. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  11747. switch (op->op) {
  11748. case GGML_OP_UNARY:
  11749. switch (ggml_get_unary_op(op)) {
  11750. case GGML_UNARY_OP_EXP:
  11751. case GGML_UNARY_OP_GELU:
  11752. case GGML_UNARY_OP_GELU_ERF:
  11753. case GGML_UNARY_OP_GELU_QUICK:
  11754. case GGML_UNARY_OP_SILU:
  11755. case GGML_UNARY_OP_RELU:
  11756. case GGML_UNARY_OP_NEG:
  11757. case GGML_UNARY_OP_TANH:
  11758. case GGML_UNARY_OP_SIGMOID:
  11759. case GGML_UNARY_OP_HARDSIGMOID:
  11760. case GGML_UNARY_OP_HARDSWISH:
  11761. case GGML_UNARY_OP_ABS:
  11762. case GGML_UNARY_OP_SOFTPLUS:
  11763. case GGML_UNARY_OP_STEP:
  11764. case GGML_UNARY_OP_ROUND:
  11765. case GGML_UNARY_OP_CEIL:
  11766. case GGML_UNARY_OP_FLOOR:
  11767. case GGML_UNARY_OP_TRUNC:
  11768. return ggml_is_contiguous(op->src[0]) &&
  11769. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11770. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11771. (op->src[0]->type == op->type);
  11772. default:
  11773. return false;
  11774. }
  11775. case GGML_OP_GLU:
  11776. switch (ggml_get_glu_op(op)) {
  11777. case GGML_GLU_OP_GEGLU:
  11778. case GGML_GLU_OP_REGLU:
  11779. case GGML_GLU_OP_SWIGLU:
  11780. case GGML_GLU_OP_SWIGLU_OAI:
  11781. case GGML_GLU_OP_GEGLU_ERF:
  11782. case GGML_GLU_OP_GEGLU_QUICK:
  11783. return ggml_is_contiguous(op->src[0]) &&
  11784. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11785. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11786. (op->src[0]->type == op->type);
  11787. default:
  11788. return false;
  11789. }
  11790. case GGML_OP_MUL_MAT:
  11791. case GGML_OP_MUL_MAT_ID:
  11792. {
  11793. ggml_type src0_type = op->src[0]->type;
  11794. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11795. const vk_device& device = ggml_vk_get_device(ctx->device);
  11796. if (op->op == GGML_OP_MUL_MAT_ID) {
  11797. if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) {
  11798. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  11799. return false;
  11800. }
  11801. }
  11802. switch (src0_type) {
  11803. case GGML_TYPE_F32:
  11804. case GGML_TYPE_F16:
  11805. case GGML_TYPE_BF16:
  11806. case GGML_TYPE_Q4_0:
  11807. case GGML_TYPE_Q4_1:
  11808. case GGML_TYPE_Q5_0:
  11809. case GGML_TYPE_Q5_1:
  11810. case GGML_TYPE_Q8_0:
  11811. case GGML_TYPE_Q2_K:
  11812. case GGML_TYPE_Q3_K:
  11813. case GGML_TYPE_Q4_K:
  11814. case GGML_TYPE_Q5_K:
  11815. case GGML_TYPE_Q6_K:
  11816. case GGML_TYPE_IQ1_S:
  11817. case GGML_TYPE_IQ1_M:
  11818. case GGML_TYPE_IQ2_XXS:
  11819. case GGML_TYPE_IQ2_XS:
  11820. case GGML_TYPE_IQ2_S:
  11821. case GGML_TYPE_IQ3_XXS:
  11822. case GGML_TYPE_IQ3_S:
  11823. case GGML_TYPE_IQ4_XS:
  11824. case GGML_TYPE_IQ4_NL:
  11825. case GGML_TYPE_MXFP4:
  11826. break;
  11827. default:
  11828. return false;
  11829. }
  11830. struct ggml_tensor * a;
  11831. struct ggml_tensor * b;
  11832. if (op->op == GGML_OP_MUL_MAT) {
  11833. a = op->src[0];
  11834. b = op->src[1];
  11835. } else {
  11836. a = op->src[2];
  11837. b = op->src[1];
  11838. }
  11839. if (a->ne[3] != b->ne[3]) {
  11840. return false;
  11841. }
  11842. 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) ||
  11843. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  11844. return false;
  11845. }
  11846. if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) {
  11847. // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader.
  11848. // So don't support this combination for now.
  11849. return false;
  11850. }
  11851. return true;
  11852. }
  11853. case GGML_OP_FLASH_ATTN_EXT:
  11854. {
  11855. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11856. auto device = ggml_vk_get_device(ctx->device);
  11857. bool coopmat2 = device->coopmat2;
  11858. uint32_t HSK = op->src[1]->ne[0];
  11859. uint32_t HSV = op->src[2]->ne[0];
  11860. if ((HSK % 8) != 0 || (HSV % 8) != 0) {
  11861. return false;
  11862. }
  11863. if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) {
  11864. return false;
  11865. }
  11866. if (op->src[0]->type != GGML_TYPE_F32) {
  11867. return false;
  11868. }
  11869. if (op->type != GGML_TYPE_F32) {
  11870. return false;
  11871. }
  11872. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  11873. return false;
  11874. }
  11875. // It's straightforward to support different K/V dequant, but would
  11876. // significantly increase the number of pipelines
  11877. if (op->src[1]->type != op->src[2]->type) {
  11878. return false;
  11879. }
  11880. switch (op->src[1]->type) {
  11881. case GGML_TYPE_F16:
  11882. case GGML_TYPE_F32:
  11883. case GGML_TYPE_Q4_0:
  11884. case GGML_TYPE_Q8_0:
  11885. // supported in scalar and coopmat2 paths
  11886. break;
  11887. case GGML_TYPE_Q4_1:
  11888. case GGML_TYPE_Q5_0:
  11889. case GGML_TYPE_Q5_1:
  11890. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  11891. //case GGML_TYPE_Q2_K:
  11892. //case GGML_TYPE_Q3_K:
  11893. //case GGML_TYPE_Q4_K:
  11894. //case GGML_TYPE_Q5_K:
  11895. //case GGML_TYPE_Q6_K:
  11896. //case GGML_TYPE_IQ1_S:
  11897. //case GGML_TYPE_IQ1_M:
  11898. //case GGML_TYPE_IQ2_XXS:
  11899. //case GGML_TYPE_IQ2_XS:
  11900. //case GGML_TYPE_IQ2_S:
  11901. //case GGML_TYPE_IQ3_XXS:
  11902. //case GGML_TYPE_IQ3_S:
  11903. //case GGML_TYPE_IQ4_XS:
  11904. case GGML_TYPE_IQ4_NL:
  11905. // currently supported only in coopmat2 path
  11906. if (!coopmat2) {
  11907. return false;
  11908. }
  11909. break;
  11910. default:
  11911. return false;
  11912. }
  11913. if (!coopmat2 && !(device->subgroup_shuffle && device->subgroup_vote)) {
  11914. // scalar/coopmat1 FA uses subgroupShuffle/subgroupAll
  11915. return false;
  11916. }
  11917. return true;
  11918. }
  11919. case GGML_OP_GET_ROWS:
  11920. {
  11921. switch (op->src[0]->type) {
  11922. case GGML_TYPE_F32:
  11923. case GGML_TYPE_F16:
  11924. case GGML_TYPE_BF16:
  11925. case GGML_TYPE_Q4_0:
  11926. case GGML_TYPE_Q4_1:
  11927. case GGML_TYPE_Q5_0:
  11928. case GGML_TYPE_Q5_1:
  11929. case GGML_TYPE_Q8_0:
  11930. case GGML_TYPE_Q2_K:
  11931. case GGML_TYPE_Q3_K:
  11932. case GGML_TYPE_Q4_K:
  11933. case GGML_TYPE_Q5_K:
  11934. case GGML_TYPE_Q6_K:
  11935. case GGML_TYPE_IQ1_S:
  11936. case GGML_TYPE_IQ1_M:
  11937. case GGML_TYPE_IQ2_XXS:
  11938. case GGML_TYPE_IQ2_XS:
  11939. case GGML_TYPE_IQ2_S:
  11940. case GGML_TYPE_IQ3_XXS:
  11941. case GGML_TYPE_IQ3_S:
  11942. case GGML_TYPE_IQ4_XS:
  11943. case GGML_TYPE_IQ4_NL:
  11944. case GGML_TYPE_MXFP4:
  11945. return true;
  11946. default:
  11947. return false;
  11948. }
  11949. }
  11950. case GGML_OP_SET_ROWS:
  11951. {
  11952. switch (op->type) {
  11953. case GGML_TYPE_F32:
  11954. case GGML_TYPE_F16:
  11955. case GGML_TYPE_BF16:
  11956. case GGML_TYPE_Q4_0:
  11957. case GGML_TYPE_Q4_1:
  11958. case GGML_TYPE_Q5_0:
  11959. case GGML_TYPE_Q5_1:
  11960. case GGML_TYPE_Q8_0:
  11961. case GGML_TYPE_IQ4_NL:
  11962. return true;
  11963. default:
  11964. return false;
  11965. }
  11966. }
  11967. case GGML_OP_CONT:
  11968. case GGML_OP_CPY:
  11969. case GGML_OP_DUP:
  11970. {
  11971. ggml_type src0_type = op->src[0]->type;
  11972. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  11973. if (src0_type == GGML_TYPE_F32) {
  11974. switch (src1_type) {
  11975. case GGML_TYPE_F32:
  11976. case GGML_TYPE_F16:
  11977. case GGML_TYPE_BF16:
  11978. case GGML_TYPE_Q4_0:
  11979. case GGML_TYPE_Q4_1:
  11980. case GGML_TYPE_Q5_0:
  11981. case GGML_TYPE_Q5_1:
  11982. case GGML_TYPE_Q8_0:
  11983. case GGML_TYPE_IQ4_NL:
  11984. return true;
  11985. default:
  11986. break;
  11987. }
  11988. }
  11989. if (src1_type == GGML_TYPE_F32) {
  11990. switch (src0_type) {
  11991. case GGML_TYPE_F16:
  11992. case GGML_TYPE_Q4_0:
  11993. case GGML_TYPE_Q4_1:
  11994. case GGML_TYPE_Q5_0:
  11995. case GGML_TYPE_Q5_1:
  11996. case GGML_TYPE_Q8_0:
  11997. case GGML_TYPE_IQ4_NL:
  11998. return true;
  11999. default:
  12000. break;
  12001. }
  12002. }
  12003. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  12004. return true;
  12005. }
  12006. if (
  12007. (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) ||
  12008. (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32)
  12009. ) {
  12010. return true;
  12011. }
  12012. // We can handle copying from a type to the same type if it's
  12013. // either not quantized or is quantized and contiguous.
  12014. // We use f16 or f32 shaders to do the copy,
  12015. // so the type/block size must be a multiple of 4.
  12016. if (src0_type == src1_type &&
  12017. (!ggml_is_quantized(src0_type) || (ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op))) &&
  12018. (ggml_type_size(src0_type) % 2) == 0) {
  12019. return true;
  12020. }
  12021. return false;
  12022. }
  12023. case GGML_OP_REPEAT:
  12024. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  12025. case GGML_OP_REPEAT_BACK:
  12026. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32;
  12027. case GGML_OP_ROPE:
  12028. case GGML_OP_ROPE_BACK:
  12029. case GGML_OP_NONE:
  12030. case GGML_OP_RESHAPE:
  12031. case GGML_OP_VIEW:
  12032. case GGML_OP_PERMUTE:
  12033. case GGML_OP_TRANSPOSE:
  12034. case GGML_OP_RMS_NORM:
  12035. return true;
  12036. case GGML_OP_NORM:
  12037. case GGML_OP_GROUP_NORM:
  12038. case GGML_OP_L2_NORM:
  12039. return ggml_is_contiguous(op->src[0]);
  12040. case GGML_OP_ADD:
  12041. case GGML_OP_SUB:
  12042. case GGML_OP_MUL:
  12043. case GGML_OP_DIV:
  12044. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12045. (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
  12046. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12047. case GGML_OP_ADD_ID:
  12048. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 &&
  12049. op->type == GGML_TYPE_F32;
  12050. case GGML_OP_SILU_BACK:
  12051. case GGML_OP_RMS_NORM_BACK:
  12052. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12053. case GGML_OP_SQR:
  12054. case GGML_OP_SQRT:
  12055. case GGML_OP_SIN:
  12056. case GGML_OP_COS:
  12057. case GGML_OP_CLAMP:
  12058. return op->src[0]->type == GGML_TYPE_F32;
  12059. case GGML_OP_LEAKY_RELU:
  12060. case GGML_OP_OPT_STEP_ADAMW:
  12061. case GGML_OP_OPT_STEP_SGD:
  12062. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12063. case GGML_OP_LOG:
  12064. case GGML_OP_TRI:
  12065. case GGML_OP_DIAG:
  12066. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12067. op->type == op->src[0]->type;
  12068. case GGML_OP_ARGSORT:
  12069. {
  12070. if (!ggml_is_contiguous(op) || !ggml_is_contiguous(op->src[0])) {
  12071. return false;
  12072. }
  12073. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12074. auto device = ggml_vk_get_device(ctx->device);
  12075. // pipeline_argsort_large_f32 requires vulkan memory model.
  12076. if (device->vulkan_memory_model) {
  12077. return true;
  12078. } else {
  12079. return op->ne[0] <= (1 << device->max_workgroup_size_log2);
  12080. }
  12081. }
  12082. case GGML_OP_TOP_K:
  12083. {
  12084. if (!ggml_is_contiguous(op) || !ggml_is_contiguous(op->src[0])) {
  12085. return false;
  12086. }
  12087. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12088. auto device = ggml_vk_get_device(ctx->device);
  12089. // We could potentially support larger, using argsort to sort the
  12090. // whole thing. Not clear if this is needed.
  12091. uint32_t min_pipeline = (uint32_t)log2f(float(op->ne[0])) + 1;
  12092. if (min_pipeline >= num_topk_pipelines ||
  12093. !device->pipeline_topk_f32[min_pipeline]) {
  12094. return false;
  12095. }
  12096. }
  12097. return true;
  12098. case GGML_OP_UPSCALE:
  12099. return op->src[0]->type == GGML_TYPE_F32 && !(op->op_params[0] & GGML_SCALE_FLAG_ANTIALIAS);
  12100. case GGML_OP_ACC:
  12101. return op->src[0]->type == GGML_TYPE_F32;
  12102. case GGML_OP_CONCAT:
  12103. return ggml_type_size(op->src[0]->type) == ggml_type_size(GGML_TYPE_F32);
  12104. case GGML_OP_ADD1:
  12105. return (op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32)
  12106. || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F32)
  12107. || (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F16);
  12108. case GGML_OP_ARANGE:
  12109. case GGML_OP_FILL:
  12110. return op->type == GGML_TYPE_F32;
  12111. case GGML_OP_SCALE:
  12112. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12113. case GGML_OP_PAD:
  12114. case GGML_OP_ROLL:
  12115. return op->src[0]->type == GGML_TYPE_F32;
  12116. case GGML_OP_DIAG_MASK_INF:
  12117. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12118. case GGML_OP_SOFT_MAX:
  12119. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32
  12120. && (!op->src[1] || (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16));
  12121. case GGML_OP_SOFT_MAX_BACK:
  12122. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32
  12123. && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32;
  12124. case GGML_OP_SUM:
  12125. case GGML_OP_SUM_ROWS:
  12126. case GGML_OP_MEAN:
  12127. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  12128. case GGML_OP_CUMSUM:
  12129. {
  12130. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12131. auto device = ggml_vk_get_device(ctx->device);
  12132. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  12133. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  12134. }
  12135. return false;
  12136. }
  12137. case GGML_OP_SOLVE_TRI:
  12138. {
  12139. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12140. const vk_device& device = ggml_vk_get_device(ctx->device);
  12141. if (op->type != GGML_TYPE_F32 || op->src[0]->type != GGML_TYPE_F32) {
  12142. return false;
  12143. }
  12144. const uint32_t N = op->src[0]->ne[0];
  12145. const uint32_t K = op->src[1]->ne[0];
  12146. // K dimension limited to workgroup size
  12147. if (K > 1u << device->max_workgroup_size_log2) {
  12148. return false;
  12149. }
  12150. const uint32_t batch_N = device->properties.limits.maxComputeSharedMemorySize / ((N + K) * sizeof(float));
  12151. if (batch_N == 0) {
  12152. return false;
  12153. }
  12154. return true;
  12155. }
  12156. case GGML_OP_ARGMAX:
  12157. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12158. case GGML_OP_COUNT_EQUAL:
  12159. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_I32
  12160. && ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_I32;
  12161. case GGML_OP_IM2COL:
  12162. return ggml_is_contiguous(op->src[1])
  12163. && op->src[1]->type == GGML_TYPE_F32
  12164. && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12165. case GGML_OP_IM2COL_3D:
  12166. return op->src[1]->type == GGML_TYPE_F32
  12167. && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  12168. case GGML_OP_TIMESTEP_EMBEDDING:
  12169. return op->src[0]->type == GGML_TYPE_F32;
  12170. case GGML_OP_CONV_2D_DW:
  12171. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16)
  12172. && op->src[1]->type == GGML_TYPE_F32;
  12173. case GGML_OP_POOL_2D:
  12174. return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32;
  12175. case GGML_OP_RWKV_WKV6:
  12176. case GGML_OP_RWKV_WKV7:
  12177. return true; // all inputs are contiguous, see ggml.c
  12178. case GGML_OP_SSM_SCAN:
  12179. {
  12180. for (int i = 0; i < 6; i++) {
  12181. if (op->src[i] && ggml_is_quantized(op->src[i]->type)) {
  12182. return false;
  12183. }
  12184. }
  12185. if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) {
  12186. return false;
  12187. }
  12188. if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
  12189. return false;
  12190. }
  12191. const uint32_t d_state = op->src[0]->ne[0];
  12192. const uint32_t head_dim = op->src[0]->ne[1];
  12193. bool is_mamba2 = (op->src[3] && op->src[3]->nb[1] == sizeof(float));
  12194. if (!is_mamba2) {
  12195. return false;
  12196. }
  12197. if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
  12198. return false;
  12199. }
  12200. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12201. const vk_device& device = ggml_vk_get_device(ctx->device);
  12202. const uint32_t SPLIT_H = 16;
  12203. size_t stateC_size = SPLIT_H * d_state * sizeof(float);
  12204. if (stateC_size > device->properties.limits.maxComputeSharedMemorySize) {
  12205. return false;
  12206. }
  12207. return true;
  12208. }
  12209. case GGML_OP_SSM_CONV:
  12210. return op->src[0]->type == GGML_TYPE_F32;
  12211. case GGML_OP_CONV_TRANSPOSE_1D:
  12212. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  12213. case GGML_OP_CONV_2D:
  12214. case GGML_OP_CONV_TRANSPOSE_2D:
  12215. {
  12216. // Channel-contiguous format is not supported yet.
  12217. return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12218. op->src[1]->type == GGML_TYPE_F32 &&
  12219. op->type == GGML_TYPE_F32 &&
  12220. ggml_is_contiguous(op->src[0]) &&
  12221. ggml_is_contiguous(op->src[1]) &&
  12222. ggml_is_contiguous(op));
  12223. }
  12224. default:
  12225. return false;
  12226. }
  12227. UNUSED(dev);
  12228. }
  12229. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  12230. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  12231. return false;
  12232. }
  12233. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12234. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  12235. return buft_ctx->device->idx == ctx->device;
  12236. }
  12237. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  12238. const int min_batch_size = 32;
  12239. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  12240. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  12241. UNUSED(dev);
  12242. }
  12243. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  12244. /* .get_name = */ ggml_backend_vk_device_get_name,
  12245. /* .get_description = */ ggml_backend_vk_device_get_description,
  12246. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  12247. /* .get_type = */ ggml_backend_vk_device_get_type,
  12248. /* .get_props = */ ggml_backend_vk_device_get_props,
  12249. /* .init_backend = */ ggml_backend_vk_device_init,
  12250. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  12251. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  12252. /* .buffer_from_host_ptr = */ NULL,
  12253. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  12254. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  12255. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  12256. /* .event_new = */ NULL,
  12257. /* .event_free = */ NULL,
  12258. /* .event_synchronize = */ NULL,
  12259. };
  12260. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  12261. UNUSED(reg);
  12262. return GGML_VK_NAME;
  12263. }
  12264. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  12265. UNUSED(reg);
  12266. return ggml_backend_vk_get_device_count();
  12267. }
  12268. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  12269. static std::vector<ggml_backend_dev_t> devices;
  12270. static bool initialized = false;
  12271. {
  12272. static std::mutex mutex;
  12273. std::lock_guard<std::mutex> lock(mutex);
  12274. if (!initialized) {
  12275. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  12276. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  12277. char desc[256];
  12278. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  12279. ctx->device = i;
  12280. ctx->name = GGML_VK_NAME + std::to_string(i);
  12281. ctx->description = desc;
  12282. ctx->is_integrated_gpu = ggml_backend_vk_get_device_type(i) == vk::PhysicalDeviceType::eIntegratedGpu;
  12283. ctx->pci_bus_id = ggml_backend_vk_get_device_pci_id(i);
  12284. devices.push_back(new ggml_backend_device {
  12285. /* .iface = */ ggml_backend_vk_device_i,
  12286. /* .reg = */ reg,
  12287. /* .context = */ ctx,
  12288. });
  12289. }
  12290. initialized = true;
  12291. }
  12292. }
  12293. GGML_ASSERT(device < devices.size());
  12294. return devices[device];
  12295. }
  12296. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  12297. /* .get_name = */ ggml_backend_vk_reg_get_name,
  12298. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  12299. /* .get_device = */ ggml_backend_vk_reg_get_device,
  12300. /* .get_proc_address = */ NULL,
  12301. };
  12302. ggml_backend_reg_t ggml_backend_vk_reg() {
  12303. static ggml_backend_reg reg = {
  12304. /* .api_version = */ GGML_BACKEND_API_VERSION,
  12305. /* .iface = */ ggml_backend_vk_reg_i,
  12306. /* .context = */ nullptr,
  12307. };
  12308. try {
  12309. ggml_vk_instance_init();
  12310. return &reg;
  12311. } catch (const vk::SystemError& e) {
  12312. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what());
  12313. return nullptr;
  12314. } catch (const std::exception &e) {
  12315. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: " << e.what());
  12316. return nullptr;
  12317. } catch (...) {
  12318. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: unknown exception during Vulkan init");
  12319. return nullptr;
  12320. }
  12321. }
  12322. // Extension availability
  12323. static bool ggml_vk_instance_layer_settings_available() {
  12324. #ifdef GGML_VULKAN_VALIDATE
  12325. // Check if validation layer provides the extension
  12326. const std::string layer_name = "VK_LAYER_KHRONOS_validation";
  12327. for (const auto& layer : vk::enumerateInstanceLayerProperties()) {
  12328. if (layer_name == layer.layerName.data()) {
  12329. for (const auto& ext : vk::enumerateInstanceExtensionProperties(layer_name)) {
  12330. if (strcmp("VK_EXT_layer_settings", ext.extensionName.data()) == 0) {
  12331. return true;
  12332. }
  12333. }
  12334. }
  12335. }
  12336. std::cerr << "ggml_vulkan: WARNING: Validation layer or layer extension VK_EXT_layer_settings not found." << std::endl;
  12337. #endif
  12338. return false;
  12339. }
  12340. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  12341. #ifdef __APPLE__
  12342. // Check for portability enumeration extension for MoltenVK support
  12343. for (const auto& properties : instance_extensions) {
  12344. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  12345. return true;
  12346. }
  12347. }
  12348. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  12349. #endif
  12350. return false;
  12351. UNUSED(instance_extensions);
  12352. }
  12353. // Extension availability
  12354. static bool ggml_vk_instance_debug_utils_ext_available(
  12355. const std::vector<vk::ExtensionProperties> & instance_extensions) {
  12356. // Check for portability enumeration extension for MoltenVK support
  12357. for (const auto & properties : instance_extensions) {
  12358. if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) {
  12359. return true;
  12360. }
  12361. }
  12362. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl;
  12363. return false;
  12364. UNUSED(instance_extensions);
  12365. }
  12366. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev) {
  12367. VkPhysicalDeviceFeatures2 device_features2;
  12368. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  12369. VkPhysicalDeviceVulkan11Features vk11_features;
  12370. vk11_features.pNext = nullptr;
  12371. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  12372. device_features2.pNext = &vk11_features;
  12373. vkGetPhysicalDeviceFeatures2(vkdev, &device_features2);
  12374. return vk11_features.storageBuffer16BitAccess;
  12375. }
  12376. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) {
  12377. switch (props.vendorID) {
  12378. case VK_VENDOR_ID_INTEL:
  12379. // Only allowing Xe2 GPU at the moment since Xe2 GPU can gain significant performance boost,
  12380. // while some older hardware (ex. Arc A770) has performance regressions
  12381. return arch == vk_device_architecture::INTEL_XE2;
  12382. case VK_VENDOR_ID_AMD:
  12383. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  12384. // Workaround for AMD proprietary driver reporting support on all GPUs
  12385. return arch == vk_device_architecture::AMD_RDNA3;
  12386. }
  12387. return true;
  12388. default:
  12389. return true;
  12390. }
  12391. }
  12392. // checks
  12393. #ifdef GGML_VULKAN_CHECK_RESULTS
  12394. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  12395. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  12396. return;
  12397. }
  12398. for (int j = 0; j < level; j++) {
  12399. std::cerr << " ";
  12400. }
  12401. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  12402. done.push_back(tensor);
  12403. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12404. if (tensor->src[i] != nullptr) {
  12405. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  12406. }
  12407. }
  12408. }
  12409. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  12410. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  12411. return;
  12412. }
  12413. i0 = std::max(i0, 5);
  12414. i1 = std::max(i1, 5);
  12415. i2 = std::max(i2, 0);
  12416. i3 = std::max(i3, 0);
  12417. fprintf(stderr, " ");
  12418. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12419. fprintf(stderr, "%7d ", idx1);
  12420. }
  12421. fprintf(stderr, "\n");
  12422. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  12423. fprintf(stderr, "%7d: ", idx0);
  12424. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12425. 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]) {
  12426. float val;
  12427. if (tensor->type == GGML_TYPE_F32) {
  12428. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12429. } else if (tensor->type == GGML_TYPE_F16) {
  12430. 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]));
  12431. } else if (tensor->type == GGML_TYPE_I32) {
  12432. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12433. } else {
  12434. GGML_ABORT("fatal error");
  12435. }
  12436. fprintf(stderr, "% 7.2f ", val);
  12437. } else {
  12438. fprintf(stderr, " ");
  12439. }
  12440. }
  12441. fprintf(stderr, "\n");
  12442. }
  12443. }
  12444. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  12445. void * tensor_data = tensor->data;
  12446. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  12447. if (is_gpu) {
  12448. const size_t tensor_size = ggml_nbytes(tensor);
  12449. tensor_data = malloc(tensor_size);
  12450. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12451. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  12452. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  12453. }
  12454. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  12455. 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;
  12456. if (tensor->src[0] != nullptr) {
  12457. 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;
  12458. }
  12459. if (tensor->src[1] != nullptr) {
  12460. 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;
  12461. }
  12462. std::cerr << std::endl << "Result:" << std::endl;
  12463. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  12464. std::cerr << std::endl;
  12465. std::vector<const ggml_tensor *> done;
  12466. ggml_vk_print_graph_origin(tensor, done);
  12467. if (is_gpu) {
  12468. free(tensor_data);
  12469. }
  12470. }
  12471. void * comp_result;
  12472. size_t comp_size;
  12473. size_t comp_nb[GGML_MAX_DIMS];
  12474. size_t check_counter = 0;
  12475. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12476. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  12477. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12478. return;
  12479. }
  12480. check_counter++;
  12481. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12482. return;
  12483. }
  12484. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  12485. struct ggml_init_params iparams = {
  12486. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  12487. /*.mem_buffer =*/ NULL,
  12488. /*.no_alloc =*/ false,
  12489. };
  12490. struct ggml_context * ggml_ctx = ggml_init(iparams);
  12491. std::array<struct ggml_tensor *, GGML_MAX_SRC> src_clone = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  12492. const char * srci_name[GGML_MAX_SRC] = {"src0", "src1", "src2", "src3", "src4", "src5", "src6", "src7", "src8", "src9"};
  12493. std::map<ggml_tensor *, ggml_tensor *> cloned_tensors;
  12494. std::vector<void *> cloned_mallocs;
  12495. struct ggml_tensor * tensor_clone = nullptr;
  12496. for (int f = 0; f < ctx->num_additional_fused_ops + 1; ++f) {
  12497. tensor = cgraph->nodes[tensor_idx + f];
  12498. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12499. ggml_tensor * srci = tensor->src[i];
  12500. if (srci == nullptr) {
  12501. continue;
  12502. }
  12503. // If a src tensor has been cloned, use that one
  12504. auto it = cloned_tensors.find(srci);
  12505. if (it != cloned_tensors.end()) {
  12506. src_clone[i] = it->second;
  12507. continue;
  12508. }
  12509. ggml_tensor * srci_clone = ggml_dup_tensor(ggml_ctx, srci);
  12510. size_t srci_size = ggml_nbytes(srci);
  12511. src_clone[i] = srci_clone;
  12512. void *src_buffer = malloc(srci_size);
  12513. cloned_mallocs.push_back(src_buffer);
  12514. srci_clone->data = src_buffer;
  12515. if (ggml_backend_buffer_is_host(srci->buffer)) {
  12516. memcpy(srci_clone->data, srci->data, srci_size);
  12517. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12518. } else if (ggml_backend_buffer_is_vk(srci->buffer)) {
  12519. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)srci->buffer->context;
  12520. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12521. uint64_t offset = vk_tensor_offset(srci) + srci->view_offs;
  12522. if (!ggml_is_contiguous(srci) && ggml_vk_dim01_contiguous(srci)) {
  12523. for (int i3 = 0; i3 < srci->ne[3]; i3++) {
  12524. for (int i2 = 0; i2 < srci->ne[2]; i2++) {
  12525. const int idx = i3*srci->ne[2] + i2;
  12526. 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]);
  12527. }
  12528. }
  12529. srci_clone->nb[0] = srci->nb[0];
  12530. srci_clone->nb[1] = srci->nb[1];
  12531. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  12532. srci_clone->nb[i] = srci_clone->nb[i - 1]*srci_clone->ne[i - 1];
  12533. }
  12534. } else {
  12535. if (offset + srci_size >= buffer_gpu->size) {
  12536. srci_size = buffer_gpu->size - offset;
  12537. }
  12538. ggml_vk_buffer_read(buffer_gpu, offset, srci_clone->data, srci_size);
  12539. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12540. }
  12541. } else {
  12542. GGML_ABORT("fatal error");
  12543. }
  12544. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12545. ggml_vk_print_tensor(srci, srci_name[i]);
  12546. }
  12547. }
  12548. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  12549. const float * params = (const float *)tensor->op_params;
  12550. 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]);
  12551. if (src_clone[4]) {
  12552. ggml_flash_attn_ext_add_sinks(tensor_clone, src_clone[4]);
  12553. }
  12554. } else if (tensor->op == GGML_OP_MUL_MAT) {
  12555. tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
  12556. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  12557. tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12558. } else if (tensor->op == GGML_OP_SUB) {
  12559. tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
  12560. } else if (tensor->op == GGML_OP_MUL) {
  12561. tensor_clone = ggml_mul(ggml_ctx, src_clone[0], src_clone[1]);
  12562. } else if (tensor->op == GGML_OP_DIV) {
  12563. tensor_clone = ggml_div(ggml_ctx, src_clone[0], src_clone[1]);
  12564. } else if (tensor->op == GGML_OP_CONCAT) {
  12565. tensor_clone = ggml_concat(ggml_ctx, src_clone[0], src_clone[1], *(int *)tensor->op_params);
  12566. } else if (tensor->op == GGML_OP_UPSCALE) {
  12567. 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]);
  12568. } else if (tensor->op == GGML_OP_SCALE) {
  12569. const float * params = (const float *)tensor->op_params;
  12570. tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]);
  12571. } else if (tensor->op == GGML_OP_ADD1) {
  12572. tensor_clone = ggml_add1(ggml_ctx, src_clone[0], src_clone[1]);
  12573. } else if (tensor->op == GGML_OP_ARANGE) {
  12574. const float start = ggml_get_op_params_f32(tensor, 0);
  12575. const float stop = ggml_get_op_params_f32(tensor, 1);
  12576. const float step = ggml_get_op_params_f32(tensor, 2);
  12577. tensor_clone = ggml_arange(ggml_ctx, start, stop, step);
  12578. } else if (tensor->op == GGML_OP_FILL) {
  12579. const float value = ggml_get_op_params_f32(tensor, 0);
  12580. tensor_clone = ggml_fill(ggml_ctx, tensor_clone, value);
  12581. } else if (tensor->op == GGML_OP_SQR) {
  12582. tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]);
  12583. } else if (tensor->op == GGML_OP_SQRT) {
  12584. tensor_clone = ggml_sqrt(ggml_ctx, src_clone[0]);
  12585. } else if (tensor->op == GGML_OP_SIN) {
  12586. tensor_clone = ggml_sin(ggml_ctx, src_clone[0]);
  12587. } else if (tensor->op == GGML_OP_COS) {
  12588. tensor_clone = ggml_cos(ggml_ctx, src_clone[0]);
  12589. } else if (tensor->op == GGML_OP_LOG) {
  12590. tensor_clone = ggml_log(ggml_ctx, src_clone[0]);
  12591. } else if (tensor->op == GGML_OP_TRI) {
  12592. tensor_clone = ggml_tri(ggml_ctx, src_clone[0], ggml_get_op_params_i32(tensor, 0));
  12593. } else if (tensor->op == GGML_OP_DIAG) {
  12594. tensor_clone = ggml_diag(ggml_ctx, src_clone[0]);
  12595. } else if (tensor->op == GGML_OP_CLAMP) {
  12596. const float * params = (const float *)tensor->op_params;
  12597. tensor_clone = ggml_clamp(ggml_ctx, src_clone[0], params[0], params[1]);
  12598. } else if (tensor->op == GGML_OP_PAD) {
  12599. 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],
  12600. tensor->op_params[4], tensor->op_params[5], tensor->op_params[6], tensor->op_params[7]);
  12601. } else if (tensor->op == GGML_OP_REPEAT) {
  12602. tensor_clone = ggml_repeat(ggml_ctx, src_clone[0], tensor);
  12603. } else if (tensor->op == GGML_OP_REPEAT_BACK) {
  12604. tensor_clone = ggml_repeat_back(ggml_ctx, src_clone[0], tensor);
  12605. } else if (tensor->op == GGML_OP_ADD) {
  12606. tensor_clone = ggml_add(ggml_ctx, src_clone[0], src_clone[1]);
  12607. } else if (tensor->op == GGML_OP_ACC) {
  12608. 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]);
  12609. } else if (tensor->op == GGML_OP_NORM) {
  12610. tensor_clone = ggml_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12611. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  12612. const float * float_params = (const float *)tensor->op_params;
  12613. tensor_clone = ggml_group_norm(ggml_ctx, src_clone[0], tensor->op_params[0], float_params[1]);
  12614. } else if (tensor->op == GGML_OP_RMS_NORM) {
  12615. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12616. } else if (tensor->op == GGML_OP_RMS_NORM_BACK) {
  12617. const float eps = ((float *) tensor->op_params)[0];
  12618. tensor_clone = ggml_rms_norm_back(ggml_ctx, src_clone[0], src_clone[1], eps);
  12619. } else if (tensor->op == GGML_OP_SILU_BACK) {
  12620. tensor_clone = ggml_silu_back(ggml_ctx, src_clone[0], src_clone[1]);
  12621. } else if (tensor->op == GGML_OP_L2_NORM) {
  12622. const float eps = ((float *) tensor->op_params)[0];
  12623. tensor_clone = ggml_l2_norm(ggml_ctx, src_clone[0], eps);
  12624. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  12625. if (tensor->src[1] != nullptr) {
  12626. const float * params = (const float *)tensor->op_params;
  12627. tensor_clone = ggml_soft_max_ext(ggml_ctx, src_clone[0], src_clone[1], params[0], params[1]);
  12628. } else {
  12629. tensor_clone = ggml_soft_max(ggml_ctx, src_clone[0]);
  12630. }
  12631. } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) {
  12632. 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]);
  12633. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  12634. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]);
  12635. } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) {
  12636. const int n_dims = ((int32_t *) tensor->op_params)[1];
  12637. const int mode = ((int32_t *) tensor->op_params)[2];
  12638. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  12639. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  12640. const float freq_base = ((float *) tensor->op_params)[5];
  12641. const float freq_scale = ((float *) tensor->op_params)[6];
  12642. const float ext_factor = ((float *) tensor->op_params)[7];
  12643. const float attn_factor = ((float *) tensor->op_params)[8];
  12644. const float beta_fast = ((float *) tensor->op_params)[9];
  12645. const float beta_slow = ((float *) tensor->op_params)[10];
  12646. if (mode & GGML_ROPE_TYPE_MROPE) {
  12647. int32_t *sections = ((int32_t *) tensor->op_params) + 11;
  12648. if (tensor->op == GGML_OP_ROPE) {
  12649. 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);
  12650. } else {
  12651. 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);
  12652. }
  12653. } else {
  12654. if (tensor->op == GGML_OP_ROPE) {
  12655. 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);
  12656. } else {
  12657. 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);
  12658. }
  12659. }
  12660. } else if (tensor->op == GGML_OP_UNARY) {
  12661. switch (ggml_get_unary_op(tensor)) {
  12662. case GGML_UNARY_OP_EXP:
  12663. tensor_clone = ggml_exp(ggml_ctx, src_clone[0]);
  12664. break;
  12665. case GGML_UNARY_OP_SILU:
  12666. tensor_clone = ggml_silu(ggml_ctx, src_clone[0]);
  12667. break;
  12668. case GGML_UNARY_OP_GELU:
  12669. tensor_clone = ggml_gelu(ggml_ctx, src_clone[0]);
  12670. break;
  12671. case GGML_UNARY_OP_GELU_ERF:
  12672. tensor_clone = ggml_gelu_erf(ggml_ctx, src_clone[0]);
  12673. break;
  12674. case GGML_UNARY_OP_GELU_QUICK:
  12675. tensor_clone = ggml_gelu_quick(ggml_ctx, src_clone[0]);
  12676. break;
  12677. case GGML_UNARY_OP_RELU:
  12678. tensor_clone = ggml_relu(ggml_ctx, src_clone[0]);
  12679. break;
  12680. case GGML_UNARY_OP_NEG:
  12681. tensor_clone = ggml_neg(ggml_ctx, src_clone[0]);
  12682. break;
  12683. case GGML_UNARY_OP_TANH:
  12684. tensor_clone = ggml_tanh(ggml_ctx, src_clone[0]);
  12685. break;
  12686. case GGML_UNARY_OP_SIGMOID:
  12687. tensor_clone = ggml_sigmoid(ggml_ctx, src_clone[0]);
  12688. break;
  12689. case GGML_UNARY_OP_HARDSIGMOID:
  12690. tensor_clone = ggml_hardsigmoid(ggml_ctx, src_clone[0]);
  12691. break;
  12692. case GGML_UNARY_OP_HARDSWISH:
  12693. tensor_clone = ggml_hardswish(ggml_ctx, src_clone[0]);
  12694. break;
  12695. case GGML_UNARY_OP_ABS:
  12696. tensor_clone = ggml_abs(ggml_ctx, src_clone[0]);
  12697. break;
  12698. case GGML_UNARY_OP_SOFTPLUS:
  12699. tensor_clone = ggml_softplus(ggml_ctx, src_clone[0]);
  12700. break;
  12701. case GGML_UNARY_OP_STEP:
  12702. tensor_clone = ggml_step(ggml_ctx, src_clone[0]);
  12703. break;
  12704. case GGML_UNARY_OP_ROUND:
  12705. tensor_clone = ggml_round(ggml_ctx, src_clone[0]);
  12706. break;
  12707. case GGML_UNARY_OP_CEIL:
  12708. tensor_clone = ggml_ceil(ggml_ctx, src_clone[0]);
  12709. break;
  12710. case GGML_UNARY_OP_FLOOR:
  12711. tensor_clone = ggml_floor(ggml_ctx, src_clone[0]);
  12712. break;
  12713. case GGML_UNARY_OP_TRUNC:
  12714. tensor_clone = ggml_trunc(ggml_ctx, src_clone[0]);
  12715. break;
  12716. default:
  12717. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12718. GGML_ABORT("fatal error");
  12719. }
  12720. } else if (tensor->op == GGML_OP_GLU) {
  12721. if (src_clone[1] == nullptr) {
  12722. tensor_clone = ggml_glu(ggml_ctx, src_clone[0], (ggml_glu_op) tensor->op_params[0], tensor->op_params[1]);
  12723. } else {
  12724. tensor_clone = ggml_glu_split(ggml_ctx, src_clone[0], src_clone[1], (ggml_glu_op) tensor->op_params[0]);
  12725. }
  12726. ggml_set_op_params_i32(tensor_clone, 2, ggml_get_op_params_i32(tensor, 2));
  12727. ggml_set_op_params_i32(tensor_clone, 3, ggml_get_op_params_i32(tensor, 3));
  12728. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  12729. if (tensor->src[1] == nullptr) {
  12730. tensor_clone = ggml_dup(ggml_ctx, src_clone[0]);
  12731. tensor_clone->type = tensor->type;
  12732. } else {
  12733. tensor_clone = ggml_cpy(ggml_ctx, src_clone[0], src_clone[1]);
  12734. }
  12735. } else if (tensor->op == GGML_OP_CONT) {
  12736. tensor_clone = ggml_cont_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12737. } else if (tensor->op == GGML_OP_RESHAPE) {
  12738. tensor_clone = ggml_reshape_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12739. } else if (tensor->op == GGML_OP_VIEW) {
  12740. 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]);
  12741. } else if (tensor->op == GGML_OP_PERMUTE) {
  12742. int32_t * params = (int32_t *)tensor->op_params;
  12743. tensor_clone = ggml_permute(ggml_ctx, src_clone[0], params[0], params[1], params[2], params[3]);
  12744. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  12745. tensor_clone = ggml_transpose(ggml_ctx, src_clone[0]);
  12746. } else if (tensor->op == GGML_OP_GET_ROWS) {
  12747. tensor_clone = ggml_get_rows(ggml_ctx, src_clone[0], src_clone[1]);
  12748. } else if (tensor->op == GGML_OP_ARGSORT) {
  12749. tensor_clone = ggml_argsort(ggml_ctx, src_clone[0], (ggml_sort_order) *(int *)tensor->op_params);
  12750. } else if (tensor->op == GGML_OP_TOP_K) {
  12751. tensor_clone = ggml_top_k(ggml_ctx, src_clone[0], tensor->ne[0]);
  12752. } else if (tensor->op == GGML_OP_SUM) {
  12753. tensor_clone = ggml_sum(ggml_ctx, src_clone[0]);
  12754. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  12755. tensor_clone = ggml_sum_rows(ggml_ctx, src_clone[0]);
  12756. } else if (tensor->op == GGML_OP_CUMSUM) {
  12757. tensor_clone = ggml_cumsum(ggml_ctx, src_clone[0]);
  12758. } else if (tensor->op == GGML_OP_MEAN) {
  12759. tensor_clone = ggml_mean(ggml_ctx, src_clone[0]);
  12760. } else if (tensor->op == GGML_OP_ARGMAX) {
  12761. tensor_clone = ggml_argmax(ggml_ctx, src_clone[0]);
  12762. } else if (tensor->op == GGML_OP_COUNT_EQUAL) {
  12763. tensor_clone = ggml_count_equal(ggml_ctx, src_clone[0], src_clone[1]);
  12764. } else if (tensor->op == GGML_OP_SOLVE_TRI) {
  12765. tensor_clone = ggml_solve_tri(ggml_ctx, src_clone[0], src_clone[1], true, true, false);
  12766. } else if (tensor->op == GGML_OP_IM2COL) {
  12767. const int32_t s0 = tensor->op_params[0];
  12768. const int32_t s1 = tensor->op_params[1];
  12769. const int32_t p0 = tensor->op_params[2];
  12770. const int32_t p1 = tensor->op_params[3];
  12771. const int32_t d0 = tensor->op_params[4];
  12772. const int32_t d1 = tensor->op_params[5];
  12773. const bool is_2D = tensor->op_params[6] == 1;
  12774. tensor_clone = ggml_im2col(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  12775. } else if (tensor->op == GGML_OP_IM2COL_3D) {
  12776. const int32_t s0 = tensor->op_params[0];
  12777. const int32_t s1 = tensor->op_params[1];
  12778. const int32_t s2 = tensor->op_params[2];
  12779. const int32_t p0 = tensor->op_params[3];
  12780. const int32_t p1 = tensor->op_params[4];
  12781. const int32_t p2 = tensor->op_params[5];
  12782. const int32_t d0 = tensor->op_params[6];
  12783. const int32_t d1 = tensor->op_params[7];
  12784. const int32_t d2 = tensor->op_params[8];
  12785. const int32_t IC = tensor->op_params[9];
  12786. 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);
  12787. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  12788. const int32_t dim = tensor->op_params[0];
  12789. const int32_t max_period = tensor->op_params[1];
  12790. tensor_clone = ggml_timestep_embedding(ggml_ctx, src_clone[0], dim, max_period);
  12791. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_1D){
  12792. const int32_t s0 = tensor->op_params[0];
  12793. const int32_t p0 = tensor->op_params[1];
  12794. const int32_t d0 = tensor->op_params[2];
  12795. tensor_clone = ggml_conv_transpose_1d(ggml_ctx, src_clone[0], src_clone[1], s0, p0, d0);
  12796. } else if (tensor->op == GGML_OP_POOL_2D) {
  12797. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  12798. const int32_t k0 = tensor->op_params[1];
  12799. const int32_t k1 = tensor->op_params[2];
  12800. const int32_t s0 = tensor->op_params[3];
  12801. const int32_t s1 = tensor->op_params[4];
  12802. const int32_t p0 = tensor->op_params[5];
  12803. const int32_t p1 = tensor->op_params[6];
  12804. tensor_clone = ggml_pool_2d(ggml_ctx, src_clone[0], op, k0, k1, s0, s1, p0, p1);
  12805. } else if (tensor->op == GGML_OP_CONV_2D) {
  12806. const int32_t s0 = tensor->op_params[0];
  12807. const int32_t s1 = tensor->op_params[1];
  12808. const int32_t p0 = tensor->op_params[2];
  12809. const int32_t p1 = tensor->op_params[3];
  12810. const int32_t d0 = tensor->op_params[4];
  12811. const int32_t d1 = tensor->op_params[5];
  12812. tensor_clone = ggml_conv_2d(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  12813. } else if (tensor->op == GGML_OP_CONV_2D_DW) {
  12814. const int32_t s0 = tensor->op_params[0];
  12815. const int32_t s1 = tensor->op_params[1];
  12816. const int32_t p0 = tensor->op_params[2];
  12817. const int32_t p1 = tensor->op_params[3];
  12818. const int32_t d0 = tensor->op_params[4];
  12819. const int32_t d1 = tensor->op_params[5];
  12820. tensor_clone = ggml_conv_2d_dw_direct(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  12821. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_2D) {
  12822. const int32_t s = tensor->op_params[0];
  12823. tensor_clone = ggml_conv_transpose_2d_p0(ggml_ctx, src_clone[0], src_clone[1], s);
  12824. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  12825. const float * op_params = (const float *)tensor->op_params;
  12826. tensor_clone = ggml_leaky_relu(ggml_ctx, src_clone[0], op_params[0], false);
  12827. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  12828. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, src_clone[0], src_clone[1],
  12829. src_clone[2], src_clone[3], src_clone[4], src_clone[5]);
  12830. } else if (tensor->op == GGML_OP_RWKV_WKV7) {
  12831. tensor_clone = ggml_rwkv_wkv7(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3],
  12832. src_clone[4], src_clone[5], src_clone[6]);
  12833. } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
  12834. src_clone[0]->flags = tensor->src[0]->flags;
  12835. tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
  12836. src_clone[2], src_clone[3], src_clone[4]);
  12837. } else if (tensor->op == GGML_OP_OPT_STEP_SGD) {
  12838. src_clone[0]->flags = tensor->src[0]->flags;
  12839. tensor_clone = ggml_opt_step_sgd(ggml_ctx, src_clone[0], src_clone[1],
  12840. src_clone[2]);
  12841. } else if (tensor->op == GGML_OP_ADD_ID) {
  12842. tensor_clone = ggml_add_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12843. } else if (tensor->op == GGML_OP_SSM_SCAN) {
  12844. tensor_clone = ggml_ssm_scan(ggml_ctx, src_clone[0], src_clone[1], src_clone[2],
  12845. src_clone[3], src_clone[4], src_clone[5], src_clone[6]);
  12846. } else if (tensor->op == GGML_OP_SSM_CONV) {
  12847. tensor_clone = ggml_ssm_conv(ggml_ctx, src_clone[0], src_clone[1]);
  12848. } else if (tensor->op == GGML_OP_ROLL) {
  12849. const int32_t s0 = tensor->op_params[0];
  12850. const int32_t s1 = tensor->op_params[1];
  12851. const int32_t s2 = tensor->op_params[2];
  12852. const int32_t s3 = tensor->op_params[3];
  12853. tensor_clone = ggml_roll(ggml_ctx, src_clone[0], s0, s1, s2, s3);
  12854. }
  12855. else {
  12856. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12857. GGML_ABORT("fatal error");
  12858. }
  12859. cloned_tensors[tensor] = tensor_clone;
  12860. }
  12861. ggml_cgraph * cgraph_cpu = ggml_new_graph(ggml_ctx);
  12862. ggml_build_forward_expand(cgraph_cpu, tensor_clone);
  12863. ggml_graph_compute_with_ctx(ggml_ctx, cgraph_cpu, 8);
  12864. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12865. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  12866. }
  12867. comp_size = ggml_nbytes(tensor_clone);
  12868. comp_result = malloc(comp_size);
  12869. memcpy(comp_result, tensor_clone->data, comp_size);
  12870. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12871. for (auto m : cloned_mallocs) {
  12872. free(m);
  12873. }
  12874. ggml_free(ggml_ctx);
  12875. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  12876. }
  12877. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12878. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  12879. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12880. return;
  12881. }
  12882. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12883. return;
  12884. }
  12885. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  12886. ggml_tensor * src0 = tensor->src[0];
  12887. ggml_tensor * src1 = tensor->src[1];
  12888. ggml_tensor * src2 = tensor->src[2];
  12889. ggml_tensor * src3 = tensor->src[3];
  12890. void * tensor_data = tensor->data;
  12891. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  12892. size_t tensor_size = ggml_nbytes(tensor);
  12893. tensor_data = malloc(tensor_size);
  12894. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12895. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12896. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  12897. if (offset + tensor_size >= buffer_gpu->size) {
  12898. tensor_size = buffer_gpu->size - offset;
  12899. }
  12900. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  12901. }
  12902. float first_error_result = -1.0f;
  12903. float first_error_correct = -1.0f;
  12904. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  12905. double avg_err = 0.0;
  12906. size_t counter = 0;
  12907. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  12908. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  12909. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  12910. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  12911. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  12912. float correct = 0.0f;
  12913. float result = 0.0f;
  12914. if (buffer_size_fit) {
  12915. if (tensor->type == GGML_TYPE_F32) {
  12916. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12917. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12918. } else if (tensor->type == GGML_TYPE_F16) {
  12919. 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]));
  12920. 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]));
  12921. } else if (tensor->type == GGML_TYPE_BF16) {
  12922. 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]));
  12923. 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]));
  12924. } else if (tensor->type == GGML_TYPE_I32) {
  12925. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12926. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12927. } else if (tensor->type == GGML_TYPE_I64) {
  12928. correct = *(int64_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12929. result = *(int64_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12930. } else {
  12931. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  12932. }
  12933. } else {
  12934. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  12935. GGML_ABORT("fatal error");
  12936. }
  12937. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  12938. 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;
  12939. 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;
  12940. if (src0 != nullptr) {
  12941. 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;
  12942. }
  12943. if (src1 != nullptr) {
  12944. 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;
  12945. }
  12946. if (src2 != nullptr) {
  12947. 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;
  12948. }
  12949. if (src3 != nullptr) {
  12950. 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;
  12951. }
  12952. 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;
  12953. std::cerr << std::endl << "Result:" << std::endl;
  12954. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  12955. std::cerr << std::endl << "Correct:" << std::endl;
  12956. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  12957. std::cerr << std::endl;
  12958. std::vector<const ggml_tensor *> done;
  12959. ggml_vk_print_graph_origin(tensor, done);
  12960. GGML_ABORT("fatal error");
  12961. }
  12962. const double denom = std::fabs(correct) > 1.0f ? (std::fabs(correct) > 1e-8 ? std::fabs(correct) : 1e-8) : 1.0f;
  12963. if (first_error[0] == -1 && std::fabs(correct - result) / denom > 0.5) {
  12964. first_error[0] = i0;
  12965. first_error[1] = i1;
  12966. first_error[2] = i2;
  12967. first_error[3] = i3;
  12968. first_error_result = result;
  12969. first_error_correct = correct;
  12970. }
  12971. // Special case, value is infinite, avoid NaN result in avg_err
  12972. // NaN also appears in results, if both are nan error is 0
  12973. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  12974. avg_err += std::fabs(correct - result) / denom;
  12975. }
  12976. counter++;
  12977. }
  12978. }
  12979. }
  12980. }
  12981. avg_err /= counter;
  12982. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12983. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  12984. 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;
  12985. if (src0 != nullptr) {
  12986. 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;
  12987. }
  12988. if (src1 != nullptr) {
  12989. 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;
  12990. }
  12991. if (src2 != nullptr) {
  12992. 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;
  12993. }
  12994. if (src3 != nullptr) {
  12995. 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;
  12996. }
  12997. 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;
  12998. std::cerr << std::endl << "Result:" << std::endl;
  12999. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  13000. std::cerr << std::endl << "Correct:" << std::endl;
  13001. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  13002. std::cerr << std::endl;
  13003. std::vector<const ggml_tensor *> done;
  13004. ggml_vk_print_graph_origin(tensor, done);
  13005. }
  13006. if (avg_err > 0.5 || std::isnan(avg_err)) {
  13007. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  13008. 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;
  13009. if (src0 != nullptr) {
  13010. 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;
  13011. }
  13012. if (src1 != nullptr) {
  13013. 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;
  13014. }
  13015. if (src2 != nullptr) {
  13016. 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;
  13017. }
  13018. if (src3 != nullptr) {
  13019. 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;
  13020. }
  13021. 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;
  13022. std::cerr << std::endl << "Result:" << std::endl;
  13023. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  13024. std::cerr << std::endl << "Correct:" << std::endl;
  13025. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  13026. std::cerr << std::endl;
  13027. std::vector<const ggml_tensor *> done;
  13028. ggml_vk_print_graph_origin(tensor, done);
  13029. GGML_ABORT("fatal error");
  13030. } else {
  13031. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  13032. }
  13033. free(comp_result);
  13034. comp_result = nullptr;
  13035. comp_size = 0;
  13036. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  13037. free(tensor_data);
  13038. }
  13039. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  13040. }
  13041. #endif
  13042. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)