ggml-vulkan.cpp 724 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603
  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 <unordered_map>
  33. #include <memory>
  34. #include <mutex>
  35. #include <future>
  36. #include <thread>
  37. #if defined(_MSC_VER)
  38. # define NOMINMAX 1
  39. # include <windows.h>
  40. # define YIELD() YieldProcessor()
  41. #elif defined(__clang__) || defined(__GNUC__)
  42. # if defined(__x86_64__) ||defined(__i386__)
  43. # include <immintrin.h>
  44. # define YIELD() _mm_pause()
  45. # elif defined(__arm__) || defined(__aarch64__)
  46. # if defined(__clang__)
  47. # include <arm_acle.h>
  48. # define YIELD() __yield()
  49. # else
  50. # define YIELD() asm volatile("yield")
  51. # endif
  52. # endif
  53. #endif
  54. #if !defined(YIELD)
  55. #define YIELD()
  56. #endif
  57. #include "ggml-impl.h"
  58. #include "ggml-backend-impl.h"
  59. #include "ggml-vulkan-shaders.hpp"
  60. // remove this once it's more widely available in the SDK
  61. #if !defined(VK_KHR_shader_bfloat16)
  62. #define VK_KHR_shader_bfloat16 1
  63. #define VK_KHR_SHADER_BFLOAT16_SPEC_VERSION 1
  64. #define VK_KHR_SHADER_BFLOAT16_EXTENSION_NAME "VK_KHR_shader_bfloat16"
  65. #define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR ((VkStructureType)1000141000)
  66. #define VK_COMPONENT_TYPE_BFLOAT16_KHR ((VkComponentTypeKHR)1000141000)
  67. typedef struct VkPhysicalDeviceShaderBfloat16FeaturesKHR {
  68. VkStructureType sType;
  69. void* pNext;
  70. VkBool32 shaderBFloat16Type;
  71. VkBool32 shaderBFloat16DotProduct;
  72. VkBool32 shaderBFloat16CooperativeMatrix;
  73. } VkPhysicalDeviceShaderBfloat16FeaturesKHR;
  74. #endif
  75. #define ROUNDUP_POW2(M, N) (((M) + (N) - 1) & ~((N) - 1))
  76. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  77. static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; }
  78. #define VK_VENDOR_ID_AMD 0x1002
  79. #define VK_VENDOR_ID_APPLE 0x106b
  80. #define VK_VENDOR_ID_INTEL 0x8086
  81. #define VK_VENDOR_ID_NVIDIA 0x10de
  82. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 256
  83. #define GGML_VK_MAX_NODES 8192
  84. #define VK_CHECK(err, msg) \
  85. do { \
  86. vk::Result err_ = (err); \
  87. if (err_ != vk::Result::eSuccess) { \
  88. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  89. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  90. exit(1); \
  91. } \
  92. } while (0)
  93. #ifdef GGML_VULKAN_DEBUG
  94. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  95. #else
  96. #define VK_LOG_DEBUG(msg) ((void) 0)
  97. #endif // GGML_VULKAN_DEBUG
  98. struct ggml_backend_vk_context;
  99. #define MAX_PARAMETER_COUNT 12
  100. // Max number of adds that can be fused without exceeding MAX_PARAMETER_COUNT.
  101. #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3)
  102. struct vk_pipeline_struct {
  103. std::string name;
  104. vk::ShaderModule shader_module;
  105. vk::PipelineLayout layout;
  106. vk::Pipeline pipeline;
  107. uint32_t push_constant_size;
  108. uint32_t parameter_count;
  109. std::array<uint32_t, 3> wg_denoms;
  110. uint32_t align;
  111. // true if fields have been set by ggml_vk_create_pipeline
  112. bool initialized {};
  113. // set to true to request the pipeline is compiled
  114. std::atomic<bool> needed {};
  115. // set to true when the shader has been compiled
  116. std::atomic<bool> compiled {};
  117. // number of registers used, extracted from pipeline executable properties
  118. uint32_t register_count {};
  119. };
  120. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  121. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  122. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  123. struct vk_matmul_pipeline_struct {
  124. vk_pipeline l, m, s;
  125. vk_pipeline a_l, a_m, a_s;
  126. // Returns true when all unaligned pipelines are null.
  127. // We only check for unaligned variants since one of the unaligned pipelines must exist
  128. // while aligned pipelines are optional
  129. bool is_empty() const {
  130. return l == nullptr && m == nullptr && s == nullptr;
  131. }
  132. };
  133. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  134. struct vk_matmul_pipeline2 {
  135. vk_matmul_pipeline2() {
  136. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  137. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  138. }
  139. vk_matmul_pipeline f32acc;
  140. vk_matmul_pipeline f16acc;
  141. };
  142. struct vk_device_struct;
  143. typedef std::shared_ptr<vk_device_struct> vk_device;
  144. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  145. struct vk_buffer_struct;
  146. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  147. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  148. struct ggml_backend_vk_buffer_type_context {
  149. std::string name;
  150. vk_device device;
  151. };
  152. struct vk_queue;
  153. // Stores command pool/buffers. There's an instance of this
  154. // for each (context,queue) pair and for each (device,queue) pair.
  155. struct vk_command_pool {
  156. void init(vk_device& device, vk_queue *q_);
  157. void destroy(vk::Device& device);
  158. vk::CommandPool pool;
  159. uint32_t cmd_buffer_idx;
  160. std::vector<vk::CommandBuffer> cmd_buffers;
  161. vk_queue *q;
  162. };
  163. // Prevent simultaneous submissions to the same queue.
  164. // This could be per vk_queue if we stopped having two vk_queue structures
  165. // sharing the same vk::Queue.
  166. static std::mutex queue_mutex;
  167. struct vk_queue {
  168. uint32_t queue_family_index;
  169. vk::Queue queue;
  170. vk_command_pool cmd_pool;
  171. vk::PipelineStageFlags stage_flags;
  172. bool transfer_only;
  173. // copy everything except the cmd_pool
  174. void copyFrom(vk_queue &other) {
  175. queue_family_index = other.queue_family_index;
  176. queue = other.queue;
  177. stage_flags = other.stage_flags;
  178. transfer_only = other.transfer_only;
  179. }
  180. };
  181. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  182. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  183. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  184. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  185. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  186. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  187. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  188. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  189. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  190. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  191. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  192. /* .is_host = */ NULL,
  193. };
  194. #ifdef GGML_VULKAN_MEMORY_DEBUG
  195. class vk_memory_logger;
  196. #endif
  197. class vk_perf_logger;
  198. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  199. static constexpr uint32_t mul_mat_vec_max_cols = 8;
  200. static constexpr uint32_t p021_max_gqa_ratio = 8;
  201. enum vk_device_architecture {
  202. OTHER,
  203. AMD_GCN,
  204. AMD_RDNA1,
  205. AMD_RDNA2,
  206. AMD_RDNA3,
  207. INTEL_XE2,
  208. NVIDIA_PRE_TURING,
  209. };
  210. static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) {
  211. vk::PhysicalDeviceProperties props = device.getProperties();
  212. if (props.vendorID == VK_VENDOR_ID_AMD) {
  213. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  214. bool amd_shader_core_properties = false;
  215. bool integer_dot_product = false;
  216. bool subgroup_size_control = false;
  217. for (const auto& properties : ext_props) {
  218. if (strcmp("VK_AMD_shader_core_properties", properties.extensionName) == 0) {
  219. amd_shader_core_properties = true;
  220. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0) {
  221. integer_dot_product = true;
  222. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  223. subgroup_size_control = true;
  224. }
  225. }
  226. if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) {
  227. return vk_device_architecture::OTHER;
  228. }
  229. vk::PhysicalDeviceProperties2 props2;
  230. vk::PhysicalDeviceShaderCorePropertiesAMD shader_core_props_amd;
  231. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR integer_dot_props;
  232. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  233. props2.pNext = &shader_core_props_amd;
  234. shader_core_props_amd.pNext = &integer_dot_props;
  235. integer_dot_props.pNext = &subgroup_size_control_props;
  236. device.getProperties2(&props2);
  237. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 64) {
  238. return vk_device_architecture::AMD_GCN;
  239. }
  240. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 32) {
  241. // RDNA
  242. if (shader_core_props_amd.wavefrontsPerSimd == 20) {
  243. return vk_device_architecture::AMD_RDNA1;
  244. }
  245. if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
  246. return vk_device_architecture::AMD_RDNA3;
  247. }
  248. return vk_device_architecture::AMD_RDNA2;
  249. }
  250. } else if (props.vendorID == VK_VENDOR_ID_INTEL) {
  251. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  252. bool subgroup_size_control = false;
  253. for (const auto& properties : ext_props) {
  254. if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  255. subgroup_size_control = true;
  256. }
  257. }
  258. if (!subgroup_size_control) {
  259. return vk_device_architecture::OTHER;
  260. }
  261. vk::PhysicalDeviceProperties2 props2;
  262. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  263. props2.pNext = &subgroup_size_control_props;
  264. device.getProperties2(&props2);
  265. if (subgroup_size_control_props.minSubgroupSize == 16) {
  266. // Xe2 architecture uses SIMD16 while previous Xe and Gen architecture uses SIMD8.
  267. // Minimum subgroup size matches the SIMD width so we distinguish architecture by checking this value.
  268. // https://www.intel.com/content/www/us/en/content-details/824434/2024-intel-tech-tour-xe2-and-lunar-lake-s-gpu.html
  269. // https://www.intel.com/content/www/us/en/docs/oneapi/optimization-guide-gpu/2025-0/intel-xe-gpu-architecture.html
  270. return vk_device_architecture::INTEL_XE2;
  271. }
  272. } else if (props.vendorID == VK_VENDOR_ID_NVIDIA) {
  273. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  274. bool cooperative_matrix = false;
  275. // Detect "pre-turing" based on lack of coopmat support.
  276. for (const auto& properties : ext_props) {
  277. if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0) {
  278. cooperative_matrix = true;
  279. break;
  280. }
  281. }
  282. if (!cooperative_matrix) {
  283. return vk_device_architecture::NVIDIA_PRE_TURING;
  284. }
  285. }
  286. return vk_device_architecture::OTHER;
  287. }
  288. enum vk_conv_shapes {
  289. CONV_SHAPE_128x128,
  290. CONV_SHAPE_64x32,
  291. CONV_SHAPE_32x256,
  292. CONV_SHAPE_COUNT,
  293. };
  294. uint32_t conv_shapes_wg_denoms[][3] = {
  295. { 128, 128, 1 },
  296. { 64, 32, 1 },
  297. { 32, 256, 1 },
  298. };
  299. enum dmmv_wg_sizes {
  300. DMMV_WG_SIZE_SUBGROUP,
  301. DMMV_WG_SIZE_LARGE,
  302. DMMV_WG_SIZE_COUNT,
  303. };
  304. enum FaCodePath {
  305. FA_SCALAR,
  306. FA_COOPMAT1,
  307. FA_COOPMAT2,
  308. };
  309. struct vk_fa_pipeline_state {
  310. vk_fa_pipeline_state(uint32_t HSK, uint32_t HSV, bool small_rows, FaCodePath path, bool aligned, bool f32acc)
  311. : HSK(HSK), HSV(HSV), small_rows(small_rows), path(path), aligned(aligned), f32acc(f32acc) {}
  312. uint32_t HSK, HSV;
  313. bool small_rows;
  314. FaCodePath path;
  315. bool aligned;
  316. bool f32acc;
  317. bool operator<(const vk_fa_pipeline_state &b) const {
  318. return std::tie(HSK, HSV, small_rows, path, aligned, f32acc) <
  319. std::tie(b.HSK, b.HSV, b.small_rows, b.path, b.aligned, b.f32acc);
  320. }
  321. };
  322. struct vk_conv2d_pipeline_state {
  323. 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)
  324. : s0(s0), s1(s1), p0(p0), p1(p1), d0(d0), d1(d1), KW(KW), KH(KH) {}
  325. uint32_t s0, s1, p0, p1, d0, d1, KW, KH;
  326. bool operator<(const vk_conv2d_pipeline_state &b) const {
  327. return std::tie(s0, s1, p0, p1, d0, d1, KW, KH) <
  328. std::tie(b.s0, b.s1, b.p0, b.p1, b.d0, b.d1, b.KW, b.KH);
  329. }
  330. };
  331. enum shader_reduction_mode {
  332. SHADER_REDUCTION_MODE_SHMEM,
  333. SHADER_REDUCTION_MODE_HYBRID,
  334. SHADER_REDUCTION_MODE_SUBGROUP,
  335. SHADER_REDUCTION_MODE_COUNT,
  336. };
  337. static constexpr uint32_t num_argsort_pipelines = 11;
  338. static constexpr uint32_t max_argsort_cols = 1 << (num_argsort_pipelines-1);
  339. static constexpr uint32_t num_topk_moe_pipelines = 10;
  340. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax_norm{ GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  341. GGML_OP_VIEW, GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  342. GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV,
  343. GGML_OP_RESHAPE };
  344. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax { GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  345. GGML_OP_VIEW, GGML_OP_GET_ROWS };
  346. static constexpr std::initializer_list<ggml_op> topk_moe_late_softmax { GGML_OP_ARGSORT, GGML_OP_VIEW,
  347. GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  348. GGML_OP_SOFT_MAX, GGML_OP_RESHAPE };
  349. //node #978 ( SOFT_MAX): ffn_moe_probs-15 ( 0K) [Vulka ] use=2: ffn_moe_logits-15 ( 0K) [Vulka ]
  350. //node #979 ( RESHAPE): ffn_moe_probs-15 (re ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  351. //node #980 ( ARGSORT): ffn_moe_argsort-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  352. //node #981 ( VIEW): ffn_moe_topk-15 ( 0K) [Vulka ] use=4: ffn_moe_argsort-15 ( 0K) [Vulka ]
  353. //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 ]
  354. //node #983 ( RESHAPE): ffn_moe_weights-15 ( ( 0K) [Vulka ] use=2: ffn_moe_weights-15 ( 0K) [Vulka ]
  355. //node #984 ( SUM_ROWS): ffn_moe_weights_sum- ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ]
  356. //node #985 ( CLAMP): ffn_moe_weights_sum_ ( 0K) [Vulka ] use=1: ffn_moe_weights_sum- ( 0K) [Vulka ]
  357. //node #986 ( DIV): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ] ffn_moe_weights_sum_ ( 0K) [Vulka ]
  358. //node #987 ( RESHAPE): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights_norm ( 0K) [Vulka ]
  359. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_norm_edges {
  360. { 1, 0, 0 }, // reshape->src[0] == softmax
  361. { 2, 0, 0 }, // argsort->src[0] == softmax
  362. { 3, 0, 2 }, // view->src[0] == argsort
  363. { 4, 0, 1 }, // get_rows->src[0] == reshape
  364. { 4, 1, 3 }, // get_rows->src[1] == view
  365. { 5, 0, 4 }, // reshape->src[0] == get_rows
  366. { 6, 0, 5 }, // sum_rows->src[0] == reshape
  367. { 7, 0, 6 }, // clamp->src[0] == sum_rows
  368. { 8, 0, 5 }, // div->src[0] == reshape
  369. { 8, 1, 7 }, // div->src[1] == clamp
  370. { 9, 0, 8 }, // reshape->src[0] == div
  371. };
  372. // same as early_softmax_norm but ending after the get_rows
  373. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_edges {
  374. { 1, 0, 0 }, // reshape->src[0] == softmax
  375. { 2, 0, 0 }, // argsort->src[0] == softmax
  376. { 3, 0, 2 }, // view->src[0] == argsort
  377. { 4, 0, 1 }, // get_rows->src[0] == reshape
  378. { 4, 1, 3 }, // get_rows->src[1] == view
  379. };
  380. //node #652 ( ARGSORT): ffn_moe_argsort-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 ( 0K) [Vulka ]
  381. //node #653 ( VIEW): ffn_moe_topk-11 ( 0K) [Vulka ] use=7: ffn_moe_argsort-11 ( 0K) [Vulka ]
  382. //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 ]
  383. //node #655 ( RESHAPE): ffn_moe_weights-11 ( ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( 0K) [Vulka ]
  384. //node #656 ( SOFT_MAX): node_656 ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( ( 0K) [Vulka ]
  385. //node #657 ( RESHAPE): ffn_moe_weights_soft ( 0K) [Vulka ] use=1: node_656 ( 0K) [Vulka ]
  386. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_late_softmax_edges {
  387. { 1, 0, 0 }, // view->src[0] == argsort
  388. { 2, 1, 1 }, // get_rows->src[1] == view
  389. { 3, 0, 2 }, // reshape->src[0] == get_rows
  390. { 4, 0, 3 }, // soft_max->src[0] == reshape
  391. { 5, 0, 4 }, // reshape->src[0] == soft_max
  392. };
  393. enum topk_moe_mode {
  394. TOPK_MOE_EARLY_SOFTMAX,
  395. TOPK_MOE_EARLY_SOFTMAX_NORM,
  396. TOPK_MOE_LATE_SOFTMAX,
  397. TOPK_MOE_COUNT,
  398. };
  399. static topk_moe_mode ggml_vk_num_additional_ops_to_topk_moe_mode(uint32_t num) {
  400. topk_moe_mode mode = num == topk_moe_early_softmax_norm.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX_NORM :
  401. num == topk_moe_early_softmax.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX :
  402. TOPK_MOE_LATE_SOFTMAX;
  403. return mode;
  404. }
  405. static constexpr std::initializer_list<std::array<int, 3>> rope_view_set_rows_edges {
  406. { 1, 0, 0 }, // view->src[0] == rope
  407. { 2, 0, 1 }, // set_rows->src[0] == view
  408. };
  409. static constexpr std::initializer_list<std::array<int, 3>> rms_norm_mul_rope_view_set_rows_edges {
  410. { 1, 0, 0 }, // mul->src[0] == rms
  411. { 2, 0, 1 }, // rope->src[0] == mul
  412. { 3, 0, 2 }, // view->src[0] == rope
  413. { 4, 0, 3 }, // set_rows->src[0] == view
  414. };
  415. struct vk_device_struct {
  416. std::recursive_mutex mutex;
  417. vk::PhysicalDevice physical_device;
  418. vk::PhysicalDeviceProperties properties;
  419. std::string name;
  420. uint64_t max_memory_allocation_size;
  421. uint64_t max_buffer_size;
  422. uint64_t suballocation_block_size;
  423. bool fp16;
  424. bool bf16;
  425. bool pipeline_robustness;
  426. vk::Device device;
  427. uint32_t vendor_id;
  428. vk::DriverId driver_id;
  429. vk_device_architecture architecture;
  430. vk_queue compute_queue;
  431. vk_queue transfer_queue;
  432. bool single_queue;
  433. uint32_t subgroup_size;
  434. uint32_t shader_core_count;
  435. bool uma;
  436. bool prefer_host_memory;
  437. bool float_controls_rte_fp16;
  438. bool subgroup_arithmetic;
  439. bool subgroup_shuffle;
  440. bool subgroup_ballot;
  441. bool subgroup_clustered;
  442. bool multi_add;
  443. bool shader_int64;
  444. bool buffer_device_address;
  445. bool add_rms_fusion;
  446. uint32_t partials_binding_alignment;
  447. bool integer_dot_product;
  448. // 0: default, 1: force mmvq, -1: disable mmvq
  449. int32_t mmvq_mode;
  450. bool subgroup_size_control;
  451. uint32_t subgroup_min_size;
  452. uint32_t subgroup_max_size;
  453. bool subgroup_require_full_support;
  454. bool coopmat_support;
  455. bool coopmat_acc_f32_support {};
  456. bool coopmat_acc_f16_support {};
  457. bool coopmat_bf16_support {};
  458. bool coopmat_support_16x16x16_f16acc {};
  459. bool coopmat_support_16x16x16_f32acc {};
  460. bool coopmat1_fa_support {};
  461. uint32_t coopmat_m;
  462. uint32_t coopmat_n;
  463. uint32_t coopmat_k;
  464. bool coopmat_int_support;
  465. uint32_t coopmat_int_m;
  466. uint32_t coopmat_int_n;
  467. uint32_t coopmat_int_k;
  468. bool coopmat2;
  469. bool pipeline_executable_properties_support {};
  470. size_t idx;
  471. bool mul_mat_l[GGML_TYPE_COUNT];
  472. bool mul_mat_m[GGML_TYPE_COUNT];
  473. bool mul_mat_s[GGML_TYPE_COUNT];
  474. bool mul_mat_id_l[GGML_TYPE_COUNT];
  475. bool mul_mat_id_m[GGML_TYPE_COUNT];
  476. bool mul_mat_id_s[GGML_TYPE_COUNT];
  477. vk::DescriptorSetLayout dsl;
  478. vk_matmul_pipeline pipeline_matmul_f32 {};
  479. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  480. vk_matmul_pipeline pipeline_matmul_bf16 {};
  481. vk_matmul_pipeline2 pipeline_matmul_f16;
  482. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  483. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  484. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  485. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_COUNT];
  486. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  487. vk_matmul_pipeline pipeline_matmul_id_bf16 {};
  488. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  489. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  490. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  491. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_COUNT];
  492. vk_pipeline pipeline_matmul_split_k_reduce;
  493. vk_pipeline pipeline_quantize_q8_1_x4;
  494. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  495. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  496. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  497. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_COUNT];
  498. vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  499. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio];
  500. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  501. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  502. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  503. vk_pipeline pipeline_acc_f32;
  504. // [src0 0=fp32,1=fp16][src1 0=fp32,1=fp16][dst 0=fp32,1=fp16]
  505. vk_pipeline pipeline_add[2][2][2];
  506. vk_pipeline pipeline_add_norepeat[2][2][2];
  507. vk_pipeline pipeline_sub[2][2][2];
  508. vk_pipeline pipeline_sub_norepeat[2][2][2];
  509. vk_pipeline pipeline_mul[2][2][2];
  510. vk_pipeline pipeline_mul_norepeat[2][2][2];
  511. vk_pipeline pipeline_div[2][2][2];
  512. vk_pipeline pipeline_div_norepeat[2][2][2];
  513. vk_pipeline pipeline_add_rms[2][2][2];
  514. vk_pipeline pipeline_add_rms_norepeat[2][2][2];
  515. // indexed by num_additional_fused_ops == num_adds - 1
  516. vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS];
  517. vk_pipeline pipeline_multi_add_rms[MAX_FUSED_ADDS];
  518. vk_pipeline pipeline_add_id_f32;
  519. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  520. vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32;
  521. vk_pipeline pipeline_scale_f32;
  522. vk_pipeline pipeline_sqr_f32;
  523. vk_pipeline pipeline_sqrt_f32;
  524. vk_pipeline pipeline_sin_f32;
  525. vk_pipeline pipeline_cos_f32;
  526. vk_pipeline pipeline_clamp_f32;
  527. vk_pipeline pipeline_pad_f32;
  528. vk_pipeline pipeline_roll_f32;
  529. vk_pipeline pipeline_repeat_f32, pipeline_repeat_back_f32;
  530. 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;
  531. 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;
  532. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  533. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  534. vk_pipeline pipeline_set_rows_i32[GGML_TYPE_COUNT];
  535. vk_pipeline pipeline_set_rows_i64[GGML_TYPE_COUNT];
  536. vk_pipeline pipeline_norm_f32;
  537. vk_pipeline pipeline_group_norm_f32;
  538. vk_pipeline pipeline_rms_norm_f32;
  539. vk_pipeline pipeline_rms_norm_mul_f32;
  540. vk_pipeline pipeline_rms_norm_partials_f32;
  541. vk_pipeline pipeline_rms_norm_mul_partials_f32;
  542. vk_pipeline pipeline_rms_norm_mul_rope_f32_f32;
  543. vk_pipeline pipeline_rms_norm_mul_rope_f32_f16;
  544. vk_pipeline pipeline_rms_norm_back_f32;
  545. vk_pipeline pipeline_l2_norm_f32;
  546. // [src/dst 0=fp32,1=fp16]
  547. vk_pipeline pipeline_exp[2];
  548. vk_pipeline pipeline_gelu[2];
  549. vk_pipeline pipeline_gelu_erf[2];
  550. vk_pipeline pipeline_gelu_quick[2];
  551. vk_pipeline pipeline_silu[2];
  552. vk_pipeline pipeline_relu[2];
  553. vk_pipeline pipeline_tanh[2];
  554. vk_pipeline pipeline_sigmoid[2];
  555. vk_pipeline pipeline_hardsigmoid[2];
  556. vk_pipeline pipeline_hardswish[2];
  557. vk_pipeline pipeline_geglu[2];
  558. vk_pipeline pipeline_reglu[2];
  559. vk_pipeline pipeline_swiglu[2];
  560. vk_pipeline pipeline_swiglu_oai[2];
  561. vk_pipeline pipeline_geglu_erf[2];
  562. vk_pipeline pipeline_geglu_quick[2];
  563. vk_pipeline pipeline_leaky_relu_f32;
  564. vk_pipeline pipeline_silu_back_f32;
  565. vk_pipeline pipeline_diag_mask_inf_f32;
  566. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  567. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  568. vk_pipeline pipeline_soft_max_back_f32;
  569. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16, pipeline_rope_norm_f32_f16;
  570. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16, pipeline_rope_neox_f32_f16;
  571. vk_pipeline pipeline_rope_multi_f32, pipeline_rope_multi_f16;
  572. vk_pipeline pipeline_rope_vision_f32, pipeline_rope_vision_f16;
  573. vk_pipeline pipeline_argsort_f32[num_argsort_pipelines];
  574. vk_pipeline pipeline_sum_rows_f32;
  575. vk_pipeline pipeline_argmax_f32;
  576. vk_pipeline pipeline_count_equal_i32;
  577. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  578. vk_pipeline pipeline_im2col_3d_f32, pipeline_im2col_3d_f32_f16;
  579. vk_pipeline pipeline_timestep_embedding_f32;
  580. vk_pipeline pipeline_conv_transpose_1d_f32;
  581. vk_pipeline pipeline_pool2d_f32;
  582. vk_pipeline pipeline_rwkv_wkv6_f32;
  583. vk_pipeline pipeline_rwkv_wkv7_f32;
  584. vk_pipeline pipeline_ssm_scan_f32_d128;
  585. vk_pipeline pipeline_ssm_scan_f32_d256;
  586. vk_pipeline pipeline_ssm_conv_f32;
  587. vk_pipeline pipeline_opt_step_adamw_f32;
  588. vk_pipeline pipeline_opt_step_sgd_f32;
  589. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f32[CONV_SHAPE_COUNT];
  590. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f16_f32[CONV_SHAPE_COUNT];
  591. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f32[CONV_SHAPE_COUNT];
  592. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f16_f32[CONV_SHAPE_COUNT];
  593. vk_pipeline pipeline_conv2d_dw_whcn_f32, pipeline_conv2d_dw_whcn_f16_f32;
  594. vk_pipeline pipeline_conv2d_dw_cwhn_f32, pipeline_conv2d_dw_cwhn_f16_f32;
  595. std::map<vk_fa_pipeline_state, vk_pipeline> pipeline_flash_attn_f32_f16[GGML_TYPE_COUNT];
  596. vk_pipeline pipeline_flash_attn_split_k_reduce;
  597. vk_pipeline pipeline_topk_moe[num_topk_moe_pipelines][TOPK_MOE_COUNT];
  598. std::vector<vk_pipeline_ref> all_pipelines;
  599. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  600. vk::Fence fence;
  601. vk_buffer sync_staging;
  602. ggml_backend_buffer_type buffer_type;
  603. bool disable_fusion;
  604. bool disable_host_visible_vidmem;
  605. bool allow_sysmem_fallback;
  606. bool disable_graph_optimize;
  607. #ifdef GGML_VULKAN_MEMORY_DEBUG
  608. std::unique_ptr<vk_memory_logger> memory_logger;
  609. #endif
  610. // for GGML_VK_PERF_LOGGER
  611. std::unique_ptr<vk_perf_logger> perf_logger;
  612. vk::QueryPool query_pool;
  613. int32_t num_queries;
  614. ~vk_device_struct() {
  615. VK_LOG_DEBUG("destroy device " << name);
  616. device.destroyFence(fence);
  617. ggml_vk_destroy_buffer(sync_staging);
  618. compute_queue.cmd_pool.destroy(device);
  619. transfer_queue.cmd_pool.destroy(device);
  620. for (auto& pipeline : all_pipelines) {
  621. if (pipeline.expired()) {
  622. continue;
  623. }
  624. vk_pipeline pl = pipeline.lock();
  625. ggml_vk_destroy_pipeline(device, pl);
  626. }
  627. all_pipelines.clear();
  628. device.destroyDescriptorSetLayout(dsl);
  629. device.destroy();
  630. }
  631. };
  632. void vk_command_pool::init(vk_device& device, vk_queue *q_) {
  633. cmd_buffer_idx = 0;
  634. q = q_;
  635. vk::CommandPoolCreateInfo command_pool_create_info(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), q->queue_family_index);
  636. pool = device->device.createCommandPool(command_pool_create_info);
  637. }
  638. void vk_command_pool::destroy(vk::Device& device) {
  639. device.destroyCommandPool(pool);
  640. pool = nullptr;
  641. cmd_buffers.clear();
  642. }
  643. struct vk_buffer_struct {
  644. vk::Buffer buffer = VK_NULL_HANDLE;
  645. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  646. vk::MemoryPropertyFlags memory_property_flags;
  647. void * ptr;
  648. size_t size = 0;
  649. vk::DeviceAddress bda_addr {};
  650. vk_device device;
  651. ~vk_buffer_struct() {
  652. if (size == 0) {
  653. return;
  654. }
  655. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  656. device->device.freeMemory(device_memory);
  657. device->device.destroyBuffer(buffer);
  658. }
  659. };
  660. struct vk_subbuffer {
  661. vk_buffer buffer;
  662. uint64_t offset;
  663. uint64_t size;
  664. operator vk::DescriptorBufferInfo() const {
  665. return { buffer->buffer, offset, size };
  666. }
  667. };
  668. struct vk_semaphore {
  669. vk::Semaphore s;
  670. uint64_t value;
  671. };
  672. struct vk_submission {
  673. vk::CommandBuffer buffer;
  674. std::vector<vk_semaphore> wait_semaphores;
  675. std::vector<vk_semaphore> signal_semaphores;
  676. };
  677. typedef std::vector<vk_submission> vk_sequence;
  678. struct vk_mat_mat_push_constants {
  679. uint32_t M; uint32_t N; uint32_t K;
  680. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  681. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  682. uint32_t k_split;
  683. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  684. uint32_t padded_N;
  685. };
  686. struct vk_mat_vec_push_constants {
  687. uint32_t ncols;
  688. uint32_t stride_a;
  689. uint32_t stride_b;
  690. uint32_t stride_d;
  691. uint32_t batch_stride_a;
  692. uint32_t batch_stride_b;
  693. uint32_t batch_stride_d;
  694. uint32_t enable_bias;
  695. uint32_t enable_scale;
  696. uint32_t ne02;
  697. uint32_t ne12;
  698. uint32_t broadcast2;
  699. uint32_t broadcast3;
  700. };
  701. struct vk_mat_mat_id_push_constants {
  702. uint32_t M; uint32_t N; uint32_t K;
  703. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  704. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  705. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  706. uint32_t padded_N;
  707. };
  708. struct vk_mat_vec_id_push_constants {
  709. uint32_t ncols;
  710. uint32_t stride_a;
  711. uint32_t stride_b;
  712. uint32_t stride_d;
  713. uint32_t batch_stride_a;
  714. uint32_t batch_stride_b;
  715. uint32_t batch_stride_d;
  716. uint32_t enable_bias;
  717. uint32_t enable_scale;
  718. uint32_t nei0;
  719. uint32_t ne11;
  720. };
  721. struct vk_flash_attn_push_constants {
  722. uint32_t N;
  723. uint32_t KV;
  724. uint32_t ne1;
  725. uint32_t ne2;
  726. uint32_t ne3;
  727. uint32_t neq2;
  728. uint32_t neq3;
  729. uint32_t nek2;
  730. uint32_t nek3;
  731. uint32_t nev2;
  732. uint32_t nev3;
  733. uint32_t nem1;
  734. uint32_t nem2;
  735. uint32_t nem3;
  736. uint32_t nb01;
  737. uint32_t nb02;
  738. uint32_t nb03;
  739. uint32_t nb11;
  740. uint32_t nb12;
  741. uint32_t nb13;
  742. uint32_t nb21;
  743. uint32_t nb22;
  744. uint32_t nb23;
  745. float scale;
  746. float max_bias;
  747. float logit_softcap;
  748. uint32_t mask_n_head_log2;
  749. float m0;
  750. float m1;
  751. uint32_t gqa_ratio;
  752. uint32_t split_kv;
  753. uint32_t k_num;
  754. };
  755. static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128");
  756. struct vk_op_push_constants {
  757. uint32_t KX;
  758. uint32_t KY;
  759. float param1;
  760. float param2;
  761. };
  762. struct vk_op_glu_push_constants {
  763. uint32_t N;
  764. uint32_t ne00;
  765. uint32_t ne20;
  766. uint32_t mode; // 0: default, 1: swapped, 2: split
  767. float alpha; // for swiglu_oai
  768. float limit;
  769. };
  770. struct vk_op_unary_push_constants {
  771. uint32_t ne;
  772. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  773. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  774. uint32_t misalign_offsets;
  775. float param1; float param2;
  776. uint32_t ne0_012mp; uint32_t ne0_012L;
  777. uint32_t ne0_01mp; uint32_t ne0_01L;
  778. uint32_t ne0_0mp; uint32_t ne0_0L;
  779. uint32_t ne1_012mp; uint32_t ne1_012L;
  780. uint32_t ne1_01mp; uint32_t ne1_01L;
  781. uint32_t ne1_0mp; uint32_t ne1_0L;
  782. };
  783. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  784. static vk_op_unary_push_constants vk_op_unary_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst, int64_t ne = 0) {
  785. GGML_ASSERT(ne != 0 || (ggml_nelements(src0) == ggml_nelements(dst)));
  786. ne = ne != 0 ? ne : ggml_nelements(dst);
  787. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  788. vk_op_unary_push_constants p{};
  789. p.ne = (uint32_t)ne;
  790. size_t src0_tsize = ggml_type_size(src0->type);
  791. p.ne00 = (uint32_t)src0->ne[0];
  792. p.ne01 = (uint32_t)src0->ne[1];
  793. p.ne02 = (uint32_t)src0->ne[2];
  794. p.ne03 = (uint32_t)src0->ne[3];
  795. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  796. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  797. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  798. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  799. size_t dst_tsize = ggml_type_size(dst->type);
  800. p.ne10 = (uint32_t)dst->ne[0];
  801. p.ne11 = (uint32_t)dst->ne[1];
  802. p.ne12 = (uint32_t)dst->ne[2];
  803. p.ne13 = (uint32_t)dst->ne[3];
  804. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  805. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  806. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  807. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  808. return p; // offsets are initialized later in ggml_vk_op
  809. }
  810. struct vk_op_pad_push_constants {
  811. uint32_t ne;
  812. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  813. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  814. uint32_t misalign_offsets;
  815. uint32_t lp0; uint32_t rp0;
  816. uint32_t lp1; uint32_t rp1;
  817. uint32_t lp2; uint32_t rp2;
  818. uint32_t lp3; uint32_t rp3;
  819. };
  820. static vk_op_pad_push_constants vk_op_pad_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst) {
  821. int64_t ne = ggml_nelements(dst);
  822. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  823. vk_op_pad_push_constants p{};
  824. p.ne = (uint32_t)ne;
  825. size_t src0_tsize = ggml_type_size(src0->type);
  826. p.ne00 = (uint32_t)src0->ne[0];
  827. p.ne01 = (uint32_t)src0->ne[1];
  828. p.ne02 = (uint32_t)src0->ne[2];
  829. p.ne03 = (uint32_t)src0->ne[3];
  830. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  831. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  832. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  833. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  834. size_t dst_tsize = ggml_type_size(dst->type);
  835. p.ne10 = (uint32_t)dst->ne[0];
  836. p.ne11 = (uint32_t)dst->ne[1];
  837. p.ne12 = (uint32_t)dst->ne[2];
  838. p.ne13 = (uint32_t)dst->ne[3];
  839. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  840. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  841. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  842. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  843. p.lp0 = dst->op_params[0];
  844. p.rp0 = dst->op_params[1];
  845. p.lp1 = dst->op_params[2];
  846. p.rp1 = dst->op_params[3];
  847. p.lp2 = dst->op_params[4];
  848. p.rp2 = dst->op_params[5];
  849. p.lp3 = dst->op_params[6];
  850. p.rp3 = dst->op_params[7];
  851. return p; // fastdiv values and offsets are initialized later in ggml_vk_op
  852. }
  853. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  854. // Precompute mp (m' in the paper) and L such that division
  855. // can be computed using a multiply (high 32b of 64b result)
  856. // and a shift:
  857. //
  858. // n/d = (mulhi(n, mp) + n) >> L;
  859. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  860. {
  861. // compute L = ceil(log2(d));
  862. L = 0;
  863. while (L < 32 && (uint32_t{1} << L) < d) {
  864. L++;
  865. }
  866. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  867. }
  868. template <typename T> void init_pushconst_fastdiv(T &p) {
  869. GGML_UNUSED(p);
  870. static_assert(!std::is_const<T>::value, "unexpected type");
  871. }
  872. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  873. // Compute magic values to divide by these six numbers.
  874. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  875. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  876. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  877. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  878. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  879. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  880. }
  881. struct vk_op_binary_push_constants {
  882. uint32_t ne;
  883. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  884. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  885. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  886. uint32_t misalign_offsets;
  887. float param1; float param2; int32_t param3;
  888. };
  889. struct vk_op_multi_add_push_constants {
  890. // shape for dst
  891. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23;
  892. // strides for srcs+dst
  893. uint32_t nb[MAX_PARAMETER_COUNT][4];
  894. uint32_t rms_partials;
  895. };
  896. // update multi_add.comp if this changes
  897. static_assert(MAX_PARAMETER_COUNT == 12);
  898. static_assert(sizeof(vk_op_multi_add_push_constants) <= 256);
  899. struct vk_op_topk_moe_push_constants {
  900. uint32_t n_rows;
  901. uint32_t n_expert_used;
  902. float clamp_min;
  903. float clamp_max;
  904. };
  905. struct vk_op_add_id_push_constants {
  906. uint32_t ne0;
  907. uint32_t ne1;
  908. uint32_t s01;
  909. uint32_t s02;
  910. uint32_t s11;
  911. uint32_t s21;
  912. };
  913. struct vk_op_diag_mask_push_constants {
  914. uint32_t ncols;
  915. uint32_t rows_per_channel;
  916. int32_t n_past;
  917. };
  918. struct vk_op_rope_push_constants {
  919. uint32_t rope_mode;
  920. uint32_t ncols;
  921. uint32_t n_dims;
  922. float freq_scale;
  923. uint32_t p_delta_rows;
  924. float freq_base;
  925. float ext_factor;
  926. float attn_factor;
  927. float corr_dims[2];
  928. float theta_scale;
  929. uint32_t has_ff;
  930. uint32_t ne02;
  931. uint32_t s1;
  932. uint32_t s2;
  933. int32_t sections[4];
  934. uint32_t is_imrope;
  935. uint32_t is_back;
  936. uint32_t set_rows_stride;
  937. };
  938. // For fused rms_norm+mul+rope(+view+set_rows)
  939. struct vk_op_rms_norm_mul_rope_push_constants {
  940. vk_op_binary_push_constants bin;
  941. vk_op_rope_push_constants rope;
  942. };
  943. struct vk_op_soft_max_push_constants {
  944. uint32_t KX;
  945. uint32_t KY;
  946. uint32_t ne00;
  947. uint32_t ne01;
  948. uint32_t ne02;
  949. uint32_t ne12;
  950. uint32_t ne13;
  951. uint32_t nb11;
  952. uint32_t nb12;
  953. uint32_t nb13;
  954. float scale;
  955. float max_bias;
  956. float m0;
  957. float m1;
  958. uint32_t n_head_log2;
  959. uint32_t nrows_x;
  960. uint32_t has_sinks;
  961. };
  962. struct vk_op_argsort_push_constants {
  963. uint32_t ncols;
  964. uint32_t nrows;
  965. int32_t order;
  966. };
  967. struct vk_op_im2col_push_constants {
  968. uint64_t dst_addr;
  969. uint32_t batch_offset; uint32_t offset_delta;
  970. uint32_t IC;
  971. uint32_t IW; uint32_t IH;
  972. uint32_t OW; uint32_t OH;
  973. uint32_t KW; uint32_t KH;
  974. uint32_t pelements;
  975. uint32_t CHW;
  976. int32_t s0; int32_t s1;
  977. int32_t p0; int32_t p1;
  978. int32_t d0; int32_t d1;
  979. };
  980. struct vk_op_im2col_3d_push_constants {
  981. uint64_t dst_addr;
  982. uint32_t nb10;
  983. uint32_t nb11;
  984. uint32_t nb12;
  985. uint32_t nb13;
  986. uint32_t s0;
  987. uint32_t s1;
  988. uint32_t s2;
  989. uint32_t p0;
  990. uint32_t p1;
  991. uint32_t p2;
  992. uint32_t d0;
  993. uint32_t d1;
  994. uint32_t d2;
  995. uint32_t IW;
  996. uint32_t IH;
  997. uint32_t ID;
  998. uint32_t IC;
  999. uint32_t KW;
  1000. uint32_t OH;
  1001. uint32_t KD_KH_KW;
  1002. uint32_t KH_KW;
  1003. uint32_t IC_KD_KH_KW;
  1004. uint32_t N_OD_OH;
  1005. uint32_t OD_OH;
  1006. uint32_t OD_OH_OW_IC_KD_KH_KW;
  1007. uint32_t OH_OW_IC_KD_KH_KW;
  1008. uint32_t OW_IC_KD_KH_KW;
  1009. uint32_t misalign_offsets;
  1010. };
  1011. struct vk_op_timestep_embedding_push_constants {
  1012. uint32_t nb1;
  1013. uint32_t dim;
  1014. uint32_t max_period;
  1015. };
  1016. struct vk_op_conv_transpose_1d_push_constants {
  1017. uint32_t Cout;
  1018. uint32_t Cin;
  1019. uint32_t K;
  1020. uint32_t L;
  1021. uint32_t KL;
  1022. uint32_t nb01;
  1023. uint32_t nb02;
  1024. uint32_t nb11;
  1025. uint32_t nb1;
  1026. int32_t s0;
  1027. };
  1028. struct vk_op_pool2d_push_constants {
  1029. uint32_t IW; uint32_t IH;
  1030. uint32_t OW; uint32_t OH;
  1031. uint32_t OC;
  1032. uint32_t pelements;
  1033. uint32_t op;
  1034. int32_t k0; int32_t k1;
  1035. int32_t s0; int32_t s1;
  1036. int32_t p0; int32_t p1;
  1037. };
  1038. struct vk_op_rwkv_wkv6_push_constants {
  1039. uint32_t B;
  1040. uint32_t T;
  1041. uint32_t C;
  1042. uint32_t H;
  1043. };
  1044. struct vk_op_rwkv_wkv7_push_constants {
  1045. uint32_t B;
  1046. uint32_t T;
  1047. uint32_t C;
  1048. uint32_t H;
  1049. };
  1050. struct vk_op_ssm_scan_push_constants {
  1051. uint32_t nb02, nb03, nb12, nb13;
  1052. uint32_t nb21, nb22, nb31;
  1053. uint32_t nb42, nb43, nb52, nb53;
  1054. uint32_t s_off;
  1055. uint32_t n_head, d_head, n_group, n_tok;
  1056. };
  1057. struct vk_op_ssm_conv_push_constants {
  1058. uint32_t nb01, nb02;
  1059. uint32_t nb11;
  1060. uint32_t dst_nb0, dst_nb1, dst_nb2;
  1061. uint32_t nc, ncs, nr, n_t, n_s;
  1062. };
  1063. struct vk_op_conv2d_push_constants {
  1064. uint32_t Cout;
  1065. uint32_t Cin;
  1066. uint32_t N;
  1067. uint32_t KW;
  1068. uint32_t KH;
  1069. uint32_t W;
  1070. uint32_t H;
  1071. uint32_t OW;
  1072. uint32_t OH;
  1073. uint32_t s0;
  1074. uint32_t s1;
  1075. uint32_t p0;
  1076. uint32_t p1;
  1077. uint32_t d0;
  1078. uint32_t d1;
  1079. uint32_t nb01;
  1080. uint32_t nb02;
  1081. uint32_t nb03;
  1082. uint32_t nb11;
  1083. uint32_t nb12;
  1084. uint32_t nb13;
  1085. uint32_t nb1;
  1086. uint32_t nb2;
  1087. uint32_t nb3;
  1088. // init_fastdiv_values constants for dividing by OW, OW*OH
  1089. uint32_t OWmp; uint32_t OWL;
  1090. uint32_t OWOHmp; uint32_t OWOHL;
  1091. };
  1092. template <> void init_pushconst_fastdiv(vk_op_conv2d_push_constants &p) {
  1093. // Compute magic values to divide by OW, OW*OH
  1094. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1095. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1096. }
  1097. struct vk_op_conv_transpose_2d_push_constants {
  1098. uint32_t Cout;
  1099. uint32_t Cin;
  1100. uint32_t N;
  1101. uint32_t KW;
  1102. uint32_t KH;
  1103. uint32_t W;
  1104. uint32_t H;
  1105. uint32_t OW;
  1106. uint32_t OH;
  1107. uint32_t s0;
  1108. uint32_t s1;
  1109. uint32_t p0;
  1110. uint32_t p1;
  1111. uint32_t d0;
  1112. uint32_t d1;
  1113. uint32_t nb01;
  1114. uint32_t nb02;
  1115. uint32_t nb03;
  1116. uint32_t nb11;
  1117. uint32_t nb12;
  1118. uint32_t nb13;
  1119. uint32_t nb1;
  1120. uint32_t nb2;
  1121. uint32_t nb3;
  1122. // init_fastdiv_values constants for dividing by OW, OW*OH
  1123. uint32_t OWmp; uint32_t OWL;
  1124. uint32_t OWOHmp; uint32_t OWOHL;
  1125. };
  1126. template <> void init_pushconst_fastdiv(vk_op_conv_transpose_2d_push_constants &p) {
  1127. // Compute magic values to divide by OW, OW*OH
  1128. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1129. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1130. }
  1131. struct vk_op_conv2d_dw_push_constants {
  1132. uint32_t ne;
  1133. uint32_t batches;
  1134. uint32_t channels;
  1135. uint32_t dst_w;
  1136. uint32_t dst_h;
  1137. uint32_t src_w;
  1138. uint32_t src_h;
  1139. uint32_t knl_w;
  1140. uint32_t knl_h;
  1141. int32_t stride_x;
  1142. int32_t stride_y;
  1143. int32_t pad_x;
  1144. int32_t pad_y;
  1145. int32_t dilation_x;
  1146. int32_t dilation_y;
  1147. };
  1148. struct vk_op_upscale_push_constants {
  1149. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  1150. uint32_t ne00; uint32_t ne01;
  1151. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1152. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  1153. float sf0; float sf1; float sf2; float sf3;
  1154. float pixel_offset;
  1155. };
  1156. struct vk_op_sum_rows_push_constants
  1157. {
  1158. uint32_t n_cols;
  1159. uint32_t ne01, ne02;
  1160. uint32_t nb01, nb02, nb03;
  1161. uint32_t nb11, nb12, nb13;
  1162. float weight;
  1163. uint32_t misalign_offsets;
  1164. uint32_t ne0_12mp, ne0_12L;
  1165. uint32_t ne0_1mp, ne0_1L;
  1166. };
  1167. 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) {
  1168. uint32_t type_size = (uint32_t)ggml_type_size(src->type);
  1169. vk_op_sum_rows_push_constants p = {};
  1170. p.n_cols = (uint32_t)n_cols;
  1171. p.ne01 = (uint32_t)src->ne[1];
  1172. p.ne02 = (uint32_t)src->ne[2];
  1173. p.nb01 = (uint32_t)src->nb[1] / type_size;
  1174. p.nb02 = (uint32_t)src->nb[2] / type_size;
  1175. p.nb03 = (uint32_t)src->nb[3] / type_size;
  1176. p.nb11 = (uint32_t)dst->nb[1] / type_size;
  1177. p.nb12 = (uint32_t)dst->nb[2] / type_size;
  1178. p.nb13 = (uint32_t)dst->nb[3] / type_size;
  1179. p.weight = 1.0f;
  1180. return p;
  1181. }
  1182. template <> void init_pushconst_fastdiv(vk_op_sum_rows_push_constants &p) {
  1183. init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L);
  1184. init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L);
  1185. }
  1186. // Allow pre-recording command buffers
  1187. struct vk_staging_memcpy {
  1188. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  1189. void * dst;
  1190. const void * src;
  1191. size_t n;
  1192. };
  1193. struct vk_staging_memset {
  1194. vk_staging_memset(void * _dst, uint32_t _val, size_t _n) : dst(_dst), val(_val), n(_n) {}
  1195. void * dst;
  1196. uint32_t val;
  1197. size_t n;
  1198. };
  1199. struct vk_context_struct {
  1200. vk_submission * s;
  1201. std::vector<vk_sequence> seqs;
  1202. int exit_tensor_idx;
  1203. std::vector<vk_staging_memcpy> in_memcpys;
  1204. std::vector<vk_staging_memcpy> out_memcpys;
  1205. std::vector<vk_staging_memset> memsets;
  1206. vk_command_pool * p {};
  1207. };
  1208. typedef std::shared_ptr<vk_context_struct> vk_context;
  1209. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  1210. struct ggml_vk_garbage_collector {
  1211. std::vector<vk_semaphore> tl_semaphores;
  1212. std::vector<vk_semaphore> semaphores;
  1213. std::vector<vk::Event> events;
  1214. std::vector<vk_context> contexts;
  1215. };
  1216. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx);
  1217. static void ggml_vk_load_shaders(vk_device& device);
  1218. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx);
  1219. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  1220. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  1221. static std::string format_size(size_t size) {
  1222. const size_t kib = 1024;
  1223. const size_t mib = kib * 1024;
  1224. const size_t gib = mib * 1024;
  1225. std::ostringstream oss;
  1226. oss << std::fixed << std::setprecision(2);
  1227. if (size >= gib) {
  1228. oss << static_cast<double>(size) / gib << " GiB";
  1229. } else if (size >= mib) {
  1230. oss << static_cast<double>(size) / mib << " MiB";
  1231. } else if (size >= kib) {
  1232. oss << static_cast<double>(size) / kib << " KiB";
  1233. } else {
  1234. oss << size << " B";
  1235. }
  1236. return oss.str();
  1237. }
  1238. class vk_memory_logger {
  1239. public:
  1240. vk_memory_logger(): total_device(0), total_host(0) {}
  1241. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  1242. void log_deallocation(vk_buffer_ref buf_ref);
  1243. private:
  1244. std::map<vk::Buffer, size_t> allocations; // Track allocations
  1245. size_t total_device;
  1246. size_t total_host;
  1247. };
  1248. #else
  1249. #define VK_LOG_MEMORY(msg) ((void) 0)
  1250. #endif // GGML_VULKAN_MEMORY_DEBUG
  1251. class vk_perf_logger {
  1252. public:
  1253. void print_timings() {
  1254. if (timings.empty()) {
  1255. return;
  1256. }
  1257. uint64_t total_all_op_times = 0;
  1258. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  1259. for (const auto & t : timings) {
  1260. uint64_t total_op_times = 0;
  1261. for (const auto & time : t.second) {
  1262. total_op_times += time;
  1263. }
  1264. std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0)
  1265. << " us";
  1266. // If we have as many flops entries as timing entries for the op, then compute and log the flops/S.
  1267. auto it = flops.find(t.first);
  1268. if (it != flops.end() && (it->second).size() == t.second.size()) {
  1269. uint64_t total_op_flops = 0;
  1270. for (const auto & elem : it->second) {
  1271. total_op_flops += elem;
  1272. }
  1273. std::cerr << " ("
  1274. << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) /
  1275. (double(total_op_times) / (1000.0 * 1000.0 * 1000.0))
  1276. << " GFLOPS/s)";
  1277. }
  1278. total_all_op_times += total_op_times;
  1279. std::cerr << std::endl;
  1280. }
  1281. if (timings.size() > 0) {
  1282. std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl;
  1283. }
  1284. timings.clear();
  1285. flops.clear();
  1286. }
  1287. void log_timing(const ggml_tensor * node, uint64_t time) {
  1288. if (node->op == GGML_OP_UNARY) {
  1289. timings[ggml_unary_op_name(ggml_get_unary_op(node))].push_back(time);
  1290. return;
  1291. }
  1292. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  1293. const uint64_t m = node->src[0]->ne[1];
  1294. const uint64_t n = node->ne[1];
  1295. const uint64_t k = node->src[1]->ne[0];
  1296. const uint64_t batch = node->src[1]->ne[2] * node->src[1]->ne[3];
  1297. std::string name = ggml_op_name(node->op);
  1298. if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) ||
  1299. (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) {
  1300. name += "_VEC";
  1301. }
  1302. name += " ";
  1303. name += ggml_type_name(node->src[0]->type);
  1304. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  1305. if (batch > 1) {
  1306. name += " batch=" + std::to_string(batch);
  1307. }
  1308. timings[name].push_back(time);
  1309. flops[name].push_back(m * n * (k + (k - 1)) * batch);
  1310. return;
  1311. }
  1312. if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) {
  1313. std::string name = ggml_op_name(node->op);
  1314. ggml_tensor * knl = node->src[0];
  1315. uint64_t OW = node->ne[0];
  1316. uint64_t OH = node->ne[1];
  1317. uint64_t N = node->ne[3];
  1318. uint64_t Cout = node->ne[2];
  1319. uint64_t KW = knl->ne[0];
  1320. uint64_t KH = knl->ne[1];
  1321. uint64_t Cin = node->src[1]->ne[2];
  1322. // KxCRS @ CRSxNPQ = KxNPQ -> M=K, K=CRS, N=NPQ
  1323. uint64_t size_M = Cout;
  1324. uint64_t size_K = Cin * KW * KH;
  1325. uint64_t size_N = N * OW * OH;
  1326. uint64_t n_flops = size_M * size_N * (size_K + (size_K - 1));
  1327. name += " M=Cout=" + std::to_string(size_M) + ", K=Cin*KW*KH=" + std::to_string(size_K) +
  1328. ", N=N*OW*OH=" + std::to_string(size_N);
  1329. flops[name].push_back(n_flops);
  1330. timings[name].push_back(time);
  1331. return;
  1332. }
  1333. if (node->op == GGML_OP_RMS_NORM) {
  1334. std::string name = ggml_op_name(node->op);
  1335. 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]) + ")";
  1336. timings[name].push_back(time);
  1337. return;
  1338. }
  1339. timings[ggml_op_name(node->op)].push_back(time);
  1340. }
  1341. private:
  1342. std::map<std::string, std::vector<uint64_t>> timings;
  1343. std::map<std::string, std::vector<uint64_t>> flops;
  1344. };
  1345. struct ggml_backend_vk_context {
  1346. std::string name;
  1347. vk_device device;
  1348. size_t semaphore_idx, event_idx;
  1349. ggml_vk_garbage_collector gc;
  1350. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset;
  1351. vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials;
  1352. vk::Fence fence, almost_ready_fence;
  1353. bool almost_ready_fence_pending {};
  1354. // Set before op_add and unset after op_rms_norm to indicate that the add should
  1355. // write partial sums to accumulate the square of the vector components
  1356. bool do_add_rms_partials_offset_calculation;
  1357. bool do_add_rms_partials;
  1358. uint64_t last_total_mul_mat_bytes {};
  1359. // Cache most recent tensor that was converted into prealloc_y, and what pipeline it used to convert.
  1360. vk_pipeline_struct * prealloc_y_last_pipeline_used {};
  1361. const ggml_tensor * prealloc_y_last_tensor_used {};
  1362. // Track which nodes have been used since the last sync, and whether they were written to
  1363. std::vector<const ggml_tensor *> unsynced_nodes_written;
  1364. std::vector<const ggml_tensor *> unsynced_nodes_read;
  1365. // Track which prealloc buffers have pending reads that need to be synchronized.
  1366. // These are checked before writing to the buffer (and call ggml_vk_sync_buffers if set),
  1367. // and set to true after the buffer contents are consumed.
  1368. bool prealloc_x_need_sync, prealloc_y_need_sync, prealloc_split_k_need_sync;
  1369. vk_context_ref compute_ctx;
  1370. vk_context_ref transfer_ctx;
  1371. std::vector<vk_context_ref> tensor_ctxs;
  1372. std::vector<vk::DescriptorPool> descriptor_pools;
  1373. std::vector<vk::DescriptorSet> descriptor_sets;
  1374. uint32_t descriptor_set_idx {};
  1375. uint32_t pipeline_descriptor_set_requirements {};
  1376. vk_command_pool compute_cmd_pool;
  1377. vk_command_pool transfer_cmd_pool;
  1378. // number of additional consecutive nodes that are being fused with the
  1379. // node currently being processed
  1380. int num_additional_fused_ops {};
  1381. // Bitmask of which fused ops need to write an intermediate value to memory.
  1382. // Bit 'i' means nodes[start_of_fusion + i] writes to memory.
  1383. // If there's no fusion, bit 0 is still set.
  1384. int fused_ops_write_mask {};
  1385. };
  1386. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  1387. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  1388. if (tensor->view_src) {
  1389. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  1390. }
  1391. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  1392. }
  1393. struct ggml_backend_vk_buffer_context {
  1394. vk_device_ref device;
  1395. vk_buffer dev_buffer;
  1396. std::string name;
  1397. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  1398. device(device),
  1399. dev_buffer(dev_buffer),
  1400. name(name) {
  1401. }
  1402. ~ggml_backend_vk_buffer_context() {
  1403. ggml_vk_destroy_buffer(dev_buffer);
  1404. }
  1405. };
  1406. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1407. static std::mutex log_mutex;
  1408. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  1409. std::lock_guard<std::mutex> guard(log_mutex);
  1410. vk_buffer buf = buf_ref.lock();
  1411. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1412. const std::string type = device ? "device" : "host";
  1413. allocations[buf->buffer] = size;
  1414. total_device += device ? size : 0;
  1415. total_host += device ? 0 : size;
  1416. 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));
  1417. }
  1418. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  1419. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  1420. return;
  1421. }
  1422. std::lock_guard<std::mutex> guard(log_mutex);
  1423. vk_buffer buf = buf_ref.lock();
  1424. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1425. std::string type = device ? "device" : "host";
  1426. auto it = allocations.find(buf->buffer);
  1427. total_device -= device ? it->second : 0;
  1428. total_host -= device ? 0 : it->second;
  1429. if (it != allocations.end()) {
  1430. 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));
  1431. allocations.erase(it);
  1432. } else {
  1433. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  1434. }
  1435. }
  1436. #endif // GGML_VULKAN_MEMORY_DEBUG
  1437. struct vk_instance_t {
  1438. vk::Instance instance;
  1439. bool debug_utils_support = false; // VK_EXT_debug_utils enabled
  1440. PFN_vkSetDebugUtilsObjectNameEXT pfn_vkSetDebugUtilsObjectNameEXT = {};
  1441. PFN_vkQueueBeginDebugUtilsLabelEXT pfn_vkQueueBeginDebugUtilsLabelEXT = {};
  1442. PFN_vkQueueEndDebugUtilsLabelEXT pfn_vkQueueEndDebugUtilsLabelEXT = {};
  1443. PFN_vkCmdBeginDebugUtilsLabelEXT pfn_vkCmdBeginDebugUtilsLabelEXT = {};
  1444. PFN_vkCmdEndDebugUtilsLabelEXT pfn_vkCmdEndDebugUtilsLabelEXT = {};
  1445. PFN_vkCmdInsertDebugUtilsLabelEXT pfn_vkCmdInsertDebugUtilsLabelEXT = {};
  1446. std::vector<size_t> device_indices;
  1447. std::vector<bool> device_supports_membudget;
  1448. vk_device devices[GGML_VK_MAX_DEVICES];
  1449. };
  1450. static bool vk_instance_initialized = false;
  1451. static vk_instance_t vk_instance;
  1452. static bool vk_perf_logger_enabled = false;
  1453. #ifdef GGML_VULKAN_CHECK_RESULTS
  1454. static size_t vk_skip_checks;
  1455. static size_t vk_output_tensor;
  1456. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  1457. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1458. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1459. #endif
  1460. 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);
  1461. static void ggml_backend_vk_free(ggml_backend_t backend);
  1462. static VkDeviceSize ggml_vk_get_max_buffer_range(const ggml_backend_vk_context * ctx, const vk_buffer &buf, const VkDeviceSize offset) {
  1463. const VkDeviceSize range = std::min(VkDeviceSize{buf->size - offset},
  1464. VkDeviceSize{ctx->device->properties.limits.maxStorageBufferRange});
  1465. return range;
  1466. }
  1467. // Wait for ctx->fence to be signaled.
  1468. static void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) {
  1469. // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep
  1470. // during this wait.
  1471. if (ctx->almost_ready_fence_pending) {
  1472. VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence");
  1473. ctx->device->device.resetFences({ ctx->almost_ready_fence });
  1474. ctx->almost_ready_fence_pending = false;
  1475. }
  1476. // Spin (w/pause) waiting for the graph to finish executing.
  1477. vk::Result result;
  1478. while ((result = ctx->device->device.getFenceStatus(ctx->fence)) != vk::Result::eSuccess) {
  1479. if (result != vk::Result::eNotReady) {
  1480. fprintf(stderr, "ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__);
  1481. exit(1);
  1482. }
  1483. for (uint32_t i = 0; i < 100; ++i) {
  1484. YIELD();
  1485. YIELD();
  1486. YIELD();
  1487. YIELD();
  1488. YIELD();
  1489. YIELD();
  1490. YIELD();
  1491. YIELD();
  1492. YIELD();
  1493. YIELD();
  1494. }
  1495. }
  1496. ctx->device->device.resetFences({ ctx->fence });
  1497. }
  1498. // variables to track number of compiles in progress
  1499. static uint32_t compile_count = 0;
  1500. static std::mutex compile_count_mutex;
  1501. static std::condition_variable compile_count_cond;
  1502. 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,
  1503. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  1504. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  1505. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  1506. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  1507. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  1508. GGML_ASSERT(parameter_count > 0);
  1509. GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT);
  1510. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  1511. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  1512. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  1513. vk::PushConstantRange pcr(
  1514. vk::ShaderStageFlagBits::eCompute,
  1515. 0,
  1516. pipeline->push_constant_size
  1517. );
  1518. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr);
  1519. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  1520. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  1521. for (size_t i = 0; i < specialization_constants.size(); i++) {
  1522. specialization_entries[i].constantID = i;
  1523. specialization_entries[i].offset = i * sizeof(uint32_t);
  1524. specialization_entries[i].size = sizeof(uint32_t);
  1525. }
  1526. vk::SpecializationInfo specialization_info(
  1527. specialization_entries.size(),
  1528. specialization_entries.data(),
  1529. specialization_constants.size() * sizeof(uint32_t),
  1530. specialization_constants.data()
  1531. );
  1532. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  1533. if (device->subgroup_require_full_support && require_full_subgroups) {
  1534. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  1535. }
  1536. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  1537. pipeline_shader_stage_create_flags,
  1538. vk::ShaderStageFlagBits::eCompute,
  1539. pipeline->shader_module,
  1540. entrypoint.c_str(),
  1541. &specialization_info);
  1542. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  1543. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  1544. if (device->subgroup_size_control && required_subgroup_size > 0) {
  1545. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  1546. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  1547. }
  1548. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  1549. device->pipeline_executable_properties_support ?
  1550. vk::PipelineCreateFlagBits::eCaptureStatisticsKHR :
  1551. vk::PipelineCreateFlags{},
  1552. pipeline_shader_create_info,
  1553. pipeline->layout);
  1554. vk::PipelineRobustnessCreateInfoEXT rci;
  1555. if (device->pipeline_robustness && disable_robustness) {
  1556. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1557. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1558. compute_pipeline_create_info.setPNext(&rci);
  1559. }
  1560. try {
  1561. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  1562. } catch (const vk::SystemError& e) {
  1563. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  1564. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1565. throw e;
  1566. }
  1567. pipeline->compiled = true;
  1568. if (vk_instance.debug_utils_support) {
  1569. vk::DebugUtilsObjectNameInfoEXT duoni;
  1570. duoni.objectType = vk::ObjectType::ePipeline;
  1571. duoni.pObjectName = pipeline->name.c_str();
  1572. duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast<VkPipeline>(pipeline->pipeline));
  1573. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast<VkDebugUtilsObjectNameInfoEXT &>(duoni));
  1574. }
  1575. if (device->pipeline_executable_properties_support) {
  1576. vk::PipelineExecutableInfoKHR executableInfo;
  1577. executableInfo.pipeline = pipeline->pipeline;
  1578. auto statistics = device->device.getPipelineExecutableStatisticsKHR(executableInfo);
  1579. for (auto & s : statistics) {
  1580. // "Register Count" is reported by NVIDIA drivers.
  1581. if (strcmp(s.name, "Register Count") == 0) {
  1582. VK_LOG_DEBUG(pipeline->name << " " << s.name << ": " << s.value.u64 << " registers");
  1583. pipeline->register_count = (uint32_t)s.value.u64;
  1584. }
  1585. }
  1586. }
  1587. device->all_pipelines.push_back(pipeline);
  1588. {
  1589. std::lock_guard<std::mutex> guard(compile_count_mutex);
  1590. assert(compile_count > 0);
  1591. compile_count--;
  1592. }
  1593. compile_count_cond.notify_all();
  1594. }
  1595. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  1596. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  1597. device.destroyPipelineLayout(pipeline->layout);
  1598. device.destroyShaderModule(pipeline->shader_module);
  1599. device.destroyPipeline(pipeline->pipeline);
  1600. }
  1601. static void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) {
  1602. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  1603. ctx->pipeline_descriptor_set_requirements += n;
  1604. if (!pipeline->compiled) {
  1605. pipeline->needed = true;
  1606. ggml_vk_load_shaders(ctx->device);
  1607. }
  1608. ggml_pipeline_allocate_descriptor_sets(ctx);
  1609. }
  1610. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
  1611. if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) {
  1612. // Enough descriptors are available
  1613. return;
  1614. }
  1615. vk_device& device = ctx->device;
  1616. // Grow by 50% to avoid frequent allocations
  1617. uint32_t needed = std::max(3 * ctx->descriptor_sets.size() / 2, size_t{ctx->pipeline_descriptor_set_requirements});
  1618. uint32_t to_alloc = needed - ctx->descriptor_sets.size();
  1619. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1620. uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1621. while (to_alloc > 0) {
  1622. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  1623. to_alloc -= alloc_count;
  1624. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1625. if (pool_idx >= ctx->descriptor_pools.size()) {
  1626. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  1627. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  1628. ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  1629. }
  1630. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  1631. for (uint32_t i = 0; i < alloc_count; i++) {
  1632. layouts[i] = device->dsl;
  1633. }
  1634. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
  1635. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  1636. ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
  1637. pool_idx++;
  1638. }
  1639. }
  1640. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) {
  1641. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  1642. if (p.cmd_buffers.size() > p.cmd_buffer_idx) {
  1643. // Reuse command buffer
  1644. return p.cmd_buffers[p.cmd_buffer_idx++];
  1645. }
  1646. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  1647. p.pool,
  1648. vk::CommandBufferLevel::ePrimary,
  1649. 1);
  1650. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  1651. auto buf = cmd_buffers.front();
  1652. p.cmd_buffers.push_back(buf);
  1653. p.cmd_buffer_idx++;
  1654. return buf;
  1655. }
  1656. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  1657. if (ctx->seqs.empty()) {
  1658. if (fence) {
  1659. std::lock_guard<std::mutex> guard(queue_mutex);
  1660. ctx->p->q->queue.submit({}, fence);
  1661. }
  1662. return;
  1663. }
  1664. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  1665. std::vector<std::vector<uint64_t>> tl_wait_vals;
  1666. std::vector<std::vector<uint64_t>> tl_signal_vals;
  1667. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  1668. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  1669. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  1670. std::vector<vk::SubmitInfo> submit_infos;
  1671. int idx = -1;
  1672. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  1673. size_t reserve = 0;
  1674. for (const auto& sequence : ctx->seqs) {
  1675. reserve += sequence.size();
  1676. }
  1677. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  1678. tl_wait_semaphores.reserve(reserve);
  1679. tl_wait_vals.reserve(reserve);
  1680. tl_signal_semaphores.reserve(reserve);
  1681. tl_signal_vals.reserve(reserve);
  1682. tl_submit_infos.reserve(reserve);
  1683. submit_infos.reserve(reserve);
  1684. stage_flags.reserve(reserve);
  1685. for (const auto& sequence : ctx->seqs) {
  1686. for (const auto& submission : sequence) {
  1687. stage_flags.push_back({});
  1688. idx++;
  1689. tl_wait_vals.push_back({});
  1690. tl_wait_semaphores.push_back({});
  1691. tl_signal_vals.push_back({});
  1692. tl_signal_semaphores.push_back({});
  1693. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  1694. stage_flags[idx].push_back(ctx->p->q->stage_flags);
  1695. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  1696. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  1697. }
  1698. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  1699. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  1700. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  1701. }
  1702. tl_submit_infos.push_back({
  1703. (uint32_t) submission.wait_semaphores.size(),
  1704. tl_wait_vals[idx].data(),
  1705. (uint32_t) submission.signal_semaphores.size(),
  1706. tl_signal_vals[idx].data(),
  1707. });
  1708. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  1709. tl_submit_infos[idx].pNext = nullptr;
  1710. vk::SubmitInfo si{
  1711. (uint32_t) submission.wait_semaphores.size(),
  1712. tl_wait_semaphores[idx].data(),
  1713. stage_flags[idx].data(),
  1714. 1,
  1715. &submission.buffer,
  1716. (uint32_t) submission.signal_semaphores.size(),
  1717. tl_signal_semaphores[idx].data(),
  1718. };
  1719. si.setPNext(&tl_submit_infos[idx]);
  1720. submit_infos.push_back(si);
  1721. }
  1722. }
  1723. std::lock_guard<std::mutex> guard(queue_mutex);
  1724. ctx->p->q->queue.submit(submit_infos, fence);
  1725. ctx->seqs.clear();
  1726. }
  1727. 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) {
  1728. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  1729. const uint32_t qfsize = queue_family_props.size();
  1730. // Try with avoid preferences first
  1731. for (uint32_t i = 0; i < qfsize; i++) {
  1732. 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)) {
  1733. return i;
  1734. }
  1735. }
  1736. // Fall back to only required
  1737. for (size_t i = 0; i < qfsize; i++) {
  1738. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  1739. return i;
  1740. }
  1741. }
  1742. // Fall back to reusing compute queue
  1743. for (size_t i = 0; i < qfsize; i++) {
  1744. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  1745. return i;
  1746. }
  1747. }
  1748. // Fall back to ignoring min_num_queries
  1749. for (size_t i = 0; i < qfsize; i++) {
  1750. if (queue_family_props[i].queueFlags & required) {
  1751. return i;
  1752. }
  1753. }
  1754. // 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.
  1755. // 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.
  1756. if (compute_index >= 0) {
  1757. return compute_index;
  1758. }
  1759. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  1760. for(auto &q_family : queue_family_props) {
  1761. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  1762. }
  1763. abort();
  1764. }
  1765. 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) {
  1766. VK_LOG_DEBUG("ggml_vk_create_queue()");
  1767. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1768. q.queue_family_index = queue_family_index;
  1769. q.transfer_only = transfer_only;
  1770. q.cmd_pool.init(device, &q);
  1771. q.queue = device->device.getQueue(queue_family_index, queue_index);
  1772. q.stage_flags = stage_flags;
  1773. }
  1774. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) {
  1775. vk_context result = std::make_shared<vk_context_struct>();
  1776. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  1777. ctx->gc.contexts.emplace_back(result);
  1778. result->p = &p;
  1779. return result;
  1780. }
  1781. static vk_context ggml_vk_create_temporary_context(vk_command_pool& p) {
  1782. vk_context result = std::make_shared<vk_context_struct>();
  1783. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  1784. result->p = &p;
  1785. return result;
  1786. }
  1787. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  1788. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1789. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  1790. vk::SemaphoreCreateInfo ci{};
  1791. ci.setPNext(&tci);
  1792. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1793. ctx->gc.semaphores.push_back({ semaphore, 0 });
  1794. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  1795. }
  1796. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  1797. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1798. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  1799. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  1800. vk::SemaphoreCreateInfo ci{};
  1801. ci.setPNext(&tci);
  1802. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1803. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  1804. }
  1805. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  1806. }
  1807. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  1808. if (ctx->event_idx >= ctx->gc.events.size()) {
  1809. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  1810. }
  1811. return ctx->gc.events[ctx->event_idx++];
  1812. }
  1813. static void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) {
  1814. VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()");
  1815. // Requires command buffers to be done
  1816. device->device.resetCommandPool(p.pool);
  1817. p.cmd_buffer_idx = 0;
  1818. }
  1819. static void ggml_vk_queue_command_pools_cleanup(vk_device& device) {
  1820. VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()");
  1821. // Arbitrary frequency to cleanup/reuse command buffers
  1822. static constexpr uint32_t cleanup_frequency = 10;
  1823. if (device->compute_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1824. ggml_vk_command_pool_cleanup(device, device->compute_queue.cmd_pool);
  1825. }
  1826. if (device->transfer_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1827. ggml_vk_command_pool_cleanup(device, device->transfer_queue.cmd_pool);
  1828. }
  1829. }
  1830. static std::vector<uint32_t> ggml_vk_find_memory_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  1831. std::vector<uint32_t> indices;
  1832. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  1833. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  1834. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  1835. (flags & memory_type.propertyFlags) == flags &&
  1836. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  1837. indices.push_back(i);
  1838. }
  1839. }
  1840. return indices;
  1841. }
  1842. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, const std::initializer_list<vk::MemoryPropertyFlags> & req_flags_list) {
  1843. 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]) << ")");
  1844. if (size > device->max_buffer_size) {
  1845. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device buffer size limit");
  1846. }
  1847. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  1848. if (size == 0) {
  1849. buf->size = 0;
  1850. return buf;
  1851. }
  1852. vk::BufferUsageFlags usage_flags = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst;
  1853. vk::MemoryAllocateFlags mem_flags {};
  1854. if (device->buffer_device_address) {
  1855. usage_flags |= vk::BufferUsageFlagBits::eShaderDeviceAddress;
  1856. mem_flags |= vk::MemoryAllocateFlagBits::eDeviceAddress;
  1857. }
  1858. vk::BufferCreateInfo buffer_create_info{
  1859. vk::BufferCreateFlags(),
  1860. size,
  1861. usage_flags,
  1862. vk::SharingMode::eExclusive,
  1863. 0,
  1864. nullptr,
  1865. };
  1866. buf->buffer = device->device.createBuffer(buffer_create_info);
  1867. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  1868. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  1869. const vk::MemoryAllocateFlagsInfo mem_flags_info { mem_flags };
  1870. for (auto it = req_flags_list.begin(); it != req_flags_list.end(); it++) {
  1871. const auto & req_flags = *it;
  1872. const std::vector<uint32_t> memory_type_indices = ggml_vk_find_memory_properties(&mem_props, &mem_req, req_flags);
  1873. if (memory_type_indices.empty()) {
  1874. continue;
  1875. }
  1876. buf->memory_property_flags = req_flags;
  1877. for (auto mtype_it = memory_type_indices.begin(); mtype_it != memory_type_indices.end(); mtype_it++) {
  1878. try {
  1879. buf->device_memory = device->device.allocateMemory({ mem_req.size, *mtype_it, &mem_flags_info });
  1880. break;
  1881. } catch (const vk::SystemError& e) {
  1882. // loop and retry
  1883. // during last attempt throw the exception
  1884. if (it + 1 == req_flags_list.end() && mtype_it + 1 == memory_type_indices.end()) {
  1885. device->device.destroyBuffer(buf->buffer);
  1886. throw e;
  1887. }
  1888. }
  1889. }
  1890. }
  1891. if (!buf->device_memory) {
  1892. device->device.destroyBuffer(buf->buffer);
  1893. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  1894. }
  1895. buf->ptr = nullptr;
  1896. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1897. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  1898. }
  1899. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  1900. buf->device = device;
  1901. buf->size = size;
  1902. if (device->buffer_device_address) {
  1903. const vk::BufferDeviceAddressInfo addressInfo(buf->buffer);
  1904. buf->bda_addr = device->device.getBufferAddress(addressInfo);
  1905. }
  1906. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1907. device->memory_logger->log_allocation(buf, size);
  1908. #endif
  1909. return buf;
  1910. }
  1911. 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)) {
  1912. try {
  1913. return ggml_vk_create_buffer(device, size, {req_flags, fallback_flags});
  1914. } catch (const vk::SystemError& e) {
  1915. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  1916. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1917. throw e;
  1918. }
  1919. }
  1920. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  1921. vk_buffer buf;
  1922. try {
  1923. if (device->prefer_host_memory) {
  1924. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1925. vk::MemoryPropertyFlagBits::eDeviceLocal});
  1926. } else if (device->uma) {
  1927. // Fall back to host memory type
  1928. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  1929. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1930. } else if (device->disable_host_visible_vidmem) {
  1931. if (device->allow_sysmem_fallback) {
  1932. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  1933. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1934. } else {
  1935. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  1936. }
  1937. } else {
  1938. // use rebar if available, otherwise fallback to device only visible memory
  1939. if (device->allow_sysmem_fallback) {
  1940. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1941. vk::MemoryPropertyFlagBits::eDeviceLocal,
  1942. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1943. } else {
  1944. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1945. vk::MemoryPropertyFlagBits::eDeviceLocal});
  1946. }
  1947. }
  1948. } catch (const vk::SystemError& e) {
  1949. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  1950. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1951. throw e;
  1952. }
  1953. return buf;
  1954. }
  1955. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  1956. if (buf == nullptr) {
  1957. return;
  1958. }
  1959. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1960. if (buf->device != nullptr) {
  1961. buf->device->memory_logger->log_deallocation(buf);
  1962. }
  1963. #endif
  1964. buf.reset();
  1965. }
  1966. static vk_subbuffer ggml_vk_subbuffer(const ggml_backend_vk_context* ctx, const vk_buffer& buf, size_t offset = 0) {
  1967. return { buf, offset, ggml_vk_get_max_buffer_range(ctx, buf, offset) };
  1968. }
  1969. static void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) {
  1970. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  1971. const bool transfer_queue = subctx->p->q->transfer_only;
  1972. if (ctx) {
  1973. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  1974. }
  1975. subctx->s->buffer.pipelineBarrier(
  1976. subctx->p->q->stage_flags,
  1977. subctx->p->q->stage_flags,
  1978. {},
  1979. { {
  1980. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  1981. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  1982. } },
  1983. {},
  1984. {}
  1985. );
  1986. }
  1987. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  1988. VK_LOG_DEBUG("ggml_vk_wait_events()");
  1989. if (events.empty()) {
  1990. return;
  1991. }
  1992. ctx->s->buffer.waitEvents(
  1993. events,
  1994. ctx->p->q->stage_flags,
  1995. ctx->p->q->stage_flags,
  1996. {},
  1997. {},
  1998. {}
  1999. );
  2000. }
  2001. // number of rows/cols for flash attention shader
  2002. static constexpr uint32_t flash_attention_num_small_rows = 32;
  2003. static constexpr uint32_t scalar_flash_attention_num_small_rows = 1;
  2004. static uint32_t get_fa_scalar_num_large_rows(uint32_t hsv) {
  2005. if (hsv >= 192) {
  2006. return 2;
  2007. } else {
  2008. return 8;
  2009. }
  2010. }
  2011. // The FA coopmat1 shader assumes 16x16x16 matrix multiply support.
  2012. // 128 threads split into four subgroups, each subgroup does 1/4
  2013. // of the Bc dimension.
  2014. static constexpr uint32_t coopmat1_flash_attention_num_large_rows = 16;
  2015. static constexpr uint32_t scalar_flash_attention_Bc = 64;
  2016. static constexpr uint32_t scalar_flash_attention_workgroup_size = 128;
  2017. static uint32_t get_fa_num_small_rows(FaCodePath path) {
  2018. if (path == FA_COOPMAT2) {
  2019. return flash_attention_num_small_rows;
  2020. } else {
  2021. return scalar_flash_attention_num_small_rows;
  2022. }
  2023. }
  2024. 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) {
  2025. GGML_UNUSED(clamp);
  2026. GGML_UNUSED(hsv);
  2027. if (path == FA_SCALAR) {
  2028. if (small_rows) {
  2029. return {scalar_flash_attention_num_small_rows, 64};
  2030. } else {
  2031. if ((hsv | hsk) & 8) {
  2032. // HSV/HSK not being a multiple of 16 makes D_split smaller, which makes cols_per_iter
  2033. // larger, and Bc needs to be >= cols_per_thread. 64 is large enough, 32 is not.
  2034. return {get_fa_scalar_num_large_rows(hsv), 64};
  2035. } else {
  2036. return {get_fa_scalar_num_large_rows(hsv), 32};
  2037. }
  2038. }
  2039. }
  2040. if (path == FA_COOPMAT1) {
  2041. if (small_rows) {
  2042. return {scalar_flash_attention_num_small_rows, scalar_flash_attention_Bc};
  2043. } else {
  2044. return {coopmat1_flash_attention_num_large_rows, scalar_flash_attention_Bc};
  2045. }
  2046. }
  2047. // small rows, large cols
  2048. if (small_rows) {
  2049. return {get_fa_num_small_rows(FA_COOPMAT2), 32};
  2050. }
  2051. // small cols to reduce register count
  2052. if (ggml_is_quantized(type) || hsk >= 256 || hsv >= 256) {
  2053. if (hsk >= 512 || hsv >= 512) {
  2054. return {32, 32};
  2055. } else {
  2056. return {64, 32};
  2057. }
  2058. }
  2059. return {64, 64};
  2060. }
  2061. static uint32_t fa_align(FaCodePath path, uint32_t hsk, uint32_t hsv, ggml_type type, bool small_rows) {
  2062. return fa_rows_cols(path, hsk, hsv, 0, type, small_rows)[1];
  2063. }
  2064. 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) {
  2065. uint32_t lut_size = 0;
  2066. switch (src0_type) {
  2067. case GGML_TYPE_IQ1_S:
  2068. case GGML_TYPE_IQ1_M:
  2069. lut_size = 2*2048;
  2070. break;
  2071. case GGML_TYPE_IQ2_XXS:
  2072. lut_size = 8*256;
  2073. break;
  2074. case GGML_TYPE_IQ2_XS:
  2075. lut_size = 8*512;
  2076. break;
  2077. case GGML_TYPE_IQ2_S:
  2078. lut_size = 8*1024;
  2079. break;
  2080. case GGML_TYPE_IQ3_XXS:
  2081. lut_size = 4*256;
  2082. break;
  2083. case GGML_TYPE_IQ3_S:
  2084. lut_size = 4*512;
  2085. break;
  2086. case GGML_TYPE_IQ4_NL:
  2087. case GGML_TYPE_IQ4_XS:
  2088. case GGML_TYPE_MXFP4:
  2089. lut_size = 4*16;
  2090. break;
  2091. default:
  2092. break;
  2093. }
  2094. // Needs to be kept up to date on shader changes
  2095. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  2096. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  2097. const uint32_t warps = warptile[0] / warptile[10];
  2098. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  2099. const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0;
  2100. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  2101. const uint32_t ballots_sh = mul_mat_id ? (warps * 4 * sizeof(uint32_t)) : 0;
  2102. const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size + ballots_sh;
  2103. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  2104. VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), "
  2105. "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported);
  2106. return supported;
  2107. }
  2108. struct GpuPipelineConfig {
  2109. // GPU architecture identifier.
  2110. // Example: vk_device_architecture::AMD_GCN
  2111. vk_device_architecture arch;
  2112. // Mapping of pipeline names to their specific subgroup sizes.
  2113. // Example: {"soft_max_f32", 64}
  2114. std::unordered_map<std::string, uint32_t> pipelines;
  2115. // Default subgroup size for this GPU.
  2116. // Defaults to 0 if not explicitly provided.
  2117. uint32_t default_subgroup_size = 0;
  2118. };
  2119. // Pipeline configuration for RDNA1 GPUs.
  2120. static const std::unordered_map<std::string, uint32_t> rdna1_pipelines = {
  2121. {"soft_max", 64}, {"im2col", 64},
  2122. {"argmax", 64}, {"mul_mat_vec", 64},
  2123. {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32}
  2124. };
  2125. // Pipeline configuration for RDNA2 GPUs.
  2126. static const std::unordered_map<std::string, uint32_t> rdna2_pipelines = {
  2127. {"soft_max", 64}, {"im2col", 64},
  2128. };
  2129. static constexpr uint32_t RDNA_DEFAULT_SUBGROUP_SIZE = 32;
  2130. // Define configurations for different GPUs.
  2131. static std::vector<GpuPipelineConfig> gpu_pipeline_configs = {
  2132. {
  2133. vk_device_architecture::AMD_RDNA1,
  2134. {
  2135. rdna1_pipelines,
  2136. },
  2137. RDNA_DEFAULT_SUBGROUP_SIZE
  2138. },
  2139. {
  2140. vk_device_architecture::AMD_RDNA2,
  2141. {
  2142. rdna2_pipelines,
  2143. },
  2144. RDNA_DEFAULT_SUBGROUP_SIZE
  2145. },
  2146. };
  2147. static uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) {
  2148. for (const auto &config : gpu_pipeline_configs) {
  2149. if (config.arch == arch) {
  2150. auto pipIt = config.pipelines.find(pipeline_name);
  2151. if (pipIt != config.pipelines.end()) {
  2152. return pipIt->second;
  2153. }
  2154. std::vector<std::pair<std::string, uint32_t>> sorted_pipelines(config.pipelines.begin(), config.pipelines.end());
  2155. std::sort(sorted_pipelines.begin(), sorted_pipelines.end(),
  2156. [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
  2157. for (const auto &entry : sorted_pipelines) {
  2158. if (pipeline_name.find(entry.first) != std::string::npos) {
  2159. return entry.second;
  2160. }
  2161. }
  2162. return config.default_subgroup_size;
  2163. }
  2164. }
  2165. return 0; // If no matching configuration is found
  2166. }
  2167. static void ggml_vk_load_shaders(vk_device& device) {
  2168. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  2169. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  2170. // some shaders have a minimum subgroup size
  2171. const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u);
  2172. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  2173. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  2174. 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;
  2175. const uint32_t mul_mat_subgroup_size_8 = std::max(mul_mat_subgroup_size, 8u);
  2176. const uint32_t mul_mat_subgroup_size_16 = std::max(mul_mat_subgroup_size, 16u);
  2177. const uint32_t mul_mat_subgroup_size_32 = std::max(mul_mat_subgroup_size, 32u);
  2178. const bool subgroup_min_size_16 = (!device->subgroup_size_control && device->subgroup_size >= 16) ||
  2179. (device->subgroup_size_control && device->subgroup_max_size >= 16);
  2180. // mulmat
  2181. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  2182. l_warptile_id, m_warptile_id, s_warptile_id,
  2183. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  2184. l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int,
  2185. l_warptile_mmq_int_k, m_warptile_mmq_int_k, s_warptile_mmq_int_k,
  2186. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  2187. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid,
  2188. l_warptile_mmqid_int, m_warptile_mmqid_int, s_warptile_mmqid_int,
  2189. l_warptile_mmqid_int_k, m_warptile_mmqid_int_k, s_warptile_mmqid_int_k;
  2190. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  2191. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  2192. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  2193. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  2194. uint32_t l_align, m_align, s_align;
  2195. if (device->coopmat2) {
  2196. // spec constants and tile sizes for non-quant matmul/matmul_id
  2197. l_warptile = { 256, 128, 256, 64, 1 };
  2198. m_warptile = { 256, 128, 128, 64, 0 };
  2199. s_warptile = { 128, 64, 64, 64, 0 };
  2200. l_wg_denoms = {128, 256, 1 };
  2201. m_wg_denoms = {128, 128, 1 };
  2202. s_wg_denoms = { 64, 64, 1 };
  2203. // spec constants and tile sizes for quant matmul (non-Qi_K)
  2204. l_warptile_mmq = { 256, 128, 256, 64, 1 };
  2205. m_warptile_mmq = { 256, 128, 128, 64, 1 };
  2206. s_warptile_mmq = { 256, 32, 64, 128, 0 };
  2207. l_mmq_wg_denoms = { 128, 256, 1 };
  2208. m_mmq_wg_denoms = { 128, 128, 1 };
  2209. s_mmq_wg_denoms = { 32, 64, 1 };
  2210. // spec constants and tile sizes for quant matmul (Qi_K)
  2211. l_warptile_mmq_k = { 256, 128, 256, 64, 1 };
  2212. m_warptile_mmq_k = { 256, 128, 128, 64, 1 };
  2213. s_warptile_mmq_k = { 256, 32, 64, 128, 0 };
  2214. l_mmq_wg_denoms_k = { 128, 256, 1 };
  2215. m_mmq_wg_denoms_k = { 128, 128, 1 };
  2216. s_mmq_wg_denoms_k = { 32, 64, 1 };
  2217. // spec constants and tile sizes for quant matmul_id
  2218. l_warptile_mmqid = { 256, 128, 128, 16, 1, device->subgroup_size };
  2219. m_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2220. s_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2221. l_mmqid_wg_denoms = { 128, 128, 1 };
  2222. m_mmqid_wg_denoms = { 128, 64, 1 };
  2223. s_mmqid_wg_denoms = { 128, 64, 1 };
  2224. l_align = 128;
  2225. m_align = 64;
  2226. s_align = 32;
  2227. } else {
  2228. // Matrix cores require different warp group sizes
  2229. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  2230. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  2231. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  2232. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  2233. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  2234. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  2235. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  2236. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  2237. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  2238. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2239. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2240. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2241. l_warptile_mmq = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2242. m_warptile_mmq = { 128, 64, 64, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2243. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2244. // Integer MMQ has a smaller shared memory profile, but heavier register use
  2245. l_warptile_mmq_int = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2246. m_warptile_mmq_int = { 128, 64, 64, 32, subgroup_size_8, 32, 2, 2, 2, 1, subgroup_size_8 };
  2247. s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, subgroup_size_8 };
  2248. // K-quants use even more registers, mitigate by setting WMITER to 1
  2249. l_warptile_mmq_int_k = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 1, 4, 4, 1, subgroup_size_8 };
  2250. m_warptile_mmq_int_k = { 128, 64, 64, 32, subgroup_size_8, 32, 1, 2, 2, 1, subgroup_size_8 };
  2251. s_warptile_mmq_int_k = { subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, subgroup_size_8 };
  2252. 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 };
  2253. 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 };
  2254. 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 };
  2255. 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 };
  2256. 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 };
  2257. 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 };
  2258. l_warptile_mmqid_int = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, 4, 4, 1, mul_mat_subgroup_size_8 };
  2259. m_warptile_mmqid_int = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, 2, 2, 1, mul_mat_subgroup_size_8 };
  2260. s_warptile_mmqid_int = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, mul_mat_subgroup_size_8 };
  2261. 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 };
  2262. m_warptile_mmqid_int_k = { 128, 64, 64, 32, mul_mat_subgroup_size_16, 32, 1, 2, 2, 1, mul_mat_subgroup_size_16 };
  2263. s_warptile_mmqid_int_k = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, mul_mat_subgroup_size_16 };
  2264. // chip specific tuning
  2265. if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) {
  2266. m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2267. m_warptile_mmqid = m_warptile_mmqid_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2268. }
  2269. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  2270. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  2271. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  2272. l_align = 128;
  2273. m_align = 64;
  2274. s_align = 32;
  2275. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  2276. ggml_type t = (ggml_type)i;
  2277. // Disable medium and large matrix multiplication if not enough shared memory is available
  2278. // Check mmq warptiles as the largest configuration
  2279. // Throw an error if not enough for any matrix multiplication is available
  2280. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) {
  2281. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  2282. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  2283. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) {
  2284. device->mul_mat_m[i] = false;
  2285. device->mul_mat_l[i] = false;
  2286. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) {
  2287. device->mul_mat_l[i] = false;
  2288. }
  2289. // Disable mul_mat_id if not enough shared memory is available
  2290. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmqid, true, t)) {
  2291. device->mul_mat_id_s[i] = false;
  2292. device->mul_mat_id_m[i] = false;
  2293. device->mul_mat_id_l[i] = false;
  2294. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmqid, true, t)) {
  2295. device->mul_mat_id_m[i] = false;
  2296. device->mul_mat_id_l[i] = false;
  2297. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmqid, true, t)) {
  2298. device->mul_mat_id_l[i] = false;
  2299. }
  2300. }
  2301. }
  2302. if (!device->pipeline_matmul_f32) {
  2303. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2304. }
  2305. if (!device->pipeline_matmul_f32_f16) {
  2306. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  2307. }
  2308. if (!device->pipeline_matmul_id_f32) {
  2309. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2310. }
  2311. if (!device->pipeline_matmul_bf16) {
  2312. device->pipeline_matmul_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2313. }
  2314. if (!device->pipeline_matmul_id_bf16) {
  2315. device->pipeline_matmul_id_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2316. }
  2317. std::vector<std::future<void>> compiles;
  2318. 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,
  2319. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2320. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2321. if (!require_full_subgroups && required_subgroup_size == 0) {
  2322. required_subgroup_size = get_subgroup_size(name, device->architecture);
  2323. }
  2324. if (!pipeline) {
  2325. pipeline = std::make_shared<vk_pipeline_struct>();
  2326. }
  2327. if (!pipeline->initialized) {
  2328. pipeline->name = name;
  2329. pipeline->parameter_count = parameter_count;
  2330. pipeline->push_constant_size = push_constant_size;
  2331. pipeline->wg_denoms = wg_denoms;
  2332. pipeline->align = align;
  2333. pipeline->initialized = true;
  2334. }
  2335. if (!pipeline->needed || pipeline->compiled) {
  2336. return;
  2337. }
  2338. // TODO: We're no longer benefitting from the async compiles (shaders are
  2339. // compiled individually, as needed) and this complexity can be removed.
  2340. {
  2341. // wait until fewer than N compiles are in progress
  2342. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  2343. std::unique_lock<std::mutex> guard(compile_count_mutex);
  2344. while (compile_count >= N) {
  2345. compile_count_cond.wait(guard);
  2346. }
  2347. compile_count++;
  2348. }
  2349. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  2350. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  2351. };
  2352. 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,
  2353. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2354. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2355. return ggml_vk_create_pipeline(device, pipeline, name.c_str(), spv_size, spv_data, entrypoint,
  2356. parameter_count, push_constant_size, wg_denoms, specialization_constants,
  2357. align, disable_robustness, require_full_subgroups, required_subgroup_size);
  2358. };
  2359. 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> {
  2360. return {fa_rows_cols(path, hsk, hsv, clamp, type, small_rows)[0], 1, 1};
  2361. };
  2362. 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> {
  2363. // For large number of rows, 128 invocations seems to work best.
  2364. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  2365. // can't use 256 for D==80.
  2366. // For scalar, use 128 (arbitrary)
  2367. // The same D_split value is used for both HSK and HSV, so just base it on the union of the LSBs.
  2368. const uint32_t D = (hsk|hsv);
  2369. uint32_t wg_size = (path == FA_SCALAR || path == FA_COOPMAT1)
  2370. ? scalar_flash_attention_workgroup_size
  2371. : ((small_rows && (D % 32) == 0) ? 256 : 128);
  2372. auto rows_cols = fa_rows_cols(path, hsk, hsv, clamp, type, small_rows);
  2373. // D_split can't be larger than a subgroup because we use subgroupShuffle to reduce it.
  2374. // D_split can't be larger than the LSB of D divided by 4 due to vectorization in the shader.
  2375. const uint32_t D_lsb = D ^ (D & (D-1));
  2376. uint32_t D_split = std::min(std::min(device->subgroup_size, 8u), D_lsb / 4);
  2377. return {wg_size, rows_cols[0], rows_cols[1], hsk, hsv, clamp, D_split};
  2378. };
  2379. #define CREATE_FA(TYPE, NAMELC, FAPATH, SUFFIX) \
  2380. for (auto &fa : device->pipeline_flash_attn_f32_f16[TYPE]) { \
  2381. uint32_t HSK = fa.first.HSK; \
  2382. uint32_t HSV = fa.first.HSV; \
  2383. bool small_rows = fa.first.small_rows; \
  2384. FaCodePath path = fa.first.path; \
  2385. bool aligned = fa.first.aligned; \
  2386. bool f32acc = fa.first.f32acc; \
  2387. if (path == FAPATH) { \
  2388. if (aligned) { \
  2389. if (f32acc) { \
  2390. 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, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2391. } else { \
  2392. 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, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2393. } \
  2394. } else { \
  2395. if (f32acc) { \
  2396. 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, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2397. } else { \
  2398. 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, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2399. } \
  2400. } \
  2401. } \
  2402. }
  2403. CREATE_FA(GGML_TYPE_F32, f32, FA_SCALAR, )
  2404. CREATE_FA(GGML_TYPE_F16, f16, FA_SCALAR, )
  2405. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_SCALAR, )
  2406. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_SCALAR, )
  2407. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2408. if (device->coopmat1_fa_support) {
  2409. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT1, _cm1)
  2410. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT1, _cm1)
  2411. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT1, _cm1)
  2412. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT1, _cm1)
  2413. }
  2414. #endif
  2415. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2416. if (device->coopmat2) {
  2417. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT2, _cm2)
  2418. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT2, _cm2)
  2419. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT2, _cm2)
  2420. CREATE_FA(GGML_TYPE_Q4_1, q4_1, FA_COOPMAT2, _cm2)
  2421. CREATE_FA(GGML_TYPE_Q5_0, q5_0, FA_COOPMAT2, _cm2)
  2422. CREATE_FA(GGML_TYPE_Q5_1, q5_1, FA_COOPMAT2, _cm2)
  2423. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT2, _cm2)
  2424. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl, FA_COOPMAT2, _cm2)
  2425. }
  2426. #endif
  2427. #undef CREATE_FA
  2428. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2429. if (device->coopmat2) {
  2430. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2431. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2432. 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); \
  2433. 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); \
  2434. 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); \
  2435. 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); \
  2436. 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); \
  2437. 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); \
  2438. // Create 2 variants, {f16,f32} accumulator
  2439. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2440. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2441. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2442. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2443. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2444. if (device->coopmat_bf16_support) {
  2445. CREATE_MM(pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2446. }
  2447. #endif
  2448. 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)
  2449. 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)
  2450. 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)
  2451. 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)
  2452. 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)
  2453. 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)
  2454. 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)
  2455. 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)
  2456. 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)
  2457. 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)
  2458. 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)
  2459. 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)
  2460. 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)
  2461. 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)
  2462. 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)
  2463. 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)
  2464. 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)
  2465. 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)
  2466. 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)
  2467. 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)
  2468. GGML_ASSERT(device->subgroup_ballot);
  2469. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2470. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2471. if (device->coopmat_bf16_support) {
  2472. CREATE_MM(pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2473. }
  2474. #endif
  2475. 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)
  2476. 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)
  2477. 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)
  2478. 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)
  2479. 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)
  2480. 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)
  2481. 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)
  2482. 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)
  2483. 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)
  2484. 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)
  2485. 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)
  2486. 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)
  2487. 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)
  2488. 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)
  2489. 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)
  2490. 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)
  2491. 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)
  2492. 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)
  2493. 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)
  2494. 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)
  2495. #undef CREATE_MM
  2496. #undef CREATE_MM2
  2497. } else
  2498. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2499. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2500. if (device->coopmat_support) {
  2501. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2502. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2503. if (device->mul_mat ## ID ## _l[TYPE]) \
  2504. 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); \
  2505. if (device->mul_mat ## ID ## _m[TYPE]) \
  2506. 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); \
  2507. if (device->mul_mat ## ID ## _s[TYPE]) \
  2508. 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); \
  2509. if (device->mul_mat ## ID ## _l[TYPE]) \
  2510. 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); \
  2511. if (device->mul_mat ## ID ## _m[TYPE]) \
  2512. 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); \
  2513. if (device->mul_mat ## ID ## _s[TYPE]) \
  2514. 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); \
  2515. // Create 2 variants, {f16,f32} accumulator
  2516. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2517. if (device->coopmat_acc_f16_support) { \
  2518. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2519. } \
  2520. if (device->coopmat_acc_f32_support) { \
  2521. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2522. } \
  2523. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2524. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2525. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2526. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2527. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2528. if (device->coopmat_bf16_support) {
  2529. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, )
  2530. }
  2531. #endif
  2532. if (device->coopmat_acc_f16_support) {
  2533. 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, );
  2534. 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, );
  2535. 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, );
  2536. 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, );
  2537. 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, );
  2538. 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, );
  2539. 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, );
  2540. 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, );
  2541. 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, );
  2542. 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, );
  2543. 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, );
  2544. 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, );
  2545. 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, );
  2546. 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, );
  2547. 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, );
  2548. 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, );
  2549. 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, );
  2550. 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, );
  2551. 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, );
  2552. 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, );
  2553. } else {
  2554. 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, );
  2555. 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, );
  2556. 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, );
  2557. 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, );
  2558. 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, );
  2559. 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, );
  2560. 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, );
  2561. 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, );
  2562. 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, );
  2563. 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, );
  2564. 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, );
  2565. 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, );
  2566. 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, );
  2567. 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, );
  2568. 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, );
  2569. 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, );
  2570. 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, );
  2571. 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, );
  2572. 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, );
  2573. 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, );
  2574. }
  2575. GGML_ASSERT(device->subgroup_ballot);
  2576. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2577. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2578. 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);
  2579. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2580. if (device->coopmat_bf16_support) {
  2581. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2582. }
  2583. #endif
  2584. 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);
  2585. 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);
  2586. 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);
  2587. 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);
  2588. 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);
  2589. 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);
  2590. 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);
  2591. 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);
  2592. 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);
  2593. 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);
  2594. 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);
  2595. 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);
  2596. 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);
  2597. 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);
  2598. 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);
  2599. 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);
  2600. 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);
  2601. 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);
  2602. 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);
  2603. 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);
  2604. #undef CREATE_MM2
  2605. #undef CREATE_MM
  2606. } else
  2607. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2608. if (device->fp16) {
  2609. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2610. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2611. if (device->mul_mat ## ID ## _l[TYPE]) \
  2612. 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); \
  2613. if (device->mul_mat ## ID ## _m[TYPE]) \
  2614. 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); \
  2615. if (device->mul_mat ## ID ## _s[TYPE]) \
  2616. 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); \
  2617. if (device->mul_mat ## ID ## _l[TYPE]) \
  2618. 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); \
  2619. if (device->mul_mat ## ID ## _m[TYPE]) \
  2620. 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); \
  2621. if (device->mul_mat ## ID ## _s[TYPE]) \
  2622. 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); \
  2623. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2624. if (device->mul_mat ## ID ## _l[TYPE]) { \
  2625. 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); \
  2626. } \
  2627. if (device->mul_mat ## ID ## _m[TYPE]) { \
  2628. 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); \
  2629. } \
  2630. if (device->mul_mat ## ID ## _s[TYPE]) { \
  2631. 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); \
  2632. } \
  2633. // Create 2 variants, {f16,f32} accumulator
  2634. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2635. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2636. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2637. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2638. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2639. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2640. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2641. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2642. 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);
  2643. 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);
  2644. 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);
  2645. 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);
  2646. 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);
  2647. 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);
  2648. 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);
  2649. 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);
  2650. 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);
  2651. 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);
  2652. 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);
  2653. 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);
  2654. 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);
  2655. 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);
  2656. 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);
  2657. 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);
  2658. 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);
  2659. 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);
  2660. 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);
  2661. 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);
  2662. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2663. if (device->integer_dot_product) {
  2664. 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);
  2665. 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);
  2666. 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);
  2667. 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);
  2668. 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);
  2669. 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);
  2670. 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);
  2671. 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);
  2672. 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);
  2673. 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);
  2674. 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);
  2675. }
  2676. #endif
  2677. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2678. 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);
  2679. 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);
  2680. 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);
  2681. 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);
  2682. 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);
  2683. 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);
  2684. 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);
  2685. 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);
  2686. 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);
  2687. 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);
  2688. 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);
  2689. 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);
  2690. 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);
  2691. 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);
  2692. 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);
  2693. 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);
  2694. 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);
  2695. 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);
  2696. 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);
  2697. 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);
  2698. 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);
  2699. 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);
  2700. 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);
  2701. 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);
  2702. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2703. if (device->integer_dot_product) {
  2704. 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);
  2705. 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);
  2706. 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);
  2707. 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);
  2708. 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);
  2709. 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);
  2710. 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);
  2711. 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);
  2712. 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);
  2713. 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);
  2714. 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);
  2715. }
  2716. #endif
  2717. } else {
  2718. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2719. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2720. 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);
  2721. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2722. 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);
  2723. 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);
  2724. 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);
  2725. 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);
  2726. 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);
  2727. 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);
  2728. 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);
  2729. 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);
  2730. 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);
  2731. 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);
  2732. 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);
  2733. 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);
  2734. 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);
  2735. 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);
  2736. 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);
  2737. 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);
  2738. 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);
  2739. 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);
  2740. 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);
  2741. 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);
  2742. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2743. if (device->integer_dot_product) {
  2744. 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);
  2745. 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);
  2746. 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);
  2747. 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);
  2748. 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);
  2749. 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);
  2750. 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);
  2751. 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);
  2752. 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);
  2753. 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);
  2754. 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);
  2755. }
  2756. #endif
  2757. }
  2758. #undef CREATE_MM2
  2759. #undef CREATE_MMQ
  2760. #undef CREATE_MM
  2761. } else {
  2762. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2763. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2764. if (device->mul_mat ## ID ## _l[TYPE]) \
  2765. 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); \
  2766. if (device->mul_mat ## ID ## _m[TYPE]) \
  2767. 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); \
  2768. if (device->mul_mat ## ID ## _s[TYPE]) \
  2769. 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); \
  2770. if (device->mul_mat ## ID ## _l[TYPE]) \
  2771. 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); \
  2772. if (device->mul_mat ## ID ## _m[TYPE]) \
  2773. 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); \
  2774. if (device->mul_mat ## ID ## _s[TYPE]) \
  2775. 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); \
  2776. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2777. if (device->mul_mat ## ID ## _l[TYPE]) \
  2778. 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); \
  2779. if (device->mul_mat ## ID ## _m[TYPE]) \
  2780. 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); \
  2781. if (device->mul_mat ## ID ## _s[TYPE]) \
  2782. 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); \
  2783. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2784. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2785. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2786. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2787. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2788. 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);
  2789. 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);
  2790. 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);
  2791. 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);
  2792. 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);
  2793. 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);
  2794. 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);
  2795. 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);
  2796. 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);
  2797. 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);
  2798. 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);
  2799. 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);
  2800. 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);
  2801. 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);
  2802. 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);
  2803. 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);
  2804. 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);
  2805. 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);
  2806. 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);
  2807. 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);
  2808. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2809. if (device->integer_dot_product) {
  2810. 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, );
  2811. 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, );
  2812. 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, );
  2813. 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, );
  2814. 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, );
  2815. 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, );
  2816. 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, );
  2817. 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, );
  2818. 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, );
  2819. 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, );
  2820. }
  2821. #endif
  2822. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2823. 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);
  2824. 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);
  2825. 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);
  2826. 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);
  2827. 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);
  2828. 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);
  2829. 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);
  2830. 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);
  2831. 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);
  2832. 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);
  2833. 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);
  2834. 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);
  2835. 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);
  2836. 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);
  2837. 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);
  2838. 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);
  2839. 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);
  2840. 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);
  2841. 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);
  2842. 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);
  2843. 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);
  2844. 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);
  2845. 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);
  2846. 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);
  2847. } else {
  2848. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2849. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2850. 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);
  2851. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2852. 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);
  2853. 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);
  2854. 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);
  2855. 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);
  2856. 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);
  2857. 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);
  2858. 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);
  2859. 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);
  2860. 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);
  2861. 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);
  2862. 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);
  2863. 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);
  2864. 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);
  2865. 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);
  2866. 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);
  2867. 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);
  2868. 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);
  2869. 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);
  2870. 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);
  2871. 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);
  2872. }
  2873. }
  2874. // reusing CREATE_MM from the fp32 path
  2875. if ((device->coopmat2 || device->coopmat_support)
  2876. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2877. && !device->coopmat_bf16_support
  2878. #endif
  2879. ) {
  2880. // use scalar tile sizes
  2881. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2882. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, 4, 2, 1, subgroup_size_8 };
  2883. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, 2, 2, 1, subgroup_size_8 };
  2884. l_wg_denoms = {128, 128, 1 };
  2885. m_wg_denoms = { 64, 64, 1 };
  2886. s_wg_denoms = { 32, 32, 1 };
  2887. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2888. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2889. }
  2890. #undef CREATE_MM
  2891. // mul mat vec
  2892. // the number of rows computed per shader depends on GPU model and quant
  2893. uint32_t rm_stdq = 1;
  2894. uint32_t rm_kq = 2;
  2895. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  2896. if (device->architecture == AMD_GCN) {
  2897. rm_stdq = 2;
  2898. rm_kq = 4;
  2899. }
  2900. } else if (device->vendor_id == VK_VENDOR_ID_INTEL)
  2901. rm_stdq = 2;
  2902. uint32_t rm_iq = 2 * rm_kq;
  2903. const bool use_subgroups = device->subgroup_arithmetic && device->architecture != vk_device_architecture::AMD_GCN;
  2904. // Ensure a subgroup size >= 16 is available
  2905. const bool use_subgroups16 = use_subgroups && subgroup_min_size_16;
  2906. 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;
  2907. const uint32_t subgroup_size16 = std::max(subgroup_size, 16u);
  2908. const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0;
  2909. const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0;
  2910. for (uint32_t w = 0; w < DMMV_WG_SIZE_COUNT; ++w) {
  2911. const uint32_t wg_size_subgroup = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size : (subgroup_size * 4);
  2912. const uint32_t wg_size_subgroup16 = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size16 : (subgroup_size16 * 4);
  2913. const shader_reduction_mode reduc = (use_subgroups && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  2914. (use_subgroups && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  2915. SHADER_REDUCTION_MODE_SHMEM;
  2916. const shader_reduction_mode reduc16 = (use_subgroups16 && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  2917. (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  2918. SHADER_REDUCTION_MODE_SHMEM;
  2919. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  2920. 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", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2921. 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", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2922. 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", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2923. 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", 4, 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);
  2924. 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", 4, 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);
  2925. 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", 4, 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);
  2926. 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", 4, 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);
  2927. 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", 4, 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);
  2928. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2929. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2930. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2931. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2932. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2933. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2934. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2935. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2936. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2937. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2938. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2939. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2940. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2941. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2942. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2943. 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", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2944. 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", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2945. 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", 4, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2946. 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", 4, 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);
  2947. 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", 4, 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);
  2948. 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", 4, 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);
  2949. 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", 4, 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);
  2950. 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", 4, 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);
  2951. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2952. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2953. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2954. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2955. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2956. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2957. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2958. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2959. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2960. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2961. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2962. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2963. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2964. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2965. 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", 4, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2966. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2967. if (device->integer_dot_product) {
  2968. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  2969. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  2970. 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", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2971. 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", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2972. 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", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2973. 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", 4, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2974. 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", 4, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2975. }
  2976. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  2977. }
  2978. }
  2979. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_F32 ], "mul_mat_vec_id_f32_f32", mul_mat_vec_id_f32_f32_len, mul_mat_vec_id_f32_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  2980. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_F16 ], "mul_mat_vec_id_f16_f32", mul_mat_vec_id_f16_f32_len, mul_mat_vec_id_f16_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  2981. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_BF16], "mul_mat_vec_id_bf16_f32", mul_mat_vec_id_bf16_f32_len, mul_mat_vec_id_bf16_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  2982. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q4_0], "mul_mat_vec_id_q4_0_f32", mul_mat_vec_id_q4_0_f32_len, mul_mat_vec_id_q4_0_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2983. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q4_1], "mul_mat_vec_id_q4_1_f32", mul_mat_vec_id_q4_1_f32_len, mul_mat_vec_id_q4_1_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2984. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q5_0], "mul_mat_vec_id_q5_0_f32", mul_mat_vec_id_q5_0_f32_len, mul_mat_vec_id_q5_0_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2985. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q5_1], "mul_mat_vec_id_q5_1_f32", mul_mat_vec_id_q5_1_f32_len, mul_mat_vec_id_q5_1_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2986. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q8_0], "mul_mat_vec_id_q8_0_f32", mul_mat_vec_id_q8_0_f32_len, mul_mat_vec_id_q8_0_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq, 1, 1}, {device->subgroup_size, 1*rm_stdq}, 1, true);
  2987. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q2_K], "mul_mat_vec_id_q2_k_f32", mul_mat_vec_id_q2_k_f32_len, mul_mat_vec_id_q2_k_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2988. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q3_K], "mul_mat_vec_id_q3_k_f32", mul_mat_vec_id_q3_k_f32_len, mul_mat_vec_id_q3_k_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2989. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q4_K], "mul_mat_vec_id_q4_k_f32", mul_mat_vec_id_q4_k_f32_len, mul_mat_vec_id_q4_k_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2990. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q5_K], "mul_mat_vec_id_q5_k_f32", mul_mat_vec_id_q5_k_f32_len, mul_mat_vec_id_q5_k_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2991. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_Q6_K], "mul_mat_vec_id_q6_k_f32", mul_mat_vec_id_q6_k_f32_len, mul_mat_vec_id_q6_k_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2992. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ1_S], "mul_mat_vec_id_iq1_s_f32", mul_mat_vec_id_iq1_s_f32_len, mul_mat_vec_id_iq1_s_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2993. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ1_M], "mul_mat_vec_id_iq1_m_f32", mul_mat_vec_id_iq1_m_f32_len, mul_mat_vec_id_iq1_m_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2994. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ2_XXS], "mul_mat_vec_id_iq2_xxs_f32", mul_mat_vec_id_iq2_xxs_f32_len, mul_mat_vec_id_iq2_xxs_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2995. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ2_XS], "mul_mat_vec_id_iq2_xs_f32", mul_mat_vec_id_iq2_xs_f32_len, mul_mat_vec_id_iq2_xs_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2996. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ2_S], "mul_mat_vec_id_iq2_s_f32", mul_mat_vec_id_iq2_s_f32_len, mul_mat_vec_id_iq2_s_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2997. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ3_XXS], "mul_mat_vec_id_iq3_xxs_f32", mul_mat_vec_id_iq3_xxs_f32_len, mul_mat_vec_id_iq3_xxs_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2998. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ3_S], "mul_mat_vec_id_iq3_s_f32", mul_mat_vec_id_iq3_s_f32_len, mul_mat_vec_id_iq3_s_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2999. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ4_XS], "mul_mat_vec_id_iq4_xs_f32", mul_mat_vec_id_iq4_xs_f32_len, mul_mat_vec_id_iq4_xs_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3000. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ4_NL], "mul_mat_vec_id_iq4_nl_f32", mul_mat_vec_id_iq4_nl_f32_len, mul_mat_vec_id_iq4_nl_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3001. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_f32", mul_mat_vec_id_mxfp4_f32_len, mul_mat_vec_id_mxfp4_f32_data, "main", 5, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3002. // dequant shaders
  3003. 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);
  3004. 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);
  3005. 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);
  3006. 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);
  3007. 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);
  3008. 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);
  3009. 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);
  3010. 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);
  3011. 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);
  3012. 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);
  3013. 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);
  3014. 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);
  3015. 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);
  3016. 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);
  3017. 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);
  3018. 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);
  3019. 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);
  3020. 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);
  3021. 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);
  3022. 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);
  3023. 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);
  3024. // get_rows
  3025. 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);
  3026. 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);
  3027. 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);
  3028. 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);
  3029. 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);
  3030. 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);
  3031. 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);
  3032. 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);
  3033. 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);
  3034. 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);
  3035. 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);
  3036. 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);
  3037. 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);
  3038. 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);
  3039. 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);
  3040. 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);
  3041. 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);
  3042. 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);
  3043. 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);
  3044. 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);
  3045. 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);
  3046. 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);
  3047. 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);
  3048. 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);
  3049. 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);
  3050. 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);
  3051. 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);
  3052. 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);
  3053. 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);
  3054. 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);
  3055. 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);
  3056. 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);
  3057. 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);
  3058. 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);
  3059. 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);
  3060. 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);
  3061. 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);
  3062. 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);
  3063. 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);
  3064. 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);
  3065. 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);
  3066. 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);
  3067. 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);
  3068. 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);
  3069. 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);
  3070. 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);
  3071. 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);
  3072. 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);
  3073. if (device->subgroup_clustered && device->subgroup_require_full_support) {
  3074. 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);
  3075. } else {
  3076. 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);
  3077. }
  3078. for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) {
  3079. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3080. 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", 4, 7 * sizeof(uint32_t), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true, true);
  3081. } else {
  3082. 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", 4, 7 * sizeof(uint32_t), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true);
  3083. }
  3084. }
  3085. 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", 4, 13 * sizeof(uint32_t), {1, 1, 1}, {}, 1);
  3086. 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);
  3087. 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);
  3088. 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);
  3089. 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);
  3090. 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);
  3091. 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);
  3092. if (device->float_controls_rte_fp16 &&
  3093. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= device->properties.limits.maxPushConstantsSize) {
  3094. 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);
  3095. 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);
  3096. }
  3097. 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);
  3098. 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);
  3099. 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);
  3100. 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);
  3101. 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);
  3102. 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);
  3103. 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);
  3104. 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);
  3105. 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);
  3106. 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);
  3107. 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);
  3108. 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);
  3109. 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);
  3110. 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);
  3111. 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);
  3112. 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);
  3113. if (device->float_controls_rte_fp16) {
  3114. 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);
  3115. 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);
  3116. 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);
  3117. 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);
  3118. 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);
  3119. 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);
  3120. } else {
  3121. 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);
  3122. 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);
  3123. 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);
  3124. 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);
  3125. 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);
  3126. 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);
  3127. }
  3128. #define SET_ROWS(itype, rte) \
  3129. 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); \
  3130. 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); \
  3131. 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); \
  3132. 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); \
  3133. 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); \
  3134. 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); \
  3135. 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); \
  3136. 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); \
  3137. 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);
  3138. if (device->float_controls_rte_fp16) {
  3139. SET_ROWS(_i32, _rte)
  3140. SET_ROWS(_i64, _rte)
  3141. } else {
  3142. SET_ROWS(_i32, )
  3143. SET_ROWS(_i64, )
  3144. }
  3145. #undef SET_ROWS
  3146. 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);
  3147. 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);
  3148. 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);
  3149. 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);
  3150. 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);
  3151. 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);
  3152. auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) {
  3153. std::string s;
  3154. s += std::string(src0_f16 ? "_f16" : "_f32");
  3155. s += std::string(src1_f16 ? "_f16" : "_f32");
  3156. s += std::string(dst_f16 ? "_f16" : "_f32");
  3157. return s;
  3158. };
  3159. bool rte = device->float_controls_rte_fp16;
  3160. #define CREATE_BINARY(name, namemod, spec, bindings) \
  3161. for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \
  3162. ggml_vk_create_pipeline2(device, device->pipeline_ ## name ## namemod[s0][s1][d], \
  3163. #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d][rte], name ## _data[s0][s1][d][rte], \
  3164. "main", (bindings), sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1);
  3165. CREATE_BINARY(add, , {0}, 4)
  3166. CREATE_BINARY(add, _norepeat, {1}, 4)
  3167. CREATE_BINARY(sub, , {0}, 3)
  3168. CREATE_BINARY(sub, _norepeat, {1}, 3)
  3169. CREATE_BINARY(mul, , {0}, 3)
  3170. CREATE_BINARY(mul, _norepeat, {1}, 3)
  3171. CREATE_BINARY(div, , {0}, 3)
  3172. CREATE_BINARY(div, _norepeat, {1}, 3)
  3173. CREATE_BINARY(add_rms, , {0}, 4)
  3174. CREATE_BINARY(add_rms, _norepeat, {1}, 4)
  3175. #undef CREATE_BINARY
  3176. if (device->multi_add) {
  3177. for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) {
  3178. 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);
  3179. 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);
  3180. }
  3181. }
  3182. 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);
  3183. 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);
  3184. 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);
  3185. 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);
  3186. 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);
  3187. 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);
  3188. 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);
  3189. 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);
  3190. 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);
  3191. 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);
  3192. 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);
  3193. 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);
  3194. 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);
  3195. 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);
  3196. 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);
  3197. 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);
  3198. 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);
  3199. #define CREATE_UNARY(name) \
  3200. 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); \
  3201. 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);
  3202. CREATE_UNARY(gelu)
  3203. CREATE_UNARY(gelu_erf)
  3204. CREATE_UNARY(gelu_quick)
  3205. CREATE_UNARY(silu)
  3206. CREATE_UNARY(relu)
  3207. CREATE_UNARY(tanh)
  3208. CREATE_UNARY(sigmoid)
  3209. CREATE_UNARY(hardsigmoid)
  3210. CREATE_UNARY(hardswish)
  3211. #undef CREATE_UNARY
  3212. #define CREATE_UNARY_RTE(name) \
  3213. if (device->float_controls_rte_fp16) { \
  3214. 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); \
  3215. 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); \
  3216. } else { \
  3217. 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); \
  3218. 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); \
  3219. }
  3220. CREATE_UNARY_RTE(exp)
  3221. #undef CREATE_UNARY_RTE
  3222. #define CREATE_GLU(name) \
  3223. if (device->float_controls_rte_fp16) { \
  3224. 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); \
  3225. 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); \
  3226. } else { \
  3227. 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); \
  3228. 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); \
  3229. }
  3230. CREATE_GLU(geglu)
  3231. CREATE_GLU(reglu)
  3232. CREATE_GLU(swiglu)
  3233. CREATE_GLU(swiglu_oai)
  3234. CREATE_GLU(geglu_erf)
  3235. CREATE_GLU(geglu_quick)
  3236. #undef CREATE_GLU
  3237. 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);
  3238. 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);
  3239. 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);
  3240. 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);
  3241. 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);
  3242. 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);
  3243. 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);
  3244. 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);
  3245. 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);
  3246. 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);
  3247. 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);
  3248. 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);
  3249. if (device->float_controls_rte_fp16) {
  3250. 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);
  3251. 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);
  3252. 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);
  3253. 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);
  3254. 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);
  3255. 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);
  3256. } else {
  3257. 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);
  3258. 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);
  3259. 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);
  3260. 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);
  3261. 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);
  3262. 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);
  3263. }
  3264. for (uint32_t i = 0; i < num_argsort_pipelines; ++i) {
  3265. ggml_vk_create_pipeline2(device, device->pipeline_argsort_f32[i], "argsort_f32_"+std::to_string(i), argsort_f32_len, argsort_f32_data, "main", 2, sizeof(vk_op_argsort_push_constants), {1u<<i, 1, 1}, {1u<<i, i}, 1, true);
  3266. }
  3267. 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);
  3268. 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);
  3269. 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);
  3270. #define IM2COL(bda) \
  3271. 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); \
  3272. 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); \
  3273. if (device->float_controls_rte_fp16) { \
  3274. 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); \
  3275. 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); \
  3276. } else { \
  3277. 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); \
  3278. 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); \
  3279. }
  3280. if (device->shader_int64 && device->buffer_device_address) {
  3281. IM2COL(_bda)
  3282. } else {
  3283. IM2COL()
  3284. }
  3285. 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);
  3286. 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);
  3287. 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);
  3288. 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);
  3289. 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);
  3290. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3291. 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);
  3292. 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);
  3293. } else {
  3294. 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);
  3295. 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);
  3296. }
  3297. 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);
  3298. 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);
  3299. 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);
  3300. // conv2d, conv_transpose_2d
  3301. for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) {
  3302. uint32_t conv2d_WG_SIZE = 256;
  3303. uint32_t conv2d_BS_K = 128;
  3304. uint32_t conv2d_BS_CRS = 16;
  3305. uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices.
  3306. uint32_t conv2d_BS_NPQ = 128;
  3307. uint32_t conv2d_TS_K = 8;
  3308. uint32_t conv2d_SHMEM_PAD = 4;
  3309. bool conv2d_UNROLL = true;
  3310. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3311. if (device->coopmat2) {
  3312. conv2d_SHMEM_PAD = 8; // 8 float16_t
  3313. }
  3314. #endif
  3315. if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3316. conv2d_SHMEM_PAD = 0;
  3317. conv2d_UNROLL = false;
  3318. } else if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3319. conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4;
  3320. }
  3321. switch (s) {
  3322. default:
  3323. case CONV_SHAPE_128x128:
  3324. conv2d_BS_K = conv_shapes_wg_denoms[CONV_SHAPE_128x128][0];
  3325. conv2d_BS_NPQ = conv_shapes_wg_denoms[CONV_SHAPE_128x128][1];
  3326. conv2d_BS_CRS = 16;
  3327. if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != vk_device_architecture::AMD_GCN) {
  3328. conv2d_UNROLL = false;
  3329. }
  3330. break;
  3331. case CONV_SHAPE_64x32:
  3332. conv2d_BS_K = conv_shapes_wg_denoms[CONV_SHAPE_64x32][0];
  3333. conv2d_BS_NPQ = conv_shapes_wg_denoms[CONV_SHAPE_64x32][1];
  3334. conv2d_BS_CRS = 32;
  3335. conv2d_TS_K = 4;
  3336. break;
  3337. case CONV_SHAPE_32x256:
  3338. conv2d_BS_K = conv_shapes_wg_denoms[CONV_SHAPE_32x256][0];
  3339. conv2d_BS_NPQ = conv_shapes_wg_denoms[CONV_SHAPE_32x256][1];
  3340. conv2d_BS_CRS = 16;
  3341. break;
  3342. }
  3343. // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math.
  3344. bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA ||
  3345. device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  3346. bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD ||
  3347. device->architecture == vk_device_architecture::AMD_GCN;
  3348. if (device->subgroup_shuffle &&
  3349. device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316.
  3350. allow_collectives_nv &&
  3351. allow_collectives_amd) {
  3352. use_collectives = 1;
  3353. conv2d_BS_CRS = std::min(
  3354. device->subgroup_size,
  3355. conv2d_BS_CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used.
  3356. }
  3357. uint32_t conv2d_shmem_req =
  3358. (conv2d_BS_K * (conv2d_BS_CRS + conv2d_SHMEM_PAD) + conv2d_BS_CRS * (conv2d_BS_NPQ + conv2d_SHMEM_PAD)) * sizeof(float);
  3359. if (device->properties.limits.maxComputeSharedMemorySize < conv2d_shmem_req) {
  3360. conv2d_BS_CRS = 8;
  3361. if (use_collectives) {
  3362. conv2d_BS_CRS = std::min(device->subgroup_size, conv2d_BS_CRS);
  3363. }
  3364. }
  3365. std::array<uint32_t, 3> wg_denoms = { conv2d_BS_K, conv2d_BS_NPQ, 1 };
  3366. 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 };
  3367. #define CREATE_CONV(name, type_suffix, spv_suffix) \
  3368. for (auto &c : device->pipeline_##name##type_suffix[s]) { \
  3369. const vk_conv2d_pipeline_state &state = c.first; \
  3370. std::vector<uint32_t> spec_constants_cpy = spec_constants; \
  3371. spec_constants_cpy.push_back(state.s0); \
  3372. spec_constants_cpy.push_back(state.s1); \
  3373. spec_constants_cpy.push_back(state.p0); \
  3374. spec_constants_cpy.push_back(state.p1); \
  3375. spec_constants_cpy.push_back(state.d0); \
  3376. spec_constants_cpy.push_back(state.d1); \
  3377. spec_constants_cpy.push_back(state.KW); \
  3378. spec_constants_cpy.push_back(state.KH); \
  3379. ggml_vk_create_pipeline( \
  3380. device, c.second, #name #type_suffix, \
  3381. name##type_suffix##spv_suffix##_len, name##type_suffix##spv_suffix##_data, "main", 3, \
  3382. sizeof(vk_op_##name##_push_constants), wg_denoms, spec_constants_cpy, 1, true, use_collectives); \
  3383. }
  3384. #define CREATE_CONVS(spv_suffix) \
  3385. CREATE_CONV(conv2d, _f32, spv_suffix) \
  3386. CREATE_CONV(conv2d, _f16_f32, spv_suffix) \
  3387. if (device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_conv_transpose_2d_push_constants)) { \
  3388. CREATE_CONV(conv_transpose_2d, _f32, spv_suffix) \
  3389. CREATE_CONV(conv_transpose_2d, _f16_f32, spv_suffix) \
  3390. }
  3391. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3392. if (device->coopmat2) {
  3393. CREATE_CONVS(_cm2)
  3394. } else
  3395. #endif
  3396. if (conv2d_UNROLL) {
  3397. CREATE_CONVS(_unroll)
  3398. } else {
  3399. CREATE_CONVS( )
  3400. }
  3401. #undef CREATE_CONV
  3402. #undef CREATE_CONVS
  3403. }
  3404. 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);
  3405. 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);
  3406. 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);
  3407. 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);
  3408. for (uint32_t i = 0; i < num_topk_moe_pipelines; ++i) {
  3409. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_EARLY_SOFTMAX], "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}, 1, true, true);
  3410. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_EARLY_SOFTMAX_NORM], "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}, 1, true, true);
  3411. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_LATE_SOFTMAX], "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}, 1, true, true);
  3412. }
  3413. for (auto &c : compiles) {
  3414. c.wait();
  3415. }
  3416. }
  3417. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch);
  3418. static vk_device ggml_vk_get_device(size_t idx) {
  3419. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  3420. if (vk_instance.devices[idx] == nullptr) {
  3421. VK_LOG_DEBUG("Initializing new vk_device");
  3422. vk_device device = std::make_shared<vk_device_struct>();
  3423. vk_instance.devices[idx] = device;
  3424. #ifdef GGML_VULKAN_MEMORY_DEBUG
  3425. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  3426. #endif
  3427. if (vk_perf_logger_enabled) {
  3428. device->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  3429. }
  3430. size_t dev_num = vk_instance.device_indices[idx];
  3431. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  3432. if (dev_num >= physical_devices.size()) {
  3433. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3434. throw std::runtime_error("Device not found");
  3435. }
  3436. device->physical_device = physical_devices[dev_num];
  3437. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  3438. device->architecture = get_device_architecture(device->physical_device);
  3439. const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY");
  3440. device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr;
  3441. const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM");
  3442. device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr;
  3443. const char* GGML_VK_ALLOW_SYSMEM_FALLBACK = getenv("GGML_VK_ALLOW_SYSMEM_FALLBACK");
  3444. device->allow_sysmem_fallback = GGML_VK_ALLOW_SYSMEM_FALLBACK != nullptr;
  3445. const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE");
  3446. device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr;
  3447. bool fp16_storage = false;
  3448. bool fp16_compute = false;
  3449. bool maintenance4_support = false;
  3450. bool sm_builtins = false;
  3451. bool amd_shader_core_properties2 = false;
  3452. bool pipeline_robustness = false;
  3453. bool coopmat2_support = false;
  3454. bool pipeline_executable_properties_support = false;
  3455. device->coopmat_support = false;
  3456. device->integer_dot_product = false;
  3457. bool bfloat16_support = false;
  3458. for (const auto& properties : ext_props) {
  3459. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  3460. maintenance4_support = true;
  3461. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3462. fp16_storage = true;
  3463. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3464. fp16_compute = true;
  3465. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  3466. sm_builtins = true;
  3467. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  3468. amd_shader_core_properties2 = true;
  3469. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  3470. pipeline_robustness = true;
  3471. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  3472. device->subgroup_size_control = true;
  3473. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3474. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3475. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3476. device->coopmat_support = true;
  3477. device->coopmat_m = 0;
  3478. device->coopmat_n = 0;
  3479. device->coopmat_k = 0;
  3480. #endif
  3481. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3482. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3483. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3484. coopmat2_support = true;
  3485. #endif
  3486. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3487. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3488. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3489. device->integer_dot_product = true;
  3490. #endif
  3491. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3492. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3493. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3494. bfloat16_support = true;
  3495. #endif
  3496. } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) {
  3497. pipeline_executable_properties_support = true;
  3498. }
  3499. }
  3500. vk::PhysicalDeviceProperties2 props2;
  3501. vk::PhysicalDeviceMaintenance3Properties props3;
  3502. vk::PhysicalDeviceMaintenance4Properties props4;
  3503. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3504. vk::PhysicalDeviceDriverProperties driver_props;
  3505. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  3506. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  3507. vk::PhysicalDeviceVulkan11Properties vk11_props;
  3508. vk::PhysicalDeviceVulkan12Properties vk12_props;
  3509. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  3510. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3511. props2.pNext = &props3;
  3512. props3.pNext = &subgroup_props;
  3513. subgroup_props.pNext = &driver_props;
  3514. driver_props.pNext = &vk11_props;
  3515. vk11_props.pNext = &vk12_props;
  3516. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  3517. if (maintenance4_support) {
  3518. last_struct->pNext = (VkBaseOutStructure *)&props4;
  3519. last_struct = (VkBaseOutStructure *)&props4;
  3520. }
  3521. if (sm_builtins) {
  3522. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  3523. last_struct = (VkBaseOutStructure *)&sm_props;
  3524. }
  3525. if (amd_shader_core_properties2) {
  3526. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3527. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3528. }
  3529. if (device->subgroup_size_control) {
  3530. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  3531. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  3532. }
  3533. #if defined(VK_NV_cooperative_matrix2)
  3534. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  3535. if (coopmat2_support) {
  3536. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  3537. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  3538. }
  3539. #endif
  3540. if (device->integer_dot_product) {
  3541. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3542. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3543. }
  3544. device->physical_device.getProperties2(&props2);
  3545. device->properties = props2.properties;
  3546. device->vendor_id = device->properties.vendorID;
  3547. device->driver_id = driver_props.driverID;
  3548. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  3549. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  3550. device->max_memory_allocation_size = std::stoull(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  3551. } else if (maintenance4_support) {
  3552. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  3553. } else {
  3554. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  3555. }
  3556. const char* GGML_VK_FORCE_MAX_BUFFER_SIZE = getenv("GGML_VK_FORCE_MAX_BUFFER_SIZE");
  3557. if (GGML_VK_FORCE_MAX_BUFFER_SIZE != nullptr) {
  3558. device->max_buffer_size = std::stoull(GGML_VK_FORCE_MAX_BUFFER_SIZE);
  3559. } else if (maintenance4_support) {
  3560. device->max_buffer_size = props4.maxBufferSize;
  3561. } else {
  3562. device->max_buffer_size = device->max_memory_allocation_size;
  3563. }
  3564. const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE");
  3565. if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) {
  3566. device->suballocation_block_size = std::stoull(GGML_VK_SUBALLOCATION_BLOCK_SIZE);
  3567. } else {
  3568. // Limit batching of allocations to 1GB by default to avoid fragmentation issues
  3569. device->suballocation_block_size = 1024*1024*1024;
  3570. }
  3571. device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size);
  3572. device->subgroup_size = subgroup_props.subgroupSize;
  3573. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3574. if (sm_builtins) {
  3575. device->shader_core_count = sm_props.shaderSMCount;
  3576. } else if (amd_shader_core_properties2) {
  3577. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  3578. } else {
  3579. device->shader_core_count = 0;
  3580. }
  3581. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  3582. device->subgroup_arithmetic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3583. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic);
  3584. #ifdef __APPLE__
  3585. // Workaround for subgroup arithmetic failing on MoltenVK with AMD GPUs (issue 15846)
  3586. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3587. device->subgroup_arithmetic = false;
  3588. }
  3589. #endif
  3590. device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3591. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle);
  3592. device->subgroup_clustered = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3593. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eClustered);
  3594. device->subgroup_ballot = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3595. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBallot);
  3596. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  3597. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  3598. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) {
  3599. device->coopmat_support = false;
  3600. }
  3601. device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated;
  3602. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  3603. // Try to find a non-graphics compute queue and transfer-focused queues
  3604. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  3605. 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);
  3606. const float priorities[] = { 1.0f, 1.0f };
  3607. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  3608. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  3609. if (compute_queue_family_index != transfer_queue_family_index) {
  3610. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3611. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  3612. } else if(!device->single_queue) {
  3613. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  3614. } else {
  3615. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3616. }
  3617. vk::DeviceCreateInfo device_create_info;
  3618. std::vector<const char *> device_extensions;
  3619. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  3620. VkPhysicalDeviceFeatures2 device_features2;
  3621. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  3622. device_features2.pNext = nullptr;
  3623. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  3624. VkPhysicalDeviceVulkan11Features vk11_features;
  3625. vk11_features.pNext = nullptr;
  3626. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  3627. device_features2.pNext = &vk11_features;
  3628. VkPhysicalDeviceVulkan12Features vk12_features;
  3629. vk12_features.pNext = nullptr;
  3630. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  3631. vk11_features.pNext = &vk12_features;
  3632. last_struct = (VkBaseOutStructure *)&vk12_features;
  3633. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  3634. pl_robustness_features.pNext = nullptr;
  3635. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  3636. pl_robustness_features.pipelineRobustness = VK_FALSE;
  3637. if (pipeline_robustness) {
  3638. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  3639. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  3640. device_extensions.push_back("VK_EXT_pipeline_robustness");
  3641. }
  3642. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  3643. subgroup_size_control_features.pNext = nullptr;
  3644. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  3645. subgroup_size_control_features.computeFullSubgroups = false;
  3646. subgroup_size_control_features.subgroupSizeControl = false;
  3647. if (device->subgroup_size_control) {
  3648. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  3649. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  3650. }
  3651. #if defined(VK_KHR_cooperative_matrix)
  3652. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  3653. coopmat_features.pNext = nullptr;
  3654. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  3655. coopmat_features.cooperativeMatrix = VK_FALSE;
  3656. if (device->coopmat_support) {
  3657. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  3658. last_struct = (VkBaseOutStructure *)&coopmat_features;
  3659. }
  3660. #endif
  3661. #if defined(VK_NV_cooperative_matrix2)
  3662. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  3663. coopmat2_features.pNext = nullptr;
  3664. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  3665. if (coopmat2_support) {
  3666. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  3667. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  3668. device_extensions.push_back("VK_NV_cooperative_matrix2");
  3669. }
  3670. #endif
  3671. #if defined(VK_KHR_shader_bfloat16)
  3672. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  3673. bfloat16_features.pNext = nullptr;
  3674. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  3675. if (bfloat16_support) {
  3676. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  3677. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  3678. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3679. }
  3680. #endif
  3681. VkPhysicalDeviceMaintenance4Features maint4_features {};
  3682. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  3683. if (maintenance4_support) {
  3684. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  3685. last_struct = (VkBaseOutStructure *)&maint4_features;
  3686. device_extensions.push_back("VK_KHR_maintenance4");
  3687. }
  3688. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  3689. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  3690. if (device->integer_dot_product) {
  3691. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3692. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3693. device_extensions.push_back("VK_KHR_shader_integer_dot_product");
  3694. }
  3695. VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pep_features {};
  3696. pep_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR;
  3697. if (pipeline_executable_properties_support) {
  3698. last_struct->pNext = (VkBaseOutStructure *)&pep_features;
  3699. last_struct = (VkBaseOutStructure *)&pep_features;
  3700. device_extensions.push_back("VK_KHR_pipeline_executable_properties");
  3701. }
  3702. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  3703. device->pipeline_executable_properties_support = pipeline_executable_properties_support;
  3704. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  3705. #if defined(VK_KHR_shader_bfloat16)
  3706. device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  3707. #else
  3708. device->bf16 = false;
  3709. #endif
  3710. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  3711. device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 &&
  3712. device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) &&
  3713. getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr;
  3714. device->shader_int64 = device_features2.features.shaderInt64;
  3715. device->buffer_device_address = vk12_features.bufferDeviceAddress;
  3716. if (device->subgroup_size_control) {
  3717. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  3718. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  3719. device_extensions.push_back("VK_EXT_subgroup_size_control");
  3720. }
  3721. device->subgroup_size_control = device->subgroup_size_control &&
  3722. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  3723. subgroup_size_control_features.subgroupSizeControl;
  3724. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  3725. #if defined(VK_KHR_cooperative_matrix)
  3726. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  3727. // coopmat1 fa shader currently assumes 32 invocations per subgroup
  3728. device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support &&
  3729. device->subgroup_size_control && device->subgroup_min_size <= 32 &&
  3730. device->subgroup_max_size >= 32;
  3731. #endif
  3732. if (coopmat2_support) {
  3733. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3734. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  3735. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  3736. coopmat2_features.cooperativeMatrixReductions &&
  3737. coopmat2_features.cooperativeMatrixConversions &&
  3738. coopmat2_features.cooperativeMatrixPerElementOperations &&
  3739. coopmat2_features.cooperativeMatrixTensorAddressing &&
  3740. coopmat2_features.cooperativeMatrixBlockLoads &&
  3741. vk12_features.bufferDeviceAddress) {
  3742. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  3743. uint32_t count = 0;
  3744. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  3745. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  3746. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  3747. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  3748. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  3749. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  3750. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  3751. flexible_dimensions.resize(count, empty_prop);
  3752. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  3753. bool found_fp16_128 = false,
  3754. found_fp16_256 = false,
  3755. found_fp32_128 = false,
  3756. found_fp32_256 = false;
  3757. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  3758. // with 32x16x16 and 256 with 32x32x16.
  3759. for (auto &prop : flexible_dimensions) {
  3760. if (prop.saturatingAccumulation == VK_FALSE &&
  3761. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  3762. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3763. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3764. if (prop.workgroupInvocations == 128 &&
  3765. prop.MGranularity <= 32 &&
  3766. prop.NGranularity <= 16 &&
  3767. prop.KGranularity <= 16) {
  3768. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3769. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3770. found_fp16_128 = true;
  3771. }
  3772. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3773. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3774. found_fp32_128 = true;
  3775. }
  3776. }
  3777. if (prop.workgroupInvocations == 256 &&
  3778. prop.MGranularity <= 32 &&
  3779. prop.NGranularity <= 32 &&
  3780. prop.KGranularity <= 16) {
  3781. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3782. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3783. found_fp16_256 = true;
  3784. }
  3785. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3786. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3787. found_fp32_256 = true;
  3788. }
  3789. }
  3790. }
  3791. }
  3792. if (found_fp16_128 && found_fp16_256 &&
  3793. found_fp32_128 && found_fp32_256 &&
  3794. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  3795. device->coopmat2 = true;
  3796. }
  3797. }
  3798. #endif
  3799. }
  3800. if (!vk11_features.storageBuffer16BitAccess) {
  3801. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  3802. throw std::runtime_error("Unsupported device");
  3803. }
  3804. device_extensions.push_back("VK_KHR_16bit_storage");
  3805. #ifdef GGML_VULKAN_VALIDATE
  3806. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  3807. #endif
  3808. if (device->fp16) {
  3809. device_extensions.push_back("VK_KHR_shader_float16_int8");
  3810. }
  3811. #if defined(VK_KHR_cooperative_matrix)
  3812. if (device->coopmat_support) {
  3813. // Query supported shapes
  3814. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  3815. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  3816. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  3817. uint32_t cm_props_num;
  3818. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  3819. cm_props.resize(cm_props_num);
  3820. for (auto& prop : cm_props) {
  3821. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  3822. }
  3823. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  3824. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  3825. for (auto& prop : cm_props) {
  3826. 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));
  3827. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  3828. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  3829. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3830. ) {
  3831. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  3832. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  3833. // coopmat sizes not set yet
  3834. if (device->coopmat_m == 0) {
  3835. device->coopmat_acc_f32_support = true;
  3836. device->coopmat_m = prop.MSize;
  3837. device->coopmat_n = prop.NSize;
  3838. device->coopmat_k = prop.KSize;
  3839. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3840. // Only enable if shape is identical
  3841. device->coopmat_acc_f32_support = true;
  3842. }
  3843. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3844. device->coopmat_support_16x16x16_f32acc = true;
  3845. }
  3846. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  3847. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  3848. // coopmat sizes not set yet
  3849. if (device->coopmat_m == 0) {
  3850. device->coopmat_acc_f16_support = true;
  3851. device->coopmat_m = prop.MSize;
  3852. device->coopmat_n = prop.NSize;
  3853. device->coopmat_k = prop.KSize;
  3854. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3855. // Only enable if shape is identical
  3856. device->coopmat_acc_f16_support = true;
  3857. }
  3858. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3859. device->coopmat_support_16x16x16_f16acc = true;
  3860. }
  3861. }
  3862. } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 &&
  3863. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 &&
  3864. (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 &&
  3865. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 &&
  3866. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup &&
  3867. device->coopmat_int_m == 0
  3868. ) {
  3869. device->coopmat_int_support = true;
  3870. device->coopmat_int_m = prop.MSize;
  3871. device->coopmat_int_n = prop.NSize;
  3872. device->coopmat_int_k = prop.KSize;
  3873. }
  3874. #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3875. if (prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3876. prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3877. prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3878. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3879. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3880. ) {
  3881. // coopmat sizes not set yet
  3882. if (device->coopmat_m == 0) {
  3883. device->coopmat_bf16_support = true;
  3884. device->coopmat_m = prop.MSize;
  3885. device->coopmat_n = prop.NSize;
  3886. device->coopmat_k = prop.KSize;
  3887. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3888. // Only enable if shape is identical
  3889. device->coopmat_bf16_support = true;
  3890. }
  3891. }
  3892. #endif
  3893. }
  3894. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  3895. // No suitable matmul mode found
  3896. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  3897. device->coopmat_support = false;
  3898. }
  3899. if (getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3900. device->coopmat_bf16_support = false;
  3901. }
  3902. }
  3903. if (device->coopmat_support) {
  3904. device_extensions.push_back("VK_KHR_cooperative_matrix");
  3905. }
  3906. #if defined(VK_KHR_shader_bfloat16)
  3907. if (device->coopmat_bf16_support) {
  3908. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3909. }
  3910. #endif
  3911. #endif
  3912. device->name = GGML_VK_NAME + std::to_string(idx);
  3913. device_create_info = {
  3914. vk::DeviceCreateFlags(),
  3915. device_queue_create_infos,
  3916. {},
  3917. device_extensions
  3918. };
  3919. device_create_info.setPNext(&device_features2);
  3920. device->device = device->physical_device.createDevice(device_create_info);
  3921. // Queues
  3922. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  3923. // Shaders
  3924. // Disable matmul tile sizes early if performance low or not supported
  3925. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  3926. switch (device->vendor_id) {
  3927. #ifndef GGML_VULKAN_RUN_TESTS
  3928. case VK_VENDOR_ID_AMD:
  3929. case VK_VENDOR_ID_INTEL:
  3930. device->mul_mat_l[i] = false;
  3931. device->mul_mat_m[i] = true;
  3932. device->mul_mat_s[i] = true;
  3933. device->mul_mat_id_l[i] = false;
  3934. device->mul_mat_id_m[i] = true;
  3935. device->mul_mat_id_s[i] = true;
  3936. break;
  3937. case VK_VENDOR_ID_APPLE:
  3938. device->mul_mat_l[i] = false;
  3939. device->mul_mat_m[i] = true;
  3940. device->mul_mat_s[i] = false;
  3941. device->mul_mat_id_l[i] = false;
  3942. device->mul_mat_id_m[i] = true;
  3943. device->mul_mat_id_s[i] = false;
  3944. break;
  3945. #endif
  3946. default:
  3947. device->mul_mat_l[i] = true;
  3948. device->mul_mat_m[i] = true;
  3949. device->mul_mat_s[i] = true;
  3950. device->mul_mat_id_l[i] = true;
  3951. device->mul_mat_id_m[i] = true;
  3952. device->mul_mat_id_s[i] = true;
  3953. break;
  3954. }
  3955. }
  3956. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  3957. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  3958. for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
  3959. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  3960. dsl_binding_flags.push_back({});
  3961. }
  3962. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  3963. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  3964. {},
  3965. dsl_binding);
  3966. descriptor_set_layout_create_info.setPNext(&dslbfci);
  3967. device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  3968. ggml_vk_load_shaders(device);
  3969. if (!device->single_queue) {
  3970. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  3971. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  3972. } else {
  3973. // TODO: Use pointer or reference to avoid copy
  3974. device->transfer_queue.copyFrom(device->compute_queue);
  3975. device->transfer_queue.cmd_pool.init(device, &device->transfer_queue);
  3976. }
  3977. device->buffer_type = {
  3978. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  3979. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  3980. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  3981. };
  3982. device->fence = device->device.createFence({});
  3983. device->idx = idx;
  3984. device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr;
  3985. device->add_rms_fusion = !device->disable_fusion &&
  3986. device->subgroup_arithmetic &&
  3987. device->vendor_id != VK_VENDOR_ID_INTEL;
  3988. device->partials_binding_alignment =
  3989. std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment);
  3990. device->mmvq_mode = 0;
  3991. if (getenv("GGML_VK_DISABLE_MMVQ")) {
  3992. device->mmvq_mode = -1;
  3993. } else if (getenv("GGML_VK_FORCE_MMVQ")) {
  3994. device->mmvq_mode = 1;
  3995. }
  3996. return device;
  3997. }
  3998. return vk_instance.devices[idx];
  3999. }
  4000. static void ggml_vk_print_gpu_info(size_t idx) {
  4001. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4002. size_t dev_num = vk_instance.device_indices[idx];
  4003. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  4004. GGML_ASSERT(vk_instance_initialized);
  4005. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4006. if (dev_num >= devices.size()) {
  4007. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  4008. throw std::runtime_error("Device not found");
  4009. }
  4010. vk::PhysicalDevice physical_device = devices[dev_num];
  4011. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  4012. bool fp16_storage = false;
  4013. bool fp16_compute = false;
  4014. bool coopmat_support = false;
  4015. bool coopmat2_support = false;
  4016. bool integer_dot_product = false;
  4017. bool bfloat16_support = false;
  4018. for (auto properties : ext_props) {
  4019. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  4020. fp16_storage = true;
  4021. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  4022. fp16_compute = true;
  4023. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4024. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  4025. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  4026. coopmat_support = true;
  4027. #endif
  4028. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  4029. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  4030. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  4031. coopmat2_support = true;
  4032. #endif
  4033. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  4034. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  4035. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  4036. integer_dot_product = true;
  4037. #endif
  4038. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4039. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  4040. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4041. bfloat16_support = true;
  4042. #endif
  4043. }
  4044. }
  4045. const vk_device_architecture device_architecture = get_device_architecture(physical_device);
  4046. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  4047. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  4048. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  4049. vk::PhysicalDeviceProperties2 props2;
  4050. vk::PhysicalDeviceMaintenance3Properties props3;
  4051. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  4052. vk::PhysicalDeviceDriverProperties driver_props;
  4053. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  4054. props2.pNext = &props3;
  4055. props3.pNext = &subgroup_props;
  4056. subgroup_props.pNext = &driver_props;
  4057. // Pointer to the last chain element
  4058. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  4059. if (integer_dot_product) {
  4060. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4061. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4062. }
  4063. physical_device.getProperties2(&props2);
  4064. VkPhysicalDeviceFeatures2 device_features2;
  4065. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  4066. device_features2.pNext = nullptr;
  4067. VkPhysicalDeviceVulkan11Features vk11_features;
  4068. vk11_features.pNext = nullptr;
  4069. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  4070. device_features2.pNext = &vk11_features;
  4071. VkPhysicalDeviceVulkan12Features vk12_features;
  4072. vk12_features.pNext = nullptr;
  4073. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  4074. vk11_features.pNext = &vk12_features;
  4075. // Pointer to the last chain element
  4076. last_struct = (VkBaseOutStructure *)&vk12_features;
  4077. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4078. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  4079. coopmat_features.pNext = nullptr;
  4080. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  4081. coopmat_features.cooperativeMatrix = VK_FALSE;
  4082. if (coopmat_support) {
  4083. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  4084. last_struct = (VkBaseOutStructure *)&coopmat_features;
  4085. }
  4086. #endif
  4087. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  4088. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  4089. if (integer_dot_product) {
  4090. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4091. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4092. }
  4093. #if defined(VK_KHR_shader_bfloat16)
  4094. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  4095. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  4096. if (bfloat16_support) {
  4097. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  4098. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  4099. }
  4100. #endif
  4101. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  4102. fp16 = fp16 && vk12_features.shaderFloat16;
  4103. #if defined(VK_KHR_shader_bfloat16)
  4104. bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4105. #else
  4106. bool bf16 = false;
  4107. #endif
  4108. uint32_t default_subgroup_size = get_subgroup_size("", device_architecture);
  4109. const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize;
  4110. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  4111. integer_dot_product = integer_dot_product
  4112. && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated
  4113. && shader_integer_dot_product_features.shaderIntegerDotProduct;
  4114. coopmat_support = coopmat_support
  4115. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4116. && coopmat_features.cooperativeMatrix
  4117. #endif
  4118. && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture);
  4119. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  4120. std::string device_name = props2.properties.deviceName.data();
  4121. 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",
  4122. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, bf16, subgroup_size,
  4123. props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str());
  4124. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  4125. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  4126. }
  4127. }
  4128. static bool ggml_vk_instance_validation_ext_available();
  4129. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  4130. static bool ggml_vk_instance_debug_utils_ext_available(const std::vector<vk::ExtensionProperties> & instance_extensions);
  4131. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev);
  4132. static DispatchLoaderDynamic ggml_vk_default_dispatcher_instance;
  4133. DispatchLoaderDynamic & ggml_vk_default_dispatcher() {
  4134. return ggml_vk_default_dispatcher_instance;
  4135. }
  4136. static void ggml_vk_instance_init() {
  4137. if (vk_instance_initialized) {
  4138. return;
  4139. }
  4140. VK_LOG_DEBUG("ggml_vk_instance_init()");
  4141. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4142. ggml_vk_default_dispatcher_instance.init(vkGetInstanceProcAddr);
  4143. uint32_t api_version = vk::enumerateInstanceVersion();
  4144. if (api_version < VK_API_VERSION_1_2) {
  4145. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  4146. throw vk::SystemError(vk::Result::eErrorFeatureNotPresent, "Vulkan 1.2 required");
  4147. }
  4148. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  4149. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  4150. const bool validation_ext = ggml_vk_instance_validation_ext_available();
  4151. #ifdef __APPLE__
  4152. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  4153. #endif
  4154. const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr;
  4155. std::vector<const char*> layers;
  4156. if (validation_ext) {
  4157. layers.push_back("VK_LAYER_KHRONOS_validation");
  4158. }
  4159. std::vector<const char*> extensions;
  4160. if (validation_ext) {
  4161. extensions.push_back("VK_EXT_validation_features");
  4162. }
  4163. #ifdef __APPLE__
  4164. if (portability_enumeration_ext) {
  4165. extensions.push_back("VK_KHR_portability_enumeration");
  4166. }
  4167. #endif
  4168. if (debug_utils_ext) {
  4169. extensions.push_back("VK_EXT_debug_utils");
  4170. }
  4171. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions);
  4172. #ifdef __APPLE__
  4173. if (portability_enumeration_ext) {
  4174. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  4175. }
  4176. #endif
  4177. std::vector<vk::ValidationFeatureEnableEXT> features_enable;
  4178. vk::ValidationFeaturesEXT validation_features;
  4179. if (validation_ext) {
  4180. features_enable = { vk::ValidationFeatureEnableEXT::eBestPractices };
  4181. validation_features = {
  4182. features_enable,
  4183. {},
  4184. };
  4185. validation_features.setPNext(nullptr);
  4186. instance_create_info.setPNext(&validation_features);
  4187. GGML_LOG_DEBUG("ggml_vulkan: Validation layers enabled\n");
  4188. }
  4189. vk_instance.instance = vk::createInstance(instance_create_info);
  4190. vk_instance_initialized = true;
  4191. if (debug_utils_ext) {
  4192. vk_instance.debug_utils_support = true;
  4193. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT");
  4194. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT");
  4195. vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT");
  4196. vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT");
  4197. vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT");
  4198. vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT");
  4199. }
  4200. vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr;
  4201. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4202. VULKAN_HPP_DEFAULT_DISPATCHER.init(vk_instance.instance);
  4203. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4204. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  4205. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  4206. if (devices_env != nullptr) {
  4207. size_t num_available_devices = devices.size();
  4208. std::string devices(devices_env);
  4209. std::replace(devices.begin(), devices.end(), ',', ' ');
  4210. std::stringstream ss(devices);
  4211. size_t tmp;
  4212. while (ss >> tmp) {
  4213. if(tmp >= num_available_devices) {
  4214. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  4215. throw std::runtime_error("Invalid Vulkan device index");
  4216. }
  4217. vk_instance.device_indices.push_back(tmp);
  4218. }
  4219. } else {
  4220. // If no vulkan devices are found, return early
  4221. if (devices.empty()) {
  4222. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4223. return;
  4224. }
  4225. // Default to using all dedicated GPUs
  4226. for (size_t i = 0; i < devices.size(); i++) {
  4227. vk::PhysicalDeviceProperties2 new_props;
  4228. vk::PhysicalDeviceDriverProperties new_driver;
  4229. vk::PhysicalDeviceIDProperties new_id;
  4230. new_props.pNext = &new_driver;
  4231. new_driver.pNext = &new_id;
  4232. devices[i].getProperties2(&new_props);
  4233. if ((new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu || new_props.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) && ggml_vk_device_is_supported(devices[i])) {
  4234. // Check if there are two physical devices corresponding to the same GPU
  4235. auto old_device = std::find_if(
  4236. vk_instance.device_indices.begin(),
  4237. vk_instance.device_indices.end(),
  4238. [&devices, &new_id](const size_t k){
  4239. vk::PhysicalDeviceProperties2 old_props;
  4240. vk::PhysicalDeviceIDProperties old_id;
  4241. old_props.pNext = &old_id;
  4242. devices[k].getProperties2(&old_props);
  4243. bool equals = std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  4244. equals = equals || (
  4245. old_id.deviceLUIDValid && new_id.deviceLUIDValid &&
  4246. std::equal(std::begin(old_id.deviceLUID), std::end(old_id.deviceLUID), std::begin(new_id.deviceLUID))
  4247. );
  4248. return equals;
  4249. }
  4250. );
  4251. if (old_device == vk_instance.device_indices.end()) {
  4252. vk_instance.device_indices.push_back(i);
  4253. } else {
  4254. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  4255. // This can cause error when splitting layers aross the devices, need to keep only 1
  4256. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  4257. vk::PhysicalDeviceProperties2 old_props;
  4258. vk::PhysicalDeviceDriverProperties old_driver;
  4259. old_props.pNext = &old_driver;
  4260. devices[*old_device].getProperties2(&old_props);
  4261. std::map<vk::DriverId, int> driver_priorities {};
  4262. int old_priority = std::numeric_limits<int>::max();
  4263. int new_priority = std::numeric_limits<int>::max();
  4264. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  4265. // Smaller number -> higher priority
  4266. switch (old_props.properties.vendorID) {
  4267. case VK_VENDOR_ID_AMD:
  4268. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  4269. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  4270. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  4271. break;
  4272. case VK_VENDOR_ID_INTEL:
  4273. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  4274. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  4275. break;
  4276. case VK_VENDOR_ID_NVIDIA:
  4277. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  4278. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  4279. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  4280. #endif
  4281. break;
  4282. }
  4283. driver_priorities[vk::DriverId::eMesaDozen] = 100;
  4284. if (driver_priorities.count(old_driver.driverID)) {
  4285. old_priority = driver_priorities[old_driver.driverID];
  4286. }
  4287. if (driver_priorities.count(new_driver.driverID)) {
  4288. new_priority = driver_priorities[new_driver.driverID];
  4289. }
  4290. if (new_priority < old_priority) {
  4291. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  4292. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  4293. vk_instance.device_indices.push_back(i);
  4294. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  4295. }
  4296. else {
  4297. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  4298. }
  4299. }
  4300. }
  4301. }
  4302. // If no GPUs found, fall back to the first non-CPU device.
  4303. // If only CPU devices are available, return without devices.
  4304. if (vk_instance.device_indices.empty()) {
  4305. for (size_t i = 0; i < devices.size(); i++) {
  4306. if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) {
  4307. vk_instance.device_indices.push_back(i);
  4308. break;
  4309. }
  4310. }
  4311. }
  4312. if (vk_instance.device_indices.empty()) {
  4313. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4314. return;
  4315. }
  4316. }
  4317. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  4318. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  4319. vk::PhysicalDevice vkdev = devices[vk_instance.device_indices[i]];
  4320. std::vector<vk::ExtensionProperties> extensionprops = vkdev.enumerateDeviceExtensionProperties();
  4321. bool membudget_supported = false;
  4322. for (const auto & ext : extensionprops) {
  4323. if (strcmp(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, ext.extensionName) == 0) {
  4324. membudget_supported = true;
  4325. break;
  4326. }
  4327. }
  4328. vk_instance.device_supports_membudget.push_back(membudget_supported);
  4329. ggml_vk_print_gpu_info(i);
  4330. }
  4331. }
  4332. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  4333. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  4334. ggml_vk_instance_init();
  4335. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4336. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4337. ctx->device = ggml_vk_get_device(idx);
  4338. ctx->semaphore_idx = 0;
  4339. ctx->event_idx = 0;
  4340. ctx->prealloc_size_x = 0;
  4341. ctx->prealloc_size_y = 0;
  4342. ctx->prealloc_size_split_k = 0;
  4343. ctx->prealloc_size_add_rms_partials = 0;
  4344. ctx->fence = ctx->device->device.createFence({});
  4345. ctx->almost_ready_fence = ctx->device->device.createFence({});
  4346. ctx->compute_cmd_pool.init(ctx->device, &ctx->device->compute_queue);
  4347. ctx->transfer_cmd_pool.init(ctx->device, &ctx->device->transfer_queue);
  4348. #ifdef GGML_VULKAN_CHECK_RESULTS
  4349. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  4350. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  4351. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  4352. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  4353. #endif
  4354. }
  4355. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  4356. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  4357. switch (type) {
  4358. case GGML_TYPE_F32:
  4359. case GGML_TYPE_Q4_0:
  4360. case GGML_TYPE_Q4_1:
  4361. case GGML_TYPE_Q5_0:
  4362. case GGML_TYPE_Q5_1:
  4363. case GGML_TYPE_Q8_0:
  4364. case GGML_TYPE_Q2_K:
  4365. case GGML_TYPE_Q3_K:
  4366. case GGML_TYPE_Q4_K:
  4367. case GGML_TYPE_Q5_K:
  4368. case GGML_TYPE_Q6_K:
  4369. case GGML_TYPE_IQ1_S:
  4370. case GGML_TYPE_IQ1_M:
  4371. case GGML_TYPE_IQ2_XXS:
  4372. case GGML_TYPE_IQ2_XS:
  4373. case GGML_TYPE_IQ2_S:
  4374. case GGML_TYPE_IQ3_XXS:
  4375. case GGML_TYPE_IQ3_S:
  4376. case GGML_TYPE_IQ4_XS:
  4377. case GGML_TYPE_IQ4_NL:
  4378. case GGML_TYPE_MXFP4:
  4379. break;
  4380. default:
  4381. return nullptr;
  4382. }
  4383. return ctx->device->pipeline_dequant[type];
  4384. }
  4385. 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) {
  4386. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ", " << prec << ")");
  4387. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4388. return ctx->device->pipeline_matmul_f32;
  4389. }
  4390. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4391. return ctx->device->pipeline_matmul_f32_f16;
  4392. }
  4393. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4394. return ctx->device->pipeline_matmul_bf16;
  4395. }
  4396. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4397. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4398. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  4399. }
  4400. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4401. return ctx->device->pipeline_matmul_f16.f16acc;
  4402. }
  4403. } else {
  4404. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4405. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  4406. }
  4407. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4408. return ctx->device->pipeline_matmul_f16.f32acc;
  4409. }
  4410. }
  4411. // MMQ
  4412. if (src1_type == GGML_TYPE_Q8_1) {
  4413. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1[src0_type].f32acc;
  4414. if (pipelines->is_empty()) {
  4415. return nullptr;
  4416. }
  4417. return pipelines;
  4418. }
  4419. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  4420. return nullptr;
  4421. }
  4422. switch (src0_type) {
  4423. case GGML_TYPE_Q4_0:
  4424. case GGML_TYPE_Q4_1:
  4425. case GGML_TYPE_Q5_0:
  4426. case GGML_TYPE_Q5_1:
  4427. case GGML_TYPE_Q8_0:
  4428. case GGML_TYPE_Q2_K:
  4429. case GGML_TYPE_Q3_K:
  4430. case GGML_TYPE_Q4_K:
  4431. case GGML_TYPE_Q5_K:
  4432. case GGML_TYPE_Q6_K:
  4433. case GGML_TYPE_IQ1_S:
  4434. case GGML_TYPE_IQ1_M:
  4435. case GGML_TYPE_IQ2_XXS:
  4436. case GGML_TYPE_IQ2_XS:
  4437. case GGML_TYPE_IQ2_S:
  4438. case GGML_TYPE_IQ3_XXS:
  4439. case GGML_TYPE_IQ3_S:
  4440. case GGML_TYPE_IQ4_XS:
  4441. case GGML_TYPE_IQ4_NL:
  4442. case GGML_TYPE_MXFP4:
  4443. break;
  4444. default:
  4445. return nullptr;
  4446. }
  4447. if (ctx->device->coopmat2) {
  4448. assert(src1_type == GGML_TYPE_F16);
  4449. 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;
  4450. }
  4451. if (ctx->device->coopmat_support) {
  4452. 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;
  4453. }
  4454. 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;
  4455. }
  4456. 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) {
  4457. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  4458. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1);
  4459. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  4460. if (b_type == GGML_TYPE_Q8_1) {
  4461. switch (a_type) {
  4462. case GGML_TYPE_Q4_0:
  4463. case GGML_TYPE_Q4_1:
  4464. case GGML_TYPE_Q5_0:
  4465. case GGML_TYPE_Q5_1:
  4466. case GGML_TYPE_Q8_0:
  4467. break;
  4468. default:
  4469. return nullptr;
  4470. }
  4471. }
  4472. switch (a_type) {
  4473. case GGML_TYPE_F32:
  4474. case GGML_TYPE_F16:
  4475. case GGML_TYPE_BF16:
  4476. case GGML_TYPE_Q4_0:
  4477. case GGML_TYPE_Q4_1:
  4478. case GGML_TYPE_Q5_0:
  4479. case GGML_TYPE_Q5_1:
  4480. case GGML_TYPE_Q8_0:
  4481. case GGML_TYPE_Q2_K:
  4482. case GGML_TYPE_Q3_K:
  4483. case GGML_TYPE_Q4_K:
  4484. case GGML_TYPE_Q5_K:
  4485. case GGML_TYPE_Q6_K:
  4486. case GGML_TYPE_IQ1_S:
  4487. case GGML_TYPE_IQ1_M:
  4488. case GGML_TYPE_IQ2_XXS:
  4489. case GGML_TYPE_IQ2_XS:
  4490. case GGML_TYPE_IQ2_S:
  4491. case GGML_TYPE_IQ3_XXS:
  4492. case GGML_TYPE_IQ3_S:
  4493. case GGML_TYPE_IQ4_XS:
  4494. case GGML_TYPE_IQ4_NL:
  4495. case GGML_TYPE_MXFP4:
  4496. break;
  4497. default:
  4498. return nullptr;
  4499. }
  4500. // heuristic to choose workgroup size
  4501. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4502. 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) {
  4503. // Prefer larger workgroups when M is small, to spread the work out more
  4504. // and keep more SMs busy.
  4505. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4506. if (a_type == GGML_TYPE_Q6_K) {
  4507. if (m < 4096 && k >= 1024) {
  4508. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4509. }
  4510. } else {
  4511. if (m <= 8192 && k >= 1024) {
  4512. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4513. }
  4514. }
  4515. }
  4516. if (b_type == GGML_TYPE_Q8_1) {
  4517. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4518. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4519. }
  4520. return ctx->device->pipeline_dequant_mul_mat_vec_q8_1_f32[dmmv_wg][a_type][num_cols-1];
  4521. }
  4522. 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];
  4523. }
  4524. 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) {
  4525. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  4526. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4527. return ctx->device->pipeline_matmul_id_f32;
  4528. }
  4529. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4530. return ctx->device->pipeline_matmul_id_bf16;
  4531. }
  4532. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4533. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4534. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  4535. }
  4536. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4537. return ctx->device->pipeline_matmul_id_f16.f16acc;
  4538. }
  4539. } else {
  4540. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4541. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  4542. }
  4543. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4544. return ctx->device->pipeline_matmul_id_f16.f32acc;
  4545. }
  4546. }
  4547. // MMQ
  4548. if (src1_type == GGML_TYPE_Q8_1) {
  4549. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_id_q8_1[src0_type].f32acc;
  4550. if (pipelines->is_empty()) {
  4551. return nullptr;
  4552. }
  4553. return pipelines;
  4554. }
  4555. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  4556. switch (src0_type) {
  4557. case GGML_TYPE_Q4_0:
  4558. case GGML_TYPE_Q4_1:
  4559. case GGML_TYPE_Q5_0:
  4560. case GGML_TYPE_Q5_1:
  4561. case GGML_TYPE_Q8_0:
  4562. case GGML_TYPE_Q2_K:
  4563. case GGML_TYPE_Q3_K:
  4564. case GGML_TYPE_Q4_K:
  4565. case GGML_TYPE_Q5_K:
  4566. case GGML_TYPE_Q6_K:
  4567. case GGML_TYPE_IQ1_S:
  4568. case GGML_TYPE_IQ1_M:
  4569. case GGML_TYPE_IQ2_XXS:
  4570. case GGML_TYPE_IQ2_XS:
  4571. case GGML_TYPE_IQ2_S:
  4572. case GGML_TYPE_IQ3_XXS:
  4573. case GGML_TYPE_IQ3_S:
  4574. case GGML_TYPE_IQ4_XS:
  4575. case GGML_TYPE_IQ4_NL:
  4576. case GGML_TYPE_MXFP4:
  4577. break;
  4578. default:
  4579. return nullptr;
  4580. }
  4581. vk_matmul_pipeline2& mmp = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type];
  4582. // XXX TODO 'prec' is not actually allowed in mul_mat_id.
  4583. bool prefer_fp16acc = ctx->device->fp16 /*&& prec == GGML_PREC_DEFAULT*/;
  4584. bool support_fp16acc = !mmp.f16acc->is_empty();
  4585. bool support_fp32acc = !mmp.f32acc->is_empty();
  4586. if (support_fp16acc && (prefer_fp16acc || !support_fp32acc)) {
  4587. return mmp.f16acc;
  4588. } else {
  4589. GGML_ASSERT(support_fp32acc);
  4590. return mmp.f32acc;
  4591. }
  4592. }
  4593. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type) {
  4594. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()");
  4595. GGML_ASSERT(b_type == GGML_TYPE_F32);
  4596. switch (a_type) {
  4597. case GGML_TYPE_F32:
  4598. case GGML_TYPE_F16:
  4599. case GGML_TYPE_BF16:
  4600. case GGML_TYPE_Q4_0:
  4601. case GGML_TYPE_Q4_1:
  4602. case GGML_TYPE_Q5_0:
  4603. case GGML_TYPE_Q5_1:
  4604. case GGML_TYPE_Q8_0:
  4605. case GGML_TYPE_Q2_K:
  4606. case GGML_TYPE_Q3_K:
  4607. case GGML_TYPE_Q4_K:
  4608. case GGML_TYPE_Q5_K:
  4609. case GGML_TYPE_Q6_K:
  4610. case GGML_TYPE_IQ1_S:
  4611. case GGML_TYPE_IQ1_M:
  4612. case GGML_TYPE_IQ2_XXS:
  4613. case GGML_TYPE_IQ2_XS:
  4614. case GGML_TYPE_IQ2_S:
  4615. case GGML_TYPE_IQ3_XXS:
  4616. case GGML_TYPE_IQ3_S:
  4617. case GGML_TYPE_IQ4_XS:
  4618. case GGML_TYPE_IQ4_NL:
  4619. case GGML_TYPE_MXFP4:
  4620. break;
  4621. default:
  4622. return nullptr;
  4623. }
  4624. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[a_type];
  4625. }
  4626. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  4627. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  4628. vk_buffer buf = ggml_vk_create_buffer(device, size,
  4629. {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4630. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  4631. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  4632. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  4633. size/1024.0/1024.0);
  4634. device->device.freeMemory(buf->device_memory);
  4635. device->device.destroyBuffer(buf->buffer);
  4636. return nullptr;
  4637. }
  4638. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4639. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  4640. return buf->ptr;
  4641. }
  4642. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  4643. if (ptr == nullptr) {
  4644. return;
  4645. }
  4646. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  4647. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4648. vk_buffer buf;
  4649. size_t index;
  4650. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4651. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4652. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4653. if (ptr >= addr && ptr < endr) {
  4654. buf = std::get<2>(device->pinned_memory[i]);
  4655. index = i;
  4656. break;
  4657. }
  4658. }
  4659. if (buf == nullptr) {
  4660. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  4661. return;
  4662. }
  4663. ggml_vk_destroy_buffer(buf);
  4664. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  4665. }
  4666. static void ggml_vk_host_get(const vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  4667. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4668. buf = nullptr;
  4669. buf_offset = 0;
  4670. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4671. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4672. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4673. if (ptr >= addr && ptr < endr) {
  4674. buf = std::get<2>(device->pinned_memory[i]);
  4675. buf_offset = ((const uint8_t *)ptr) - addr;
  4676. break;
  4677. }
  4678. }
  4679. }
  4680. static vk_subbuffer ggml_vk_tensor_subbuffer(
  4681. const ggml_backend_vk_context * ctx, const ggml_tensor * tensor, bool allow_misalign = false) {
  4682. vk_buffer buffer = nullptr;
  4683. size_t offset = 0;
  4684. if (ctx->device->uma) {
  4685. ggml_vk_host_get(ctx->device, tensor->data, buffer, offset);
  4686. }
  4687. if (!buffer) {
  4688. auto buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  4689. buffer = buf_ctx->dev_buffer;
  4690. offset = vk_tensor_offset(tensor) + tensor->view_offs;
  4691. }
  4692. GGML_ASSERT(buffer != nullptr);
  4693. size_t size = ggml_nbytes(tensor);
  4694. size_t misalign_bytes = offset & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  4695. // The shader must support misaligned offsets when indexing into the buffer
  4696. GGML_ASSERT(allow_misalign || misalign_bytes == 0);
  4697. offset &= ~misalign_bytes;
  4698. size += misalign_bytes;
  4699. return vk_subbuffer{buffer, offset, size};
  4700. }
  4701. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) {
  4702. vk_submission s;
  4703. s.buffer = ggml_vk_create_cmd_buffer(device, p);
  4704. if (one_time) {
  4705. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  4706. } else {
  4707. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  4708. }
  4709. return s;
  4710. }
  4711. template <typename T> size_t push_constant_size(const T &t) {
  4712. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4713. GGML_UNUSED(t);
  4714. return sizeof(T);
  4715. }
  4716. template <typename T> size_t push_constant_size(const std::vector<T> &t) {
  4717. GGML_UNUSED(t);
  4718. return sizeof(T) * t.size();
  4719. }
  4720. template <typename T, uint32_t N> size_t push_constant_size(const std::array<T, N> &t) {
  4721. GGML_UNUSED(t);
  4722. return sizeof(T) * N;
  4723. }
  4724. template <typename T> const T *push_constant_data(const T &t) {
  4725. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4726. return &t;
  4727. }
  4728. template <typename T> const T *push_constant_data(const std::vector<T> &t) {
  4729. return t.data();
  4730. }
  4731. template <typename T, uint32_t N> const T *push_constant_data(const std::array<T, N> &t) {
  4732. return t.data();
  4733. }
  4734. template <typename T>
  4735. 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) {
  4736. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  4737. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  4738. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  4739. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  4740. for (auto& buffer : descriptor_buffer_infos) {
  4741. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  4742. }
  4743. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  4744. GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size());
  4745. GGML_ASSERT(descriptor_buffer_infos.size() <= MAX_PARAMETER_COUNT);
  4746. GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size());
  4747. vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[ctx->descriptor_set_idx++];
  4748. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  4749. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  4750. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size(push_constants), push_constant_data(push_constants));
  4751. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  4752. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  4753. pipeline->layout,
  4754. 0,
  4755. { descriptor_set },
  4756. {});
  4757. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  4758. }
  4759. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  4760. s.buffer.end();
  4761. s.wait_semaphores = std::move(wait_semaphores);
  4762. s.signal_semaphores = std::move(signal_semaphores);
  4763. }
  4764. static void ggml_vk_ctx_end(vk_context& ctx) {
  4765. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  4766. if (ctx->s == nullptr) {
  4767. return;
  4768. }
  4769. ctx->s->buffer.end();
  4770. ctx->s = nullptr;
  4771. }
  4772. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  4773. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  4774. if (subctx->s != nullptr) {
  4775. ggml_vk_ctx_end(subctx);
  4776. }
  4777. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) });
  4778. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  4779. }
  4780. static size_t ggml_vk_align_size(size_t width, size_t align) {
  4781. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  4782. return CEIL_DIV(width, align) * align;
  4783. }
  4784. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  4785. if (memcpys == nullptr) {
  4786. memcpy(dst, src, size);
  4787. } else {
  4788. memcpys->emplace_back(dst, src, size);
  4789. }
  4790. }
  4791. static void deferred_memset(void * dst, uint32_t val, size_t size, std::vector<vk_staging_memset>* memsets = nullptr) {
  4792. if (memsets == nullptr) {
  4793. memset(dst, val, size);
  4794. } else {
  4795. memsets->emplace_back(dst, val, size);
  4796. }
  4797. }
  4798. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  4799. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  4800. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  4801. ggml_vk_destroy_buffer(device->sync_staging);
  4802. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  4803. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4804. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  4805. }
  4806. }
  4807. 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) {
  4808. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  4809. GGML_ASSERT(!ggml_is_contiguous(tensor));
  4810. // Buffer is already mapped
  4811. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4812. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4813. GGML_ABORT("fatal error");
  4814. }
  4815. // Check if src is pinned memory
  4816. vk_buffer buf = nullptr;
  4817. size_t buf_offset = 0;
  4818. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  4819. const uint64_t ne0 = tensor->ne[0];
  4820. const uint64_t ne1 = tensor->ne[1];
  4821. const uint64_t ne2 = tensor->ne[2];
  4822. const uint64_t ne3 = tensor->ne[3];
  4823. const uint64_t nb0 = tensor->nb[0];
  4824. const uint64_t nb1 = tensor->nb[1];
  4825. const uint64_t nb2 = tensor->nb[2];
  4826. const uint64_t nb3 = tensor->nb[3];
  4827. const ggml_type type = tensor->type;
  4828. const uint64_t ts = ggml_type_size(type);
  4829. const uint64_t bs = ggml_blck_size(type);
  4830. const uint64_t dstnb0 = ts;
  4831. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  4832. const uint64_t dstnb2 = dstnb1*ne1;
  4833. const uint64_t dstnb3 = dstnb2*ne2;
  4834. const uint64_t ne = ggml_nelements(tensor);
  4835. if (buf != nullptr) {
  4836. // Memory is pinned, use as staging buffer
  4837. std::vector<vk::BufferCopy> slices;
  4838. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4839. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4840. // Find longest contiguous slice
  4841. if (ne1*nb1 == dstnb2) {
  4842. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  4843. } else {
  4844. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4845. if (ne0*nb0/bs == dstnb1) {
  4846. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  4847. } else {
  4848. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4849. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4850. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4851. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  4852. }
  4853. }
  4854. }
  4855. }
  4856. }
  4857. }
  4858. ggml_vk_sync_buffers(ctx, subctx);
  4859. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  4860. return;
  4861. }
  4862. if (!sync_staging) {
  4863. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  4864. }
  4865. // Staging buffer required
  4866. vk_buffer& staging = ctx->device->sync_staging;
  4867. const uint64_t copy_size = ts*ne/bs;
  4868. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  4869. VkBufferCopy buf_copy{ 0, offset, copy_size };
  4870. ggml_vk_sync_buffers(ctx, subctx);
  4871. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  4872. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4873. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4874. // Find longest contiguous slice
  4875. if (ne1*nb1 == dstnb2) {
  4876. 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);
  4877. } else {
  4878. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4879. if (ne0*nb0/bs == dstnb1) {
  4880. 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);
  4881. } else {
  4882. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4883. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4884. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4885. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  4886. }
  4887. }
  4888. }
  4889. }
  4890. }
  4891. }
  4892. }
  4893. 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) {
  4894. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  4895. // Buffer is already mapped
  4896. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4897. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4898. GGML_ABORT("fatal error");
  4899. }
  4900. // Check if src is pinned memory
  4901. vk_buffer buf = nullptr;
  4902. size_t buf_offset = 0;
  4903. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  4904. if (buf != nullptr) {
  4905. // Memory is pinned, use as staging buffer
  4906. std::vector<vk::BufferCopy> slices(1);
  4907. if (width == spitch) {
  4908. // Only do single write if stride is equal
  4909. slices[0].srcOffset = buf_offset;
  4910. slices[0].dstOffset = offset;
  4911. slices[0].size = width * height;
  4912. } else {
  4913. slices.resize(height);
  4914. for (size_t i = 0; i < height; i++) {
  4915. slices[i].srcOffset = buf_offset + i * spitch;
  4916. slices[i].dstOffset = offset + i * width;
  4917. slices[i].size = width;
  4918. }
  4919. }
  4920. ggml_vk_sync_buffers(nullptr, subctx);
  4921. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  4922. return;
  4923. }
  4924. VK_LOG_DEBUG("STAGING");
  4925. if (!sync_staging) {
  4926. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  4927. }
  4928. // Staging buffer required
  4929. const size_t copy_size = width*height;
  4930. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  4931. vk_buffer& staging_buffer = dst->device->sync_staging;
  4932. VkBufferCopy buf_copy = {
  4933. 0,
  4934. offset,
  4935. copy_size};
  4936. ggml_vk_sync_buffers(nullptr, subctx);
  4937. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  4938. if (width == spitch) {
  4939. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  4940. } else {
  4941. for (size_t i = 0; i < height; i++) {
  4942. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  4943. }
  4944. }
  4945. }
  4946. 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) {
  4947. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  4948. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  4949. }
  4950. 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) {
  4951. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  4952. // Buffer is already mapped
  4953. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4954. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  4955. for (size_t i = 0; i < height; i++) {
  4956. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  4957. }
  4958. } else {
  4959. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  4960. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  4961. ggml_vk_ctx_begin(dst->device, subctx);
  4962. ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  4963. ggml_vk_ctx_end(subctx);
  4964. for (auto& cpy : subctx->in_memcpys) {
  4965. memcpy(cpy.dst, cpy.src, cpy.n);
  4966. }
  4967. for (auto& mset : subctx->memsets) {
  4968. memset(mset.dst, mset.val, mset.n);
  4969. }
  4970. ggml_vk_submit(subctx, dst->device->fence);
  4971. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  4972. dst->device->device.resetFences({ dst->device->fence });
  4973. ggml_vk_queue_command_pools_cleanup(dst->device);
  4974. }
  4975. }
  4976. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  4977. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  4978. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  4979. }
  4980. static void 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) {
  4981. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  4982. GGML_ASSERT(width > 0);
  4983. GGML_ASSERT(height > 0);
  4984. GGML_ASSERT(src != nullptr);
  4985. // TODO: staging_offset is not used
  4986. // Check if dst is pinned memory
  4987. vk_buffer buf = nullptr;
  4988. size_t buf_offset = 0;
  4989. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  4990. std::vector<vk::BufferCopy> slices(1);
  4991. if (width == spitch && width == dpitch) {
  4992. // Only do single write if stride is equal
  4993. slices[0].srcOffset = offset;
  4994. slices[0].dstOffset = buf_offset;
  4995. slices[0].size = width * height;
  4996. } else {
  4997. slices.resize(height);
  4998. for (size_t i = 0; i < height; i++) {
  4999. slices[i].srcOffset = offset + i * spitch;
  5000. slices[i].dstOffset = buf_offset + i * dpitch;
  5001. slices[i].size = width;
  5002. }
  5003. }
  5004. if (buf != nullptr) {
  5005. // Memory is pinned, use as staging buffer
  5006. ggml_vk_sync_buffers(nullptr, subctx);
  5007. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  5008. return;
  5009. }
  5010. VK_LOG_DEBUG("STAGING");
  5011. if (!sync_staging) {
  5012. GGML_ABORT("Asynchronous read from non-pinned memory not supported");
  5013. }
  5014. // Fall back to staging buffer
  5015. const size_t copy_size = dpitch * height;
  5016. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  5017. vk_buffer& staging_buffer = src->device->sync_staging;
  5018. ggml_vk_sync_buffers(nullptr, subctx);
  5019. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  5020. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  5021. }
  5022. static void ggml_vk_buffer_read_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t size, bool sync_staging = false) {
  5023. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  5024. }
  5025. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  5026. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  5027. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  5028. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  5029. // the HW device to host copy path.
  5030. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  5031. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5032. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  5033. } else {
  5034. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5035. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5036. ggml_vk_ctx_begin(src->device, subctx);
  5037. ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  5038. ggml_vk_ctx_end(subctx);
  5039. ggml_vk_submit(subctx, src->device->fence);
  5040. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  5041. src->device->device.resetFences({ src->device->fence });
  5042. ggml_vk_queue_command_pools_cleanup(src->device);
  5043. for (auto& cpy : subctx->out_memcpys) {
  5044. memcpy(cpy.dst, cpy.src, cpy.n);
  5045. }
  5046. }
  5047. }
  5048. 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) {
  5049. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  5050. // Make sure both buffers are on same device
  5051. GGML_ASSERT(src->device == dst->device);
  5052. VkBufferCopy bc{ src_offset, dst_offset, size };
  5053. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  5054. }
  5055. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  5056. if (src->device == dst->device) {
  5057. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5058. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  5059. // Copy within the device
  5060. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5061. ggml_vk_ctx_begin(src->device, subctx);
  5062. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  5063. ggml_vk_ctx_end(subctx);
  5064. ggml_vk_submit(subctx, src->device->fence);
  5065. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  5066. src->device->device.resetFences({ src->device->fence });
  5067. ggml_vk_queue_command_pools_cleanup(src->device);
  5068. } else {
  5069. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  5070. // Copy device to device
  5071. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  5072. // Copy to src staging buffer
  5073. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  5074. // Copy to dst buffer
  5075. ggml_vk_buffer_write_2d(dst, dst_offset, src->device->sync_staging->ptr, 0, size, 1);
  5076. }
  5077. }
  5078. static void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5079. VK_LOG_DEBUG("ggml_vk_buffer_memset_async(" << offset << ", " << c << ", " << size << ")");
  5080. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5081. dst->device->uma) {
  5082. deferred_memset((uint8_t*)dst->ptr + offset, c, size, &ctx->memsets);
  5083. return;
  5084. }
  5085. // Fall back to GPU fillBuffer for non-UMA or non-host-visible buffers
  5086. ctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5087. }
  5088. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5089. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  5090. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5091. dst->device->uma) {
  5092. memset((uint8_t*)dst->ptr + offset, c, size);
  5093. return;
  5094. }
  5095. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5096. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5097. ggml_vk_ctx_begin(dst->device, subctx);
  5098. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5099. ggml_vk_ctx_end(subctx);
  5100. ggml_vk_submit(subctx, dst->device->fence);
  5101. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  5102. dst->device->device.resetFences({ dst->device->fence });
  5103. ggml_vk_queue_command_pools_cleanup(dst->device);
  5104. }
  5105. 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) {
  5106. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ", " << disable_split_k << ")");
  5107. if (disable_split_k) {
  5108. return 1;
  5109. }
  5110. uint32_t split_k = 1;
  5111. if (ctx->device->shader_core_count != 0 && m >= pipeline->wg_denoms[0] && n >= pipeline->wg_denoms[1]) {
  5112. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  5113. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  5114. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  5115. if (k >= 2048) {
  5116. if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) {
  5117. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  5118. } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) {
  5119. split_k = 3;
  5120. }
  5121. // Cap the split at 8x. Unless k is huge this is a lot of overhead.
  5122. split_k = std::min(split_k, 8u);
  5123. // ggml_vk_matmul will align the splits to be a multiple of 256.
  5124. // If this rounded up size would cause the last split to be empty,
  5125. // then reduce the split count.
  5126. while (true) {
  5127. if (split_k == 1) {
  5128. break;
  5129. }
  5130. uint32_t k_split = CEIL_DIV(k, split_k);
  5131. k_split = ROUNDUP_POW2(k_split, 256);
  5132. if (k_split * (split_k - 1) < k) {
  5133. break;
  5134. }
  5135. split_k--;
  5136. }
  5137. }
  5138. }
  5139. return split_k;
  5140. }
  5141. 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) {
  5142. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5143. if (ctx->device->coopmat2) {
  5144. const uint32_t shader_core_count = ctx->device->shader_core_count;
  5145. const uint32_t tiles_l = CEIL_DIV(m, mmp->a_l->wg_denoms[0]) * CEIL_DIV(n, mmp->a_l->wg_denoms[1]);
  5146. const uint32_t tiles_m = CEIL_DIV(m, mmp->a_m->wg_denoms[0]) * CEIL_DIV(n, mmp->a_m->wg_denoms[1]);
  5147. // Use large shader when the N dimension is greater than the medium shader's tile size
  5148. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5149. // Prefer large over medium if either:
  5150. // - medium or large tiles would overfill the GPU
  5151. // - large tiles with a split_k==3 fits in the GPU and medium tiles with split_k==2 does not
  5152. // (medium with split_k==2 is probably better if it fits - more workgroups running and less split_k overhead)
  5153. bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count ||
  5154. // split_k==3 with large tiles likely better than medium tiles with no split_k.
  5155. (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2);
  5156. 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])) {
  5157. return aligned ? mmp->a_l : mmp->l;
  5158. }
  5159. // Use medium shader when the N dimension is greater than the small shader's tile size
  5160. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5161. if ((ctx->device->mul_mat_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_s[src0_type]) {
  5162. return aligned ? mmp->a_m : mmp->m;
  5163. }
  5164. return aligned ? mmp->a_s : mmp->s;
  5165. }
  5166. 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])) {
  5167. return aligned ? mmp->a_s : mmp->s;
  5168. }
  5169. if ((ctx->device->mul_mat_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l[src0_type]) {
  5170. return aligned ? mmp->a_m : mmp->m;
  5171. }
  5172. return aligned ? mmp->a_l : mmp->l;
  5173. GGML_UNUSED(src1_type);
  5174. }
  5175. 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) {
  5176. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5177. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, src0_type, src1_type)->align;
  5178. }
  5179. static void ggml_vk_matmul(
  5180. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5181. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  5182. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5183. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5184. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3,
  5185. uint32_t padded_n) {
  5186. 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 << ")");
  5187. if (split_k == 1) {
  5188. 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 };
  5189. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc, { m, n, batch });
  5190. return;
  5191. }
  5192. if (ctx->prealloc_split_k_need_sync) {
  5193. ggml_vk_sync_buffers(ctx, subctx);
  5194. }
  5195. GGML_ASSERT(batch_stride_d == m * n);
  5196. // Round the split size up to a multiple of 256 (k-quant alignment)
  5197. uint32_t k_split = CEIL_DIV(k, split_k);
  5198. k_split = ROUNDUP_POW2(k_split, 256);
  5199. 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 };
  5200. // Make sure enough workgroups get assigned for split k to work
  5201. 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 });
  5202. ggml_vk_sync_buffers(ctx, subctx);
  5203. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  5204. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 });
  5205. ctx->prealloc_split_k_need_sync = true;
  5206. }
  5207. 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) {
  5208. VK_LOG_DEBUG("ggml_vk_guess_matmul_id_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ")");
  5209. if (ctx->device->coopmat2) {
  5210. // Use large shader when the N dimension is greater than the medium shader's tile size
  5211. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5212. 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])) {
  5213. return aligned ? mmp->a_l : mmp->l;
  5214. }
  5215. // Use medium shader when the N dimension is greater than the small shader's tile size
  5216. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5217. if ((ctx->device->mul_mat_id_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_id_s[src0_type]) {
  5218. return aligned ? mmp->a_m : mmp->m;
  5219. }
  5220. return aligned ? mmp->a_s : mmp->s;
  5221. }
  5222. 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])) {
  5223. return aligned ? mmp->a_s : mmp->s;
  5224. }
  5225. if ((ctx->device->mul_mat_id_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l[src0_type]) {
  5226. return aligned ? mmp->a_m : mmp->m;
  5227. }
  5228. return aligned ? mmp->a_l : mmp->l;
  5229. }
  5230. 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) {
  5231. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ")");
  5232. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true, src0_type)->align;
  5233. }
  5234. static void ggml_vk_matmul_id(
  5235. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5236. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  5237. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5238. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5239. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11,
  5240. uint32_t padded_n) {
  5241. 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 << "), " <<
  5242. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  5243. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  5244. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  5245. 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,
  5246. nei0, nei1, nbi1, ne11, padded_n };
  5247. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, pc, { m, nei1, n_as });
  5248. }
  5249. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  5250. return
  5251. tensor->nb[0] == ggml_type_size(tensor->type) &&
  5252. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  5253. (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]);
  5254. }
  5255. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  5256. // Choose "contiguous copy" shader if src/dst are contiguous
  5257. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  5258. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  5259. if (contig) {
  5260. return ctx->device->pipeline_contig_cpy_f32_f32;
  5261. } else {
  5262. return ctx->device->pipeline_cpy_f32_f32;
  5263. }
  5264. }
  5265. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  5266. if (contig) {
  5267. return ctx->device->pipeline_contig_cpy_f32_f16;
  5268. } else {
  5269. return ctx->device->pipeline_cpy_f32_f16;
  5270. }
  5271. }
  5272. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  5273. if (contig) {
  5274. return ctx->device->pipeline_contig_cpy_f16_f16;
  5275. } else {
  5276. return ctx->device->pipeline_cpy_f16_f16;
  5277. }
  5278. }
  5279. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) {
  5280. if (contig) {
  5281. return ctx->device->pipeline_contig_cpy_f16_f32;
  5282. } else {
  5283. return ctx->device->pipeline_cpy_f16_f32;
  5284. }
  5285. }
  5286. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) {
  5287. if (contig) {
  5288. return ctx->device->pipeline_contig_cpy_f32_bf16;
  5289. } else {
  5290. return ctx->device->pipeline_cpy_f32_bf16;
  5291. }
  5292. }
  5293. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
  5294. if (contig) {
  5295. return ctx->device->pipeline_contig_cpy_f32_i32;
  5296. } else {
  5297. return ctx->device->pipeline_cpy_f32_i32;
  5298. }
  5299. }
  5300. if (src->type == GGML_TYPE_I32 && to == GGML_TYPE_F32) {
  5301. if (contig) {
  5302. return ctx->device->pipeline_contig_cpy_i32_f32;
  5303. } else {
  5304. return ctx->device->pipeline_cpy_i32_f32;
  5305. }
  5306. }
  5307. if (src->type == GGML_TYPE_F32) {
  5308. switch (to) {
  5309. case GGML_TYPE_Q4_0:
  5310. case GGML_TYPE_Q4_1:
  5311. case GGML_TYPE_Q5_0:
  5312. case GGML_TYPE_Q5_1:
  5313. case GGML_TYPE_Q8_0:
  5314. case GGML_TYPE_IQ4_NL:
  5315. return ctx->device->pipeline_cpy_f32_quant[to];
  5316. default:
  5317. break;
  5318. }
  5319. }
  5320. if (to == GGML_TYPE_F32) {
  5321. switch (src->type) {
  5322. case GGML_TYPE_Q4_0:
  5323. case GGML_TYPE_Q4_1:
  5324. case GGML_TYPE_Q5_0:
  5325. case GGML_TYPE_Q5_1:
  5326. case GGML_TYPE_Q8_0:
  5327. case GGML_TYPE_IQ4_NL:
  5328. return ctx->device->pipeline_cpy_quant_f32[src->type];
  5329. default:
  5330. break;
  5331. }
  5332. }
  5333. if (src->type == to) {
  5334. // Copy two or four bytes at a time, depending on block size.
  5335. // For quantized types, we scale by block size/type size. But
  5336. // this path is also used for bf16->bf16 for example, where the
  5337. // type size must be exactly 2 or 4.
  5338. GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4);
  5339. if ((ggml_type_size(src->type) % 4) == 0) {
  5340. if (contig) {
  5341. return ctx->device->pipeline_contig_cpy_f32_f32;
  5342. } else {
  5343. return ctx->device->pipeline_cpy_f32_f32;
  5344. }
  5345. } else {
  5346. if (contig) {
  5347. return ctx->device->pipeline_contig_cpy_f16_f16;
  5348. } else {
  5349. return ctx->device->pipeline_cpy_f16_f16;
  5350. }
  5351. }
  5352. }
  5353. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  5354. GGML_ABORT("fatal error");
  5355. }
  5356. static void ggml_vk_cpy_to_contiguous(ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline pipeline, const ggml_tensor * tensor, vk_subbuffer&& in, vk_subbuffer&& out) {
  5357. 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] << "), ";
  5358. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  5359. const int tensor_type_size = ggml_type_size(tensor->type);
  5360. const uint32_t ne = ggml_nelements(tensor);
  5361. std::array<uint32_t, 3> elements;
  5362. if (ne > 262144) {
  5363. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  5364. } else if (ne > 512) {
  5365. elements = { 512, CEIL_DIV(ne, 512), 1 };
  5366. } else {
  5367. elements = { ne, 1, 1 };
  5368. }
  5369. vk_op_unary_push_constants pc = {
  5370. (uint32_t)ne,
  5371. (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,
  5372. (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]),
  5373. 0,
  5374. 0.0f, 0.0f,
  5375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5376. };
  5377. init_pushconst_fastdiv(pc);
  5378. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements);
  5379. ggml_vk_sync_buffers(ctx, subctx);
  5380. }
  5381. static vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type) {
  5382. switch(type) {
  5383. case GGML_TYPE_Q8_1:
  5384. return ctx->device->pipeline_quantize_q8_1_x4;
  5385. default:
  5386. std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl;
  5387. GGML_ABORT("fatal error");
  5388. }
  5389. }
  5390. static void ggml_vk_quantize_q8_1(ggml_backend_vk_context * ctx, vk_context& subctx, vk_subbuffer&& in, vk_subbuffer&& out, uint32_t ne) {
  5391. VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")");
  5392. vk_pipeline pipeline = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5393. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, std::array<uint32_t, 1>{ne}, { ne, 1, 1 });
  5394. ggml_vk_sync_buffers(ctx, subctx);
  5395. }
  5396. 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) {
  5397. 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];
  5398. 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];
  5399. 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];
  5400. std::cerr << "))");
  5401. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5402. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5403. const uint64_t ne00 = src0->ne[0];
  5404. const uint64_t ne01 = src0->ne[1];
  5405. const uint64_t ne02 = src0->ne[2];
  5406. const uint64_t ne03 = src0->ne[3];
  5407. const uint64_t ne10 = src1->ne[0];
  5408. const uint64_t ne11 = src1->ne[1];
  5409. const uint64_t ne12 = src1->ne[2];
  5410. const uint64_t ne13 = src1->ne[3];
  5411. const uint64_t ne21 = dst->ne[1];
  5412. const uint32_t stride_d = dst->nb[1] / ggml_type_size(dst->type);
  5413. const uint32_t stride_batch_d = stride_d*ne21;
  5414. const uint64_t r2 = ne12 / ne02;
  5415. const uint64_t r3 = ne13 / ne03;
  5416. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5417. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5418. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5419. vk_buffer d_Qx = nullptr;
  5420. size_t qx_buf_offset = 0;
  5421. vk_buffer d_Qy = nullptr;
  5422. size_t qy_buf_offset = 0;
  5423. bool src0_uma = false;
  5424. bool src1_uma = false;
  5425. if (ctx->device->uma) {
  5426. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5427. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5428. src0_uma = d_Qx != nullptr;
  5429. src1_uma = d_Qy != nullptr;
  5430. }
  5431. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5432. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5433. !ggml_vk_dim01_contiguous(src0);
  5434. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5435. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5436. !ggml_vk_dim01_contiguous(src1);
  5437. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5438. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5439. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5440. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0;
  5441. // Check for mmq first
  5442. 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;
  5443. if (mmp == nullptr) {
  5444. // Fall back to f16 dequant mul mat
  5445. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  5446. quantize_y = false;
  5447. }
  5448. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5449. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  5450. if (qx_needs_dequant) {
  5451. // Fall back to dequant + f16 mulmat
  5452. 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]);
  5453. }
  5454. // Not implemented
  5455. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5456. 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)));
  5457. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8;
  5458. 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));
  5459. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  5460. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11;
  5461. const uint64_t x_ne = ggml_nelements(src0);
  5462. // 128 elements per Q8_1 x4 block
  5463. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  5464. const uint64_t d_ne = ggml_nelements(dst);
  5465. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline);
  5466. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  5467. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5468. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  5469. 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);
  5470. const uint64_t d_sz = sizeof(float) * d_ne;
  5471. vk_pipeline to_fp16_vk_0 = nullptr;
  5472. vk_pipeline to_fp16_vk_1 = nullptr;
  5473. vk_pipeline to_q8_1 = nullptr;
  5474. if (x_non_contig) {
  5475. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  5476. } else {
  5477. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  5478. }
  5479. if (y_non_contig) {
  5480. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  5481. } else {
  5482. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5483. }
  5484. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5485. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5486. if (quantize_y) {
  5487. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5488. }
  5489. {
  5490. const uint64_t split_k_size = split_k > 1 ? d_sz * split_k : 0;
  5491. if (
  5492. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  5493. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  5494. (split_k > 1 && split_k_size > ctx->device->properties.limits.maxStorageBufferRange)) {
  5495. GGML_ABORT("Requested preallocation size is too large");
  5496. }
  5497. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  5498. ctx->prealloc_size_x = x_sz;
  5499. ggml_vk_preallocate_buffers(ctx, subctx);
  5500. }
  5501. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  5502. ctx->prealloc_size_y = y_sz;
  5503. ggml_vk_preallocate_buffers(ctx, subctx);
  5504. }
  5505. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  5506. ctx->prealloc_size_split_k = split_k_size;
  5507. ggml_vk_preallocate_buffers(ctx, subctx);
  5508. }
  5509. // Request descriptor sets
  5510. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  5511. if (qx_needs_dequant) {
  5512. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5513. }
  5514. if (qy_needs_dequant) {
  5515. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5516. }
  5517. if (quantize_y) {
  5518. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5519. }
  5520. if (split_k > 1) {
  5521. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  5522. }
  5523. }
  5524. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5525. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5526. GGML_ASSERT(d_D != nullptr);
  5527. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz);
  5528. vk_buffer d_X;
  5529. uint64_t x_buf_offset = 0;
  5530. vk_buffer d_Y;
  5531. uint64_t y_buf_offset = 0;
  5532. if (!src0_uma) {
  5533. d_Qx = src0_buf_ctx->dev_buffer;
  5534. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5535. GGML_ASSERT(d_Qx != nullptr);
  5536. }
  5537. if (!src1_uma) {
  5538. d_Qy = src1_buf_ctx->dev_buffer;
  5539. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5540. GGML_ASSERT(d_Qy != nullptr);
  5541. }
  5542. if (qx_needs_dequant) {
  5543. d_X = ctx->prealloc_x;
  5544. GGML_ASSERT(d_X->size >= x_sz);
  5545. } else {
  5546. d_X = d_Qx;
  5547. x_buf_offset = qx_buf_offset;
  5548. GGML_ASSERT(qx_sz == x_sz);
  5549. }
  5550. if (qy_needs_dequant) {
  5551. d_Y = ctx->prealloc_y;
  5552. GGML_ASSERT(d_Y->size >= y_sz);
  5553. } else if (quantize_y) {
  5554. d_Y = ctx->prealloc_y;
  5555. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  5556. } else {
  5557. d_Y = d_Qy;
  5558. y_buf_offset = qy_buf_offset;
  5559. GGML_ASSERT(qy_sz == y_sz);
  5560. }
  5561. if (x_non_contig || qx_needs_dequant) {
  5562. if (ctx->prealloc_x_need_sync) {
  5563. ggml_vk_sync_buffers(ctx, subctx);
  5564. }
  5565. }
  5566. if (x_non_contig) {
  5567. 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));
  5568. } else if (qx_needs_dequant) {
  5569. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  5570. 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});
  5571. ggml_vk_sync_buffers(ctx, subctx);
  5572. }
  5573. if (y_non_contig) {
  5574. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5575. ctx->prealloc_y_last_tensor_used != src1) {
  5576. if (ctx->prealloc_y_need_sync) {
  5577. ggml_vk_sync_buffers(ctx, subctx);
  5578. }
  5579. 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));
  5580. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5581. ctx->prealloc_y_last_tensor_used = src1;
  5582. }
  5583. }
  5584. if (quantize_y) {
  5585. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5586. ctx->prealloc_y_last_tensor_used != src1) {
  5587. if (ctx->prealloc_y_need_sync) {
  5588. ggml_vk_sync_buffers(ctx, subctx);
  5589. }
  5590. 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);
  5591. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5592. ctx->prealloc_y_last_tensor_used = src1;
  5593. }
  5594. }
  5595. uint32_t stride_batch_x = ne00*ne01;
  5596. uint32_t stride_batch_y = ne10*ne11;
  5597. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5598. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5599. }
  5600. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  5601. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5602. }
  5603. // compute
  5604. ggml_vk_matmul(
  5605. ctx, subctx, pipeline,
  5606. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  5607. ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, d_sz * split_k },
  5608. ne01, ne11, ne10,
  5609. ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d,
  5610. split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n
  5611. ); // NOLINT
  5612. if (x_non_contig || qx_needs_dequant) {
  5613. ctx->prealloc_x_need_sync = true;
  5614. }
  5615. if (y_non_contig || quantize_y) {
  5616. ctx->prealloc_y_need_sync = true;
  5617. }
  5618. }
  5619. // Device tuning
  5620. static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_t n, uint32_t k, ggml_type src0_type) {
  5621. if (device->mmvq_mode == 1) {
  5622. return true;
  5623. } else if (device->mmvq_mode == -1) {
  5624. return false;
  5625. }
  5626. // MMVQ is generally good for batches
  5627. if (n > 1) {
  5628. return true;
  5629. }
  5630. switch (device->vendor_id) {
  5631. case VK_VENDOR_ID_NVIDIA:
  5632. switch (src0_type) {
  5633. case GGML_TYPE_Q8_0:
  5634. return device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  5635. default:
  5636. return true;
  5637. }
  5638. case VK_VENDOR_ID_AMD:
  5639. switch (src0_type) {
  5640. case GGML_TYPE_Q8_0:
  5641. return device->architecture == vk_device_architecture::AMD_GCN;
  5642. default:
  5643. return true;
  5644. }
  5645. case VK_VENDOR_ID_INTEL:
  5646. switch (src0_type) {
  5647. // From tests on A770 Linux, may need more tuning
  5648. case GGML_TYPE_Q4_0:
  5649. case GGML_TYPE_Q5_1:
  5650. return false;
  5651. default:
  5652. return true;
  5653. }
  5654. default:
  5655. return true;
  5656. }
  5657. GGML_UNUSED(m);
  5658. GGML_UNUSED(k);
  5659. }
  5660. 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) {
  5661. ggml_tensor * dst = cgraph->nodes[node_idx];
  5662. const ggml_tensor * src0 = dst->src[0];
  5663. const ggml_tensor * src1 = dst->src[1];
  5664. 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];
  5665. 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];
  5666. 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];
  5667. std::cerr << ")),)");
  5668. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5669. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5670. const uint64_t ne00 = src0->ne[0];
  5671. const uint64_t ne01 = src0->ne[1];
  5672. const uint64_t ne02 = src0->ne[2];
  5673. const uint64_t ne03 = src0->ne[3];
  5674. const uint64_t ne10 = src1->ne[0];
  5675. const uint64_t ne11 = src1->ne[1];
  5676. const uint64_t ne12 = src1->ne[2];
  5677. const uint64_t ne13 = src1->ne[3];
  5678. const uint64_t ne20 = dst->ne[0];
  5679. const uint64_t ne21 = dst->ne[1];
  5680. // const uint64_t ne22 = dst->ne[2];
  5681. // const uint64_t ne23 = dst->ne[3];
  5682. const uint64_t r2 = ne12 / ne02;
  5683. const uint64_t r3 = ne13 / ne03;
  5684. // batch_n indicates that we need to compute a few vector results, and this assumes
  5685. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  5686. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  5687. bool batch_n = ne11 > 1;
  5688. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5689. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5690. vk_buffer d_Qx = nullptr;
  5691. size_t qx_buf_offset = 0;
  5692. vk_buffer d_Qy = nullptr;
  5693. size_t qy_buf_offset = 0;
  5694. bool src0_uma = false;
  5695. bool src1_uma = false;
  5696. if (ctx->device->uma) {
  5697. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5698. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5699. src0_uma = d_Qx != nullptr;
  5700. src1_uma = d_Qy != nullptr;
  5701. }
  5702. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  5703. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  5704. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  5705. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0 && ggml_vk_should_use_mmvq(ctx->device, ne01, ne11, ne10, src0->type);
  5706. vk_pipeline to_fp16_vk_0 = nullptr;
  5707. vk_pipeline to_fp16_vk_1 = nullptr;
  5708. if (x_non_contig) {
  5709. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  5710. }
  5711. if (y_non_contig) {
  5712. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  5713. } else {
  5714. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5715. }
  5716. // Check for mmq first
  5717. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr;
  5718. vk_pipeline to_q8_1 = nullptr;
  5719. if (dmmv == nullptr) {
  5720. // Fall back to f16 dequant mul mat
  5721. dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11, ne20, ne00);
  5722. quantize_y = false;
  5723. }
  5724. if (quantize_y) {
  5725. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5726. }
  5727. const bool qx_needs_dequant = x_non_contig;
  5728. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  5729. // Not implemented
  5730. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5731. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5732. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5733. GGML_ASSERT(dmmv != nullptr);
  5734. const uint64_t x_ne = ggml_nelements(src0);
  5735. const uint64_t y_ne = ggml_nelements(src1);
  5736. const uint64_t d_ne = ggml_nelements(dst);
  5737. 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);
  5738. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5739. 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;
  5740. 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)) :
  5741. (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  5742. const uint64_t d_sz = sizeof(float) * d_ne;
  5743. {
  5744. if (
  5745. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  5746. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  5747. GGML_ABORT("Requested preallocation size is too large");
  5748. }
  5749. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  5750. ctx->prealloc_size_x = x_sz;
  5751. ggml_vk_preallocate_buffers(ctx, subctx);
  5752. }
  5753. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  5754. ctx->prealloc_size_y = y_sz;
  5755. ggml_vk_preallocate_buffers(ctx, subctx);
  5756. }
  5757. // Request descriptor sets
  5758. if (qx_needs_dequant) {
  5759. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5760. }
  5761. if (qy_needs_dequant) {
  5762. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5763. }
  5764. if (quantize_y) {
  5765. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5766. }
  5767. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  5768. }
  5769. vk_buffer d_D;
  5770. uint64_t d_buf_offset = 0;
  5771. if (ctx->num_additional_fused_ops > 0) {
  5772. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  5773. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)add->buffer->context;
  5774. d_D = dst_buf_ctx->dev_buffer;
  5775. d_buf_offset = vk_tensor_offset(add) + add->view_offs;
  5776. } else {
  5777. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5778. d_D = dst_buf_ctx->dev_buffer;
  5779. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5780. }
  5781. GGML_ASSERT(d_D != nullptr);
  5782. vk_buffer d_X;
  5783. uint64_t x_buf_offset = 0;
  5784. vk_buffer d_Y;
  5785. uint64_t y_buf_offset = 0;
  5786. if(!src0_uma) {
  5787. d_Qx = src0_buf_ctx->dev_buffer;
  5788. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5789. GGML_ASSERT(d_Qx != nullptr);
  5790. }
  5791. if(!src1_uma) {
  5792. d_Qy = src1_buf_ctx->dev_buffer;
  5793. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5794. GGML_ASSERT(d_Qy != nullptr);
  5795. }
  5796. if (qx_needs_dequant) {
  5797. d_X = ctx->prealloc_x;
  5798. } else {
  5799. d_X = d_Qx;
  5800. x_buf_offset = qx_buf_offset;
  5801. GGML_ASSERT(qx_sz == x_sz);
  5802. }
  5803. if (qy_needs_dequant) {
  5804. d_Y = ctx->prealloc_y;
  5805. } else if (quantize_y) {
  5806. d_Y = ctx->prealloc_y;
  5807. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  5808. } else {
  5809. d_Y = d_Qy;
  5810. y_buf_offset = qy_buf_offset;
  5811. GGML_ASSERT(qy_sz == y_sz);
  5812. }
  5813. if (x_non_contig) {
  5814. if (ctx->prealloc_x_need_sync) {
  5815. ggml_vk_sync_buffers(ctx, subctx);
  5816. }
  5817. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  5818. 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));
  5819. }
  5820. if (y_non_contig) {
  5821. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  5822. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5823. ctx->prealloc_y_last_tensor_used != src1) {
  5824. if (ctx->prealloc_y_need_sync) {
  5825. ggml_vk_sync_buffers(ctx, subctx);
  5826. }
  5827. 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));
  5828. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5829. ctx->prealloc_y_last_tensor_used = src1;
  5830. }
  5831. }
  5832. if (quantize_y) {
  5833. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5834. ctx->prealloc_y_last_tensor_used != src1) {
  5835. if (ctx->prealloc_y_need_sync) {
  5836. ggml_vk_sync_buffers(ctx, subctx);
  5837. }
  5838. 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);
  5839. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5840. ctx->prealloc_y_last_tensor_used = src1;
  5841. }
  5842. }
  5843. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  5844. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  5845. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  5846. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  5847. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5848. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5849. }
  5850. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  5851. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5852. }
  5853. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  5854. uint32_t groups_x = ne01;
  5855. uint32_t groups_z = 1;
  5856. if (ne01 > max_groups_x) {
  5857. groups_z = 64;
  5858. groups_x = CEIL_DIV(groups_x, groups_z);
  5859. }
  5860. uint32_t enable_bias = ctx->num_additional_fused_ops > 0;
  5861. vk_buffer d_B = d_D;
  5862. size_t b_buf_offset = 0;
  5863. uint64_t b_sz = 0;
  5864. if (enable_bias) {
  5865. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  5866. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  5867. bool b_uma = false;
  5868. if (ctx->device->uma) {
  5869. ggml_vk_host_get(ctx->device, bias->data, d_B, b_buf_offset);
  5870. b_uma = d_B != nullptr;
  5871. }
  5872. if(!b_uma) {
  5873. ggml_backend_vk_buffer_context * bias_buf_ctx = (ggml_backend_vk_buffer_context *)bias->buffer->context;
  5874. d_B = bias_buf_ctx->dev_buffer;
  5875. b_buf_offset = vk_tensor_offset(bias) + bias->view_offs;
  5876. GGML_ASSERT(d_B != nullptr);
  5877. b_sz = ggml_nbytes(bias);
  5878. }
  5879. }
  5880. // compute
  5881. const vk_mat_vec_push_constants pc = {
  5882. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  5883. stride_batch_x, stride_batch_y, stride_batch_d, enable_bias, 0,
  5884. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  5885. };
  5886. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  5887. {
  5888. vk_subbuffer{ d_X, x_buf_offset, x_sz },
  5889. vk_subbuffer{ d_Y, y_buf_offset, y_sz },
  5890. vk_subbuffer{ d_D, d_buf_offset, d_sz },
  5891. vk_subbuffer{ d_B, b_buf_offset, b_sz },
  5892. },
  5893. pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  5894. if (x_non_contig) {
  5895. ctx->prealloc_x_need_sync = true;
  5896. }
  5897. if (y_non_contig || quantize_y) {
  5898. ctx->prealloc_y_need_sync = true;
  5899. }
  5900. }
  5901. 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) {
  5902. ggml_tensor * dst = cgraph->nodes[node_idx];
  5903. const ggml_tensor * src0 = dst->src[0];
  5904. const ggml_tensor * src1 = dst->src[1];
  5905. 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];
  5906. 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];
  5907. 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];
  5908. std::cerr << "))");
  5909. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  5910. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  5911. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  5912. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  5913. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  5914. const uint64_t ne00 = src0->ne[0];
  5915. const uint64_t ne01 = src0->ne[1];
  5916. const uint64_t ne02 = src0->ne[2];
  5917. // const uint64_t ne03 = src0->ne[3];
  5918. const uint64_t ne10 = src1->ne[0];
  5919. const uint64_t ne11 = src1->ne[1];
  5920. const uint64_t ne12 = src1->ne[2];
  5921. // const uint64_t ne13 = src1->ne[3];
  5922. GGML_ASSERT(ne11 == 1);
  5923. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5924. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5925. vk_buffer d_Qy = nullptr;
  5926. size_t qy_buf_offset = 0;
  5927. bool src1_uma = false;
  5928. if (ctx->device->uma) {
  5929. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5930. src1_uma = d_Qy != nullptr;
  5931. }
  5932. const uint64_t x_ne = ne00 * ne01 * ne02;
  5933. const uint64_t y_ne = ne10 * ne11 * ne12;
  5934. const uint64_t d_ne = ne01 * ne11 * ne12;
  5935. 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);
  5936. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5937. const uint64_t d_sz = sizeof(float) * d_ne;
  5938. // With grouped query attention there are > 1 Q matrices per K, V matrix.
  5939. uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02;
  5940. if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) {
  5941. gqa_ratio = 1;
  5942. }
  5943. {
  5944. // Request descriptor sets
  5945. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], 1);
  5946. }
  5947. vk_buffer d_D;
  5948. uint64_t d_buf_offset = 0;
  5949. if (ctx->num_additional_fused_ops > 0) {
  5950. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  5951. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)add->buffer->context;
  5952. d_D = dst_buf_ctx->dev_buffer;
  5953. d_buf_offset = vk_tensor_offset(add) + add->view_offs;
  5954. } else {
  5955. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5956. d_D = dst_buf_ctx->dev_buffer;
  5957. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5958. }
  5959. GGML_ASSERT(d_D != nullptr);
  5960. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  5961. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5962. GGML_ASSERT(d_Qx != nullptr);
  5963. if (!src1_uma) {
  5964. d_Qy = src1_buf_ctx->dev_buffer;
  5965. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5966. GGML_ASSERT(d_Qx != nullptr);
  5967. }
  5968. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5969. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  5970. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5971. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  5972. uint32_t enable_bias = ctx->num_additional_fused_ops > 0;
  5973. vk_buffer d_B = d_D;
  5974. size_t b_buf_offset = 0;
  5975. uint64_t b_sz = 0;
  5976. if (enable_bias) {
  5977. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  5978. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  5979. bool b_uma = false;
  5980. if (ctx->device->uma) {
  5981. ggml_vk_host_get(ctx->device, bias->data, d_B, b_buf_offset);
  5982. b_uma = d_B != nullptr;
  5983. }
  5984. if(!b_uma) {
  5985. ggml_backend_vk_buffer_context * bias_buf_ctx = (ggml_backend_vk_buffer_context *)bias->buffer->context;
  5986. d_B = bias_buf_ctx->dev_buffer;
  5987. b_buf_offset = vk_tensor_offset(bias) + bias->view_offs;
  5988. GGML_ASSERT(d_B != nullptr);
  5989. b_sz = ggml_nbytes(bias);
  5990. }
  5991. }
  5992. // compute
  5993. const std::array<uint32_t, 7> pc = { (uint32_t)ne00, (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne12, (uint32_t)(qy_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type)), enable_bias };
  5994. uint32_t workgroups_z = (uint32_t)ne12;
  5995. // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups
  5996. if (gqa_ratio > 1) {
  5997. workgroups_z /= gqa_ratio;
  5998. }
  5999. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1],
  6000. {
  6001. vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz },
  6002. vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset },
  6003. vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset },
  6004. vk_subbuffer{ d_B, b_buf_offset, b_sz },
  6005. }, pc, { 1, (uint32_t)ne01, workgroups_z });
  6006. }
  6007. 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) {
  6008. ggml_tensor * dst = cgraph->nodes[node_idx];
  6009. const ggml_tensor * src0 = dst->src[0];
  6010. const ggml_tensor * src1 = dst->src[1];
  6011. 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];
  6012. 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];
  6013. 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];
  6014. std::cerr << "))");
  6015. GGML_ASSERT(!ggml_is_transposed(src0));
  6016. GGML_ASSERT(!ggml_is_transposed(src1));
  6017. GGML_ASSERT(!ggml_is_permuted(src0));
  6018. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6019. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6020. const uint64_t ne00 = src0->ne[0];
  6021. const uint64_t ne01 = src0->ne[1];
  6022. const uint64_t ne02 = src0->ne[2];
  6023. const uint64_t ne03 = src0->ne[3];
  6024. const uint64_t nb01 = src0->nb[1];
  6025. const uint64_t nb02 = src0->nb[2];
  6026. const uint64_t nb12 = src1->nb[2];
  6027. // const uint64_t ne10 = src1->ne[0];
  6028. const uint64_t ne11 = src1->ne[1];
  6029. const uint64_t ne12 = src1->ne[2];
  6030. // const uint64_t ne13 = src1->ne[3];
  6031. const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t));
  6032. const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float));
  6033. const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float));
  6034. GGML_ASSERT(ne11 == 1);
  6035. GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in supports_op
  6036. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6037. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6038. vk_buffer d_Qy = nullptr;
  6039. size_t qy_buf_offset = 0;
  6040. bool src1_uma = false;
  6041. if (ctx->device->uma) {
  6042. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6043. src1_uma = d_Qy != nullptr;
  6044. }
  6045. const uint64_t d_ne = ne01 * ne11 * ne12 * ne03;
  6046. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  6047. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  6048. const uint32_t channel_stride_y = nb12 / sizeof(float);
  6049. const uint64_t qx_sz = ggml_nbytes(src0);
  6050. const uint64_t qy_sz = ggml_nbytes(src1);
  6051. const uint64_t d_sz = sizeof(float) * d_ne;
  6052. {
  6053. // Request descriptor sets
  6054. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  6055. }
  6056. vk_buffer d_D;
  6057. uint64_t d_buf_offset = 0;
  6058. if (ctx->num_additional_fused_ops > 0) {
  6059. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6060. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)add->buffer->context;
  6061. d_D = dst_buf_ctx->dev_buffer;
  6062. d_buf_offset = vk_tensor_offset(add) + add->view_offs;
  6063. } else {
  6064. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6065. d_D = dst_buf_ctx->dev_buffer;
  6066. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6067. }
  6068. GGML_ASSERT(d_D != nullptr);
  6069. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  6070. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6071. GGML_ASSERT(d_Qx != nullptr);
  6072. if (!src1_uma) {
  6073. d_Qy = src1_buf_ctx->dev_buffer;
  6074. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6075. GGML_ASSERT(d_Qx != nullptr);
  6076. }
  6077. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  6078. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  6079. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  6080. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  6081. uint32_t enable_bias = ctx->num_additional_fused_ops > 0;
  6082. vk_buffer d_B = d_D;
  6083. size_t b_buf_offset = 0;
  6084. uint64_t b_sz = 0;
  6085. if (enable_bias) {
  6086. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6087. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6088. bool b_uma = false;
  6089. if (ctx->device->uma) {
  6090. ggml_vk_host_get(ctx->device, bias->data, d_B, b_buf_offset);
  6091. b_uma = d_B != nullptr;
  6092. }
  6093. if(!b_uma) {
  6094. ggml_backend_vk_buffer_context * bias_buf_ctx = (ggml_backend_vk_buffer_context *)bias->buffer->context;
  6095. d_B = bias_buf_ctx->dev_buffer;
  6096. b_buf_offset = vk_tensor_offset(bias) + bias->view_offs;
  6097. GGML_ASSERT(d_B != nullptr);
  6098. b_sz = ggml_nbytes(bias);
  6099. }
  6100. }
  6101. // compute
  6102. const std::array<uint32_t, 13> pc = { (uint32_t)ne00, (uint32_t)ne01, row_stride_x, channel_stride_x, channel_stride_y, (uint32_t)(ne12 / ne02), (uint32_t)ne12, (uint32_t)(qy_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type)), nb03, nb13, nb23, enable_bias };
  6103. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  6104. {
  6105. vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz },
  6106. vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset },
  6107. vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset },
  6108. vk_subbuffer{ d_B, b_buf_offset, b_sz },
  6109. }, pc, { (uint32_t)ne03, (uint32_t)ne01, (uint32_t)ne12 });
  6110. }
  6111. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6112. ggml_tensor * dst = cgraph->nodes[node_idx];
  6113. ggml_tensor * src0 = dst->src[0];
  6114. ggml_tensor * src1 = dst->src[1];
  6115. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  6116. // Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases
  6117. // where the M dimension is very large.
  6118. // Split_k doesn't work with M splitting.
  6119. const size_t nbytes = ggml_nbytes(src0);
  6120. const bool needs_split = nbytes > ctx->device->properties.limits.maxStorageBufferRange;
  6121. if (needs_split) {
  6122. // Choose the number of rows that can fit (and divide by two, to allow for any additional offsets)
  6123. const uint32_t M_split = ctx->device->properties.limits.maxStorageBufferRange / (2 * src0->nb[1]);
  6124. uint32_t m_offset = 0;
  6125. while (m_offset < dst->ne[0]) {
  6126. const uint32_t cur_M_size = std::min(M_split, (uint32_t)(dst->ne[0] - m_offset));
  6127. ggml_tensor dst2 = *dst;
  6128. ggml_tensor src02 = *src0;
  6129. dst2.view_src = dst->view_src ? dst->view_src : dst;
  6130. src02.view_src = src0->view_src ? src0->view_src : src0;
  6131. dst2.view_offs += m_offset * dst->nb[0];
  6132. src02.view_offs += m_offset * src0->nb[1];
  6133. dst2.ne[0] = cur_M_size;
  6134. src02.ne[1] = cur_M_size;
  6135. ggml_vk_mul_mat_q_f16(ctx, subctx, &src02, src1, &dst2, true);
  6136. m_offset += cur_M_size;
  6137. }
  6138. } else if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  6139. // detect 0213 permutation, and batch size of 1
  6140. src0->nb[0] <= src0->nb[2] &&
  6141. src0->nb[2] <= src0->nb[1] &&
  6142. src0->nb[1] <= src0->nb[3] &&
  6143. src1->nb[0] <= src1->nb[2] &&
  6144. src1->nb[2] <= src1->nb[1] &&
  6145. src1->nb[1] <= src1->nb[3] &&
  6146. src0->ne[3] == 1 &&
  6147. src1->ne[3] == 1) {
  6148. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, cgraph, node_idx);
  6149. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  6150. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  6151. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, cgraph, node_idx);
  6152. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  6153. // when ne12 and ne13 are one.
  6154. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  6155. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
  6156. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx);
  6157. } else {
  6158. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false);
  6159. }
  6160. }
  6161. 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) {
  6162. 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];
  6163. 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];
  6164. 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];
  6165. 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] << "),)");
  6166. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6167. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6168. const uint64_t ne00 = src0->ne[0];
  6169. const uint64_t ne01 = src0->ne[1];
  6170. const uint64_t ne02 = src0->ne[2];
  6171. // const uint64_t ne03 = src0->ne[3];
  6172. const uint64_t ne10 = src1->ne[0];
  6173. const uint64_t ne11 = src1->ne[1];
  6174. const uint64_t ne12 = src1->ne[2];
  6175. const uint64_t ne13 = src1->ne[3];
  6176. const uint64_t nei0 = ids->ne[0];
  6177. const uint64_t nei1 = ids->ne[1];
  6178. const uint32_t nbi1 = ids->nb[1];
  6179. const uint32_t nbi2 = ids->nb[2];
  6180. const uint64_t ne20 = dst->ne[0];
  6181. const uint64_t ne21 = dst->ne[1];
  6182. // const uint64_t ne22 = dst->ne[2];
  6183. // const uint64_t ne23 = dst->ne[3];
  6184. const uint64_t n_as = ne02;
  6185. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6186. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6187. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6188. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6189. vk_buffer d_Qx = nullptr;
  6190. size_t qx_buf_offset = 0;
  6191. vk_buffer d_Qy = nullptr;
  6192. size_t qy_buf_offset = 0;
  6193. vk_buffer d_ids = nullptr;
  6194. size_t ids_buf_offset = 0;
  6195. bool src0_uma = false;
  6196. bool src1_uma = false;
  6197. bool ids_uma = false;
  6198. if (ctx->device->uma) {
  6199. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6200. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6201. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6202. src0_uma = d_Qx != nullptr;
  6203. src1_uma = d_Qy != nullptr;
  6204. ids_uma = d_ids != nullptr;
  6205. }
  6206. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  6207. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  6208. !ggml_vk_dim01_contiguous(src0);
  6209. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  6210. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  6211. !ggml_vk_dim01_contiguous(src1);
  6212. // If src0 is BF16, try to use a BF16 x BF16 multiply
  6213. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  6214. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  6215. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0;
  6216. // Check for mmq first
  6217. 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;
  6218. if (mmp == nullptr) {
  6219. // Fall back to f16 dequant mul mat
  6220. 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]);
  6221. quantize_y = false;
  6222. }
  6223. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  6224. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  6225. if (qx_needs_dequant) {
  6226. // Fall back to dequant + f16 mulmat
  6227. 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]);
  6228. }
  6229. // Not implemented
  6230. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6231. 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));
  6232. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && nei1 > 8;
  6233. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned, qx_needs_dequant ? f16_type : src0->type);
  6234. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  6235. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) :ne11;
  6236. const uint64_t x_ne = ggml_nelements(src0);
  6237. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  6238. const uint64_t d_ne = ggml_nelements(dst);
  6239. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  6240. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6241. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  6242. 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);
  6243. const uint64_t ids_sz = nbi2;
  6244. const uint64_t d_sz = sizeof(float) * d_ne;
  6245. vk_pipeline to_fp16_vk_0 = nullptr;
  6246. vk_pipeline to_fp16_vk_1 = nullptr;
  6247. vk_pipeline to_q8_1 = nullptr;
  6248. if (x_non_contig) {
  6249. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  6250. } else {
  6251. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  6252. }
  6253. if (y_non_contig) {
  6254. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  6255. } else {
  6256. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6257. }
  6258. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6259. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6260. if (quantize_y) {
  6261. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6262. }
  6263. {
  6264. if (
  6265. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6266. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6267. GGML_ABORT("Requested preallocation size is too large");
  6268. }
  6269. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6270. ctx->prealloc_size_x = x_sz;
  6271. ggml_vk_preallocate_buffers(ctx, subctx);
  6272. }
  6273. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6274. ctx->prealloc_size_y = y_sz;
  6275. ggml_vk_preallocate_buffers(ctx, subctx);
  6276. }
  6277. // Request descriptor sets
  6278. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6279. if (qx_needs_dequant) {
  6280. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6281. }
  6282. if (qy_needs_dequant) {
  6283. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6284. }
  6285. if (quantize_y) {
  6286. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6287. }
  6288. }
  6289. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6290. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6291. GGML_ASSERT(d_D != nullptr);
  6292. vk_buffer d_X;
  6293. uint64_t x_buf_offset = 0;
  6294. vk_buffer d_Y;
  6295. uint64_t y_buf_offset = 0;
  6296. if (!src0_uma) {
  6297. d_Qx = src0_buf_ctx->dev_buffer;
  6298. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6299. GGML_ASSERT(d_Qx != nullptr);
  6300. }
  6301. if (!src1_uma) {
  6302. d_Qy = src1_buf_ctx->dev_buffer;
  6303. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6304. GGML_ASSERT(d_Qy != nullptr);
  6305. }
  6306. if (!ids_uma) {
  6307. d_ids = ids_buf_ctx->dev_buffer;
  6308. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6309. GGML_ASSERT(d_ids != nullptr);
  6310. }
  6311. if (qx_needs_dequant) {
  6312. d_X = ctx->prealloc_x;
  6313. GGML_ASSERT(d_X->size >= x_sz);
  6314. } else {
  6315. d_X = d_Qx;
  6316. x_buf_offset = qx_buf_offset;
  6317. GGML_ASSERT(qx_sz == x_sz);
  6318. }
  6319. if (qy_needs_dequant) {
  6320. d_Y = ctx->prealloc_y;
  6321. GGML_ASSERT(d_Y->size >= y_sz);
  6322. } else if (quantize_y) {
  6323. d_Y = ctx->prealloc_y;
  6324. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  6325. } else {
  6326. d_Y = d_Qy;
  6327. y_buf_offset = qy_buf_offset;
  6328. GGML_ASSERT(qy_sz == y_sz);
  6329. }
  6330. if (x_non_contig || qx_needs_dequant) {
  6331. if (ctx->prealloc_x_need_sync) {
  6332. ggml_vk_sync_buffers(ctx, subctx);
  6333. }
  6334. }
  6335. if (x_non_contig) {
  6336. 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));
  6337. } else if (qx_needs_dequant) {
  6338. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6339. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  6340. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)x_ne, 1, 1});
  6341. ggml_vk_sync_buffers(ctx, subctx);
  6342. }
  6343. if (y_non_contig) {
  6344. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6345. ctx->prealloc_y_last_tensor_used != src1) {
  6346. if (ctx->prealloc_y_need_sync) {
  6347. ggml_vk_sync_buffers(ctx, subctx);
  6348. }
  6349. 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));
  6350. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6351. ctx->prealloc_y_last_tensor_used = src1;
  6352. }
  6353. }
  6354. if (quantize_y) {
  6355. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6356. ctx->prealloc_y_last_tensor_used != src1) {
  6357. if (ctx->prealloc_y_need_sync) {
  6358. ggml_vk_sync_buffers(ctx, subctx);
  6359. }
  6360. 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);
  6361. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6362. ctx->prealloc_y_last_tensor_used = src1;
  6363. }
  6364. }
  6365. uint32_t stride_batch_x = ne00*ne01;
  6366. uint32_t stride_batch_y = ne10*ne11;
  6367. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6368. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6369. }
  6370. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  6371. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6372. }
  6373. // compute
  6374. ggml_vk_matmul_id(
  6375. ctx, subctx, pipeline,
  6376. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  6377. { d_D, d_buf_offset, d_sz }, { d_ids, ids_buf_offset, ids_sz },
  6378. ne01, ne21, ne10, ne10, ne10, ne01,
  6379. stride_batch_x, stride_batch_y, ne20*ne21,
  6380. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, padded_n
  6381. ); // NOLINT
  6382. if (x_non_contig || qx_needs_dequant) {
  6383. ctx->prealloc_x_need_sync = true;
  6384. }
  6385. if (y_non_contig) {
  6386. ctx->prealloc_y_need_sync = true;
  6387. }
  6388. }
  6389. 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) {
  6390. ggml_tensor * dst = cgraph->nodes[node_idx];
  6391. ggml_tensor * src0 = dst->src[0];
  6392. ggml_tensor * src1 = dst->src[1];
  6393. ggml_tensor * ids = dst->src[2];
  6394. 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];
  6395. 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];
  6396. 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];
  6397. 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];
  6398. std::cerr << "))");
  6399. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6400. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6401. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6402. const uint64_t ne00 = src0->ne[0];
  6403. const uint64_t ne01 = src0->ne[1];
  6404. // const uint64_t ne02 = src0->ne[2];
  6405. // const uint64_t ne03 = src0->ne[3];
  6406. const uint64_t ne10 = src1->ne[0];
  6407. const uint64_t ne11 = src1->ne[1];
  6408. // const uint64_t ne12 = src1->ne[2];
  6409. // const uint64_t ne13 = src1->ne[3];
  6410. const uint64_t nei0 = ids->ne[0];
  6411. const uint64_t nei1 = ids->ne[1];
  6412. const uint64_t nbi2 = ids->nb[2];
  6413. GGML_ASSERT(nei1 == 1);
  6414. const uint64_t ne20 = dst->ne[0];
  6415. const uint64_t ne21 = dst->ne[1];
  6416. // const uint64_t ne22 = dst->ne[2];
  6417. // const uint64_t ne23 = dst->ne[3];
  6418. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6419. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6420. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6421. vk_buffer d_Qx = nullptr;
  6422. size_t qx_buf_offset = 0;
  6423. vk_buffer d_Qy = nullptr;
  6424. size_t qy_buf_offset = 0;
  6425. vk_buffer d_ids = nullptr;
  6426. size_t ids_buf_offset = 0;
  6427. bool src0_uma = false;
  6428. bool src1_uma = false;
  6429. bool ids_uma = false;
  6430. if (ctx->device->uma) {
  6431. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6432. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6433. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6434. src0_uma = d_Qx != nullptr;
  6435. src1_uma = d_Qy != nullptr;
  6436. ids_uma = d_ids != nullptr;
  6437. }
  6438. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6439. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6440. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6441. const bool qx_needs_dequant = x_non_contig;
  6442. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  6443. // Not implemented
  6444. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6445. const uint64_t x_ne = ggml_nelements(src0);
  6446. const uint64_t y_ne = ggml_nelements(src1);
  6447. const uint64_t d_ne = ggml_nelements(dst);
  6448. 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);
  6449. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6450. 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;
  6451. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  6452. const uint64_t ids_sz = nbi2;
  6453. const uint64_t d_sz = sizeof(float) * d_ne;
  6454. vk_pipeline to_fp16_vk_0 = nullptr;
  6455. vk_pipeline to_fp16_vk_1 = nullptr;
  6456. if (x_non_contig) {
  6457. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6458. }
  6459. if (y_non_contig) {
  6460. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6461. } else {
  6462. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6463. }
  6464. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type);
  6465. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6466. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6467. GGML_ASSERT(dmmv != nullptr);
  6468. {
  6469. if (
  6470. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6471. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6472. GGML_ABORT("Requested preallocation size is too large");
  6473. }
  6474. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6475. ctx->prealloc_size_x = x_sz;
  6476. ggml_vk_preallocate_buffers(ctx, subctx);
  6477. }
  6478. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz) {
  6479. ctx->prealloc_size_y = y_sz;
  6480. ggml_vk_preallocate_buffers(ctx, subctx);
  6481. }
  6482. // Request descriptor sets
  6483. if (qx_needs_dequant) {
  6484. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6485. }
  6486. if (qy_needs_dequant) {
  6487. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6488. }
  6489. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6490. }
  6491. vk_buffer d_D;
  6492. uint64_t d_buf_offset = 0;
  6493. if (ctx->num_additional_fused_ops > 0) {
  6494. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6495. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)add->buffer->context;
  6496. d_D = dst_buf_ctx->dev_buffer;
  6497. d_buf_offset = vk_tensor_offset(add) + add->view_offs;
  6498. } else {
  6499. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6500. d_D = dst_buf_ctx->dev_buffer;
  6501. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6502. }
  6503. GGML_ASSERT(d_D != nullptr);
  6504. vk_buffer d_X;
  6505. uint64_t x_buf_offset = 0;
  6506. vk_buffer d_Y;
  6507. uint64_t y_buf_offset = 0;
  6508. if(!src0_uma) {
  6509. d_Qx = src0_buf_ctx->dev_buffer;
  6510. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6511. GGML_ASSERT(d_Qx != nullptr);
  6512. }
  6513. if(!src1_uma) {
  6514. d_Qy = src1_buf_ctx->dev_buffer;
  6515. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6516. GGML_ASSERT(d_Qy != nullptr);
  6517. }
  6518. if(!ids_uma) {
  6519. d_ids = ids_buf_ctx->dev_buffer;
  6520. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6521. GGML_ASSERT(d_ids != nullptr);
  6522. }
  6523. if (qx_needs_dequant) {
  6524. d_X = ctx->prealloc_x;
  6525. } else {
  6526. d_X = d_Qx;
  6527. x_buf_offset = qx_buf_offset;
  6528. GGML_ASSERT(qx_sz == x_sz);
  6529. }
  6530. if (qy_needs_dequant) {
  6531. d_Y = ctx->prealloc_y;
  6532. } else {
  6533. d_Y = d_Qy;
  6534. y_buf_offset = qy_buf_offset;
  6535. GGML_ASSERT(qy_sz == y_sz);
  6536. }
  6537. if (x_non_contig) {
  6538. if (ctx->prealloc_x_need_sync) {
  6539. ggml_vk_sync_buffers(ctx, subctx);
  6540. }
  6541. }
  6542. if (x_non_contig) {
  6543. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6544. 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));
  6545. }
  6546. if (y_non_contig) {
  6547. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6548. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6549. ctx->prealloc_y_last_tensor_used != src1) {
  6550. if (ctx->prealloc_y_need_sync) {
  6551. ggml_vk_sync_buffers(ctx, subctx);
  6552. }
  6553. 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));
  6554. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6555. ctx->prealloc_y_last_tensor_used = src1;
  6556. }
  6557. }
  6558. uint32_t stride_batch_y = ne10*ne11;
  6559. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6560. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6561. }
  6562. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6563. uint32_t groups_x = ne01;
  6564. uint32_t groups_z = 1;
  6565. if (ne01 > max_groups_x) {
  6566. groups_z = 64;
  6567. groups_x = CEIL_DIV(groups_x, groups_z);
  6568. }
  6569. uint32_t enable_bias = 0;
  6570. uint32_t enable_scale = 0;
  6571. if (ctx->num_additional_fused_ops > 0) {
  6572. if (cgraph->nodes[node_idx + 1]->op == GGML_OP_MUL) {
  6573. enable_scale = 1;
  6574. } else {
  6575. GGML_ASSERT(cgraph->nodes[node_idx + 1]->op == GGML_OP_ADD_ID);
  6576. enable_bias = 1;
  6577. }
  6578. }
  6579. vk_buffer d_B = d_D;
  6580. size_t b_buf_offset = 0;
  6581. uint64_t b_sz = 0;
  6582. if (enable_bias || enable_scale) {
  6583. const ggml_tensor * bias = cgraph->nodes[node_idx + 1]->src[1];
  6584. bool b_uma = false;
  6585. if (ctx->device->uma) {
  6586. ggml_vk_host_get(ctx->device, bias->data, d_B, b_buf_offset);
  6587. b_uma = d_B != nullptr;
  6588. }
  6589. if(!b_uma) {
  6590. ggml_backend_vk_buffer_context * bias_buf_ctx = (ggml_backend_vk_buffer_context *)bias->buffer->context;
  6591. d_B = bias_buf_ctx->dev_buffer;
  6592. b_buf_offset = vk_tensor_offset(bias) + bias->view_offs;
  6593. GGML_ASSERT(d_B != nullptr);
  6594. b_sz = ggml_nbytes(bias);
  6595. }
  6596. }
  6597. // compute
  6598. const vk_mat_vec_id_push_constants pc = {
  6599. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6600. (uint32_t)(ne00 * ne01), stride_batch_y, (uint32_t)(ne20 * ne21),
  6601. enable_bias, enable_scale,
  6602. (uint32_t)nei0, (uint32_t)ne11,
  6603. };
  6604. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6605. {
  6606. vk_subbuffer{ d_X, x_buf_offset, x_sz },
  6607. vk_subbuffer{ d_Y, y_buf_offset, y_sz },
  6608. vk_subbuffer{ d_D, d_buf_offset, d_sz },
  6609. vk_subbuffer{ d_B, b_buf_offset, b_sz },
  6610. vk_subbuffer{ d_ids, ids_buf_offset, ids_sz },
  6611. },
  6612. pc, { groups_x, (uint32_t)nei0, groups_z });
  6613. if (x_non_contig) {
  6614. ctx->prealloc_x_need_sync = true;
  6615. }
  6616. if (y_non_contig) {
  6617. ctx->prealloc_y_need_sync = true;
  6618. }
  6619. }
  6620. static bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx) {
  6621. ggml_tensor * dst = cgraph->nodes[node_idx];
  6622. ggml_tensor * src0 = dst->src[0];
  6623. ggml_tensor * src2 = dst->src[2];
  6624. return src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type));
  6625. }
  6626. static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6627. ggml_tensor * dst = cgraph->nodes[node_idx];
  6628. ggml_tensor * src0 = dst->src[0];
  6629. ggml_tensor * src1 = dst->src[1];
  6630. ggml_tensor * src2 = dst->src[2];
  6631. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  6632. if (ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  6633. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, cgraph, node_idx);
  6634. } else {
  6635. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst);
  6636. }
  6637. }
  6638. static bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv) {
  6639. // Needs to be kept up to date on shader changes
  6640. GGML_UNUSED(hsv);
  6641. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6642. const uint32_t Br = get_fa_scalar_num_large_rows(hsv);
  6643. const uint32_t Bc = scalar_flash_attention_Bc;
  6644. const uint32_t tmpsh = wg_size * sizeof(float);
  6645. const uint32_t tmpshv4 = wg_size * 4 * sizeof(float);
  6646. const uint32_t masksh = Bc * Br * sizeof(float);
  6647. const uint32_t Qf = Br * (hsk / 4 + 2) * 4 * sizeof(float);
  6648. const uint32_t total_size = tmpsh + tmpshv4 + masksh + Qf;
  6649. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6650. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported);
  6651. return supported;
  6652. }
  6653. static bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool f32acc) {
  6654. // Needs to be kept up to date on shader changes
  6655. GGML_UNUSED(hsv);
  6656. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6657. const uint32_t Br = coopmat1_flash_attention_num_large_rows;
  6658. const uint32_t Bc = scalar_flash_attention_Bc;
  6659. const uint32_t hsk_pad = ROUNDUP_POW2(hsk, 16);
  6660. const uint32_t acctype = f32acc ? 4 : 2;
  6661. const uint32_t f16vec4 = 8;
  6662. const uint32_t tmpsh = wg_size * sizeof(float);
  6663. const uint32_t tmpshv4 = wg_size * 4 * acctype;
  6664. const uint32_t qstride = hsk_pad / 4 + 2;
  6665. const uint32_t Qf = Br * qstride * f16vec4;
  6666. const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br;
  6667. const uint32_t sfsh = Bc * sfshstride * acctype;
  6668. const uint32_t kshstride = hsk_pad / 4 + 2;
  6669. const uint32_t ksh = Bc * kshstride * f16vec4;
  6670. const uint32_t slope = Br * sizeof(float);
  6671. const uint32_t total_size = tmpsh + tmpshv4 + Qf + sfsh + ksh + slope;
  6672. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6673. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported);
  6674. return supported;
  6675. }
  6676. 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) {
  6677. 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];
  6678. 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];
  6679. 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];
  6680. 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];
  6681. if (sinks) {
  6682. 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];
  6683. }
  6684. std::cerr << "))");
  6685. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  6686. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  6687. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  6688. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  6689. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  6690. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  6691. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  6692. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  6693. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  6694. const uint32_t nem2 = mask ? mask->ne[2] : 0;
  6695. const uint32_t nem3 = mask ? mask->ne[3] : 0;
  6696. const uint32_t HSK = nek0;
  6697. const uint32_t HSV = nev0;
  6698. uint32_t N = neq1;
  6699. const uint32_t KV = nek1;
  6700. GGML_ASSERT(ne0 == HSV);
  6701. GGML_ASSERT(ne2 == N);
  6702. // input tensor rows must be contiguous
  6703. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  6704. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  6705. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  6706. GGML_ASSERT(neq0 == HSK);
  6707. GGML_ASSERT(neq1 == N);
  6708. GGML_ASSERT(nev1 == nek1);
  6709. // dst cannot be transposed or permuted
  6710. GGML_ASSERT(nb0 == sizeof(float));
  6711. GGML_ASSERT(nb0 <= nb1);
  6712. GGML_ASSERT(nb1 <= nb2);
  6713. GGML_ASSERT(nb2 <= nb3);
  6714. assert(dst->type == GGML_TYPE_F32);
  6715. assert(q->type == GGML_TYPE_F32);
  6716. assert(k->type == v->type);
  6717. FaCodePath path = ctx->device->coopmat2 ? FA_COOPMAT2 :
  6718. ctx->device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;
  6719. if (path == FA_COOPMAT1) {
  6720. const bool coopmat_shape_supported = (dst->op_params[3] == GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f32acc) ||
  6721. (dst->op_params[3] != GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f16acc);
  6722. const bool coopmat_shmem_supported = ggml_vk_flash_attn_coopmat_shmem_support(ctx->device, HSK, HSV, dst->op_params[3] == GGML_PREC_F32);
  6723. if (!coopmat_shape_supported || !coopmat_shmem_supported) {
  6724. path = FA_SCALAR;
  6725. }
  6726. }
  6727. uint32_t gqa_ratio = 1;
  6728. uint32_t qk_ratio = neq2 / nek2;
  6729. uint32_t workgroups_x = (uint32_t)neq1;
  6730. uint32_t workgroups_y = (uint32_t)neq2;
  6731. uint32_t workgroups_z = (uint32_t)neq3;
  6732. // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga.
  6733. // For coopmat2 FA, we always use the small size (which is still pretty large for gqa).
  6734. uint32_t max_gqa;
  6735. switch (path) {
  6736. case FA_SCALAR:
  6737. case FA_COOPMAT1:
  6738. // We may switch from coopmat1 to scalar, so use the scalar limit for both
  6739. max_gqa = get_fa_scalar_num_large_rows(HSV);
  6740. break;
  6741. case FA_COOPMAT2:
  6742. max_gqa = get_fa_num_small_rows(FA_COOPMAT2);
  6743. break;
  6744. default:
  6745. GGML_ASSERT(0);
  6746. }
  6747. if (N == 1 && qk_ratio > 1 && qk_ratio <= max_gqa &&
  6748. qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) {
  6749. // grouped query attention - make the N dimension equal to gqa_ratio, reduce
  6750. // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1
  6751. // and change addressing calculations to index Q's dimension 2.
  6752. gqa_ratio = qk_ratio;
  6753. N = gqa_ratio;
  6754. workgroups_y /= N;
  6755. }
  6756. bool small_rows = N <= get_fa_num_small_rows(path);
  6757. // coopmat1 does not actually support "small rows" (it needs 16 rows).
  6758. // So use scalar instead.
  6759. if (small_rows && path == FA_COOPMAT1) {
  6760. path = FA_SCALAR;
  6761. }
  6762. // scalar is faster than coopmat2 when N==1
  6763. if (N == 1 && path == FA_COOPMAT2) {
  6764. path = FA_SCALAR;
  6765. }
  6766. // with large hsk/hsv, scalar path may need to use small_rows to fit in shared memory
  6767. if (path == FA_SCALAR &&
  6768. !ggml_vk_flash_attn_scalar_shmem_support(ctx->device, HSK, HSV)) {
  6769. small_rows = true;
  6770. }
  6771. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  6772. uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  6773. uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  6774. // For F32, the shader treats it as a block of size 4 (for vec4 loads)
  6775. if (k->type == GGML_TYPE_F32) {
  6776. k_stride /= 4;
  6777. }
  6778. if (v->type == GGML_TYPE_F32) {
  6779. v_stride /= 4;
  6780. }
  6781. uint32_t alignment = fa_align(path, HSK, HSV, k->type, small_rows);
  6782. bool aligned = (KV % alignment) == 0 &&
  6783. // the "aligned" shader variant will forcibly align strides, for performance
  6784. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  6785. // Need to use the coopmat2 variant that clamps loads when HSK/HSV aren't sufficiently aligned.
  6786. if (((HSK | HSV) % 16) != 0 && path == FA_COOPMAT2) {
  6787. aligned = false;
  6788. }
  6789. bool f32acc = path == FA_SCALAR || dst->op_params[3] == GGML_PREC_F32;
  6790. vk_fa_pipeline_state fa_pipeline_state(HSK, HSV, small_rows, path, aligned, f32acc);
  6791. vk_pipeline pipeline = nullptr;
  6792. {
  6793. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  6794. auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16[k->type];
  6795. auto it = pipelines.find(fa_pipeline_state);
  6796. if (it != pipelines.end()) {
  6797. pipeline = it->second;
  6798. } else {
  6799. pipelines[fa_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  6800. }
  6801. }
  6802. assert(pipeline);
  6803. uint32_t split_kv = KV;
  6804. uint32_t split_k = 1;
  6805. // Use a placeholder core count if one isn't available. split_k is a big help for perf.
  6806. const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count : 16;
  6807. // Try to use split_k when KV is large enough to be worth the overhead
  6808. if (workgroups_x == 1 && shader_core_count > 0) {
  6809. // Try to run two workgroups per SM.
  6810. split_k = shader_core_count * 2 / (workgroups_y * workgroups_z);
  6811. if (split_k > 1) {
  6812. // Try to evenly split KV into split_k chunks, but it needs to be a multiple
  6813. // of "align", so recompute split_k based on that.
  6814. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment);
  6815. split_k = CEIL_DIV(KV, split_kv);
  6816. workgroups_x = split_k;
  6817. }
  6818. }
  6819. // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1)
  6820. // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows.
  6821. const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne3 : 0;
  6822. if (split_k_size > ctx->device->properties.limits.maxStorageBufferRange) {
  6823. GGML_ABORT("Requested preallocation size is too large");
  6824. }
  6825. if (ctx->prealloc_size_split_k < split_k_size) {
  6826. ctx->prealloc_size_split_k = split_k_size;
  6827. ggml_vk_preallocate_buffers(ctx, subctx);
  6828. }
  6829. {
  6830. // Request descriptor sets
  6831. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6832. if (split_k > 1) {
  6833. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1);
  6834. }
  6835. }
  6836. float scale = 1.0f;
  6837. float max_bias = 0.0f;
  6838. float logit_softcap = 0.0f;
  6839. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  6840. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  6841. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  6842. if (logit_softcap != 0) {
  6843. scale /= logit_softcap;
  6844. }
  6845. const uint32_t n_head_kv = neq2;
  6846. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  6847. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  6848. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  6849. vk_subbuffer q_buf = ggml_vk_tensor_subbuffer(ctx, q);
  6850. vk_subbuffer k_buf = ggml_vk_tensor_subbuffer(ctx, k);
  6851. vk_subbuffer v_buf = ggml_vk_tensor_subbuffer(ctx, v);
  6852. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  6853. vk_subbuffer mask_buf = mask ? ggml_vk_tensor_subbuffer(ctx, mask) : q_buf;
  6854. vk_subbuffer sinks_buf = sinks ? ggml_vk_tensor_subbuffer(ctx, sinks) : q_buf;
  6855. uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | ((mask != nullptr) << 16) | n_head_log2;
  6856. const vk_flash_attn_push_constants pc = { N, KV,
  6857. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  6858. (uint32_t)neq2, (uint32_t)neq3,
  6859. (uint32_t)nek2, (uint32_t)nek3,
  6860. (uint32_t)nev2, (uint32_t)nev3,
  6861. nem1, nem2, nem3,
  6862. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  6863. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  6864. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  6865. scale, max_bias, logit_softcap,
  6866. mask_n_head_log2, m0, m1,
  6867. gqa_ratio, split_kv, split_k };
  6868. if (split_k > 1) {
  6869. if (ctx->prealloc_split_k_need_sync) {
  6870. ggml_vk_sync_buffers(ctx, subctx);
  6871. }
  6872. vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  6873. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6874. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf},
  6875. // We only use split_k when group query attention is enabled, which means
  6876. // there's no more than one tile of rows (i.e. workgroups_x would have been
  6877. // one). We reuse workgroups_x to mean the number of splits, so we need to
  6878. // cancel out the divide by wg_denoms[0].
  6879. pc, { workgroups_x * pipeline->wg_denoms[0], workgroups_y, workgroups_z });
  6880. ggml_vk_sync_buffers(ctx, subctx);
  6881. const std::array<uint32_t, 5> pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne3, split_k, (sinks != nullptr) };
  6882. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce,
  6883. {split_k_buf, sinks_buf, dst_buf},
  6884. pc2, { (uint32_t)ne1, HSV, (uint32_t)ne3 });
  6885. ctx->prealloc_split_k_need_sync = true;
  6886. } else {
  6887. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6888. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf},
  6889. pc, { workgroups_x, workgroups_y, workgroups_z });
  6890. }
  6891. }
  6892. static std::array<uint32_t, 3> ggml_vk_get_conv_elements(const ggml_tensor *dst) {
  6893. const ggml_tensor *src0 = dst->src[0];
  6894. const ggml_tensor *src1 = dst->src[1];
  6895. // src0 - kernel: [KW, KH, Cin, Cout]
  6896. // src1 - input: [W, H, Cin, N]
  6897. // dst - result: [OW, OH, Cout, N]
  6898. // Copied from ggml.c: int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d)
  6899. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6900. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  6901. };
  6902. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6903. int64_t W = src1->ne[0];
  6904. int64_t H = src1->ne[1];
  6905. int64_t KW = src0->ne[0];
  6906. int64_t KH = src0->ne[1];
  6907. int64_t Cout = src0->ne[3];
  6908. int64_t N = src1->ne[3];
  6909. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[1], dst->op_params[3], dst->op_params[5]);
  6910. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], dst->op_params[2], dst->op_params[4]);
  6911. int64_t NPQ = N * OW * OH;
  6912. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6913. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6914. return elements;
  6915. }
  6916. static std::array<uint32_t, 3> ggml_vk_get_conv_transpose_2d_elements(const ggml_tensor *dst) {
  6917. const ggml_tensor *src0 = dst->src[0];
  6918. const ggml_tensor *src1 = dst->src[1];
  6919. // src0 - kernel: [KW, KH, Cout, Cin]
  6920. // src1 - input: [W, H, Cin, N]
  6921. // dst - result: [OW, OH, Cout, N]
  6922. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6923. return (ins - 1) * s - 2 * p + (ks - 1) * d + 1;
  6924. };
  6925. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6926. int64_t W = src1->ne[0];
  6927. int64_t H = src1->ne[1];
  6928. int64_t KW = src0->ne[0];
  6929. int64_t KH = src0->ne[1];
  6930. int64_t Cout = src0->ne[2];
  6931. int64_t N = src1->ne[3];
  6932. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[0], 0, 1);
  6933. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], 0, 1);
  6934. int64_t NPQ = N * OW * OH;
  6935. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6936. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6937. return elements;
  6938. }
  6939. 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) {
  6940. switch (op) {
  6941. case GGML_OP_GET_ROWS:
  6942. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  6943. if (dst->type == GGML_TYPE_F16) {
  6944. return ctx->device->pipeline_get_rows[src0->type];
  6945. }
  6946. if (dst->type == GGML_TYPE_F32) {
  6947. return ctx->device->pipeline_get_rows_f32[src0->type];
  6948. }
  6949. return nullptr;
  6950. case GGML_OP_ACC:
  6951. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6952. return ctx->device->pipeline_acc_f32;
  6953. }
  6954. return nullptr;
  6955. case GGML_OP_ADD:
  6956. case GGML_OP_SUB:
  6957. case GGML_OP_MUL:
  6958. case GGML_OP_DIV:
  6959. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  6960. (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
  6961. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
  6962. return nullptr;
  6963. }
  6964. switch (op) {
  6965. case GGML_OP_ADD:
  6966. {
  6967. if (ctx->num_additional_fused_ops > 0) {
  6968. if (ctx->do_add_rms_partials) {
  6969. return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops];
  6970. } else {
  6971. return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  6972. }
  6973. }
  6974. if (ctx->do_add_rms_partials) {
  6975. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_rms_norepeat : ctx->device->pipeline_add_rms;
  6976. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6977. } else {
  6978. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add;
  6979. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6980. }
  6981. }
  6982. case GGML_OP_SUB:
  6983. {
  6984. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub;
  6985. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6986. }
  6987. case GGML_OP_MUL:
  6988. {
  6989. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul;
  6990. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6991. }
  6992. case GGML_OP_DIV:
  6993. {
  6994. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div;
  6995. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6996. }
  6997. default:
  6998. break;
  6999. }
  7000. return nullptr;
  7001. case GGML_OP_ADD_ID:
  7002. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) {
  7003. return ctx->device->pipeline_add_id_f32;
  7004. }
  7005. return nullptr;
  7006. case GGML_OP_CONCAT:
  7007. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7008. return ctx->device->pipeline_concat_f32;
  7009. }
  7010. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7011. return ctx->device->pipeline_concat_f16;
  7012. }
  7013. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  7014. return ctx->device->pipeline_concat_i32;
  7015. }
  7016. return nullptr;
  7017. case GGML_OP_UPSCALE:
  7018. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7019. ggml_scale_mode mode = (ggml_scale_mode)(ggml_get_op_params_i32(dst, 0) & 0xFF);
  7020. switch (mode) {
  7021. case GGML_SCALE_MODE_NEAREST:
  7022. return ctx->device->pipeline_upscale_nearest_f32;
  7023. case GGML_SCALE_MODE_BILINEAR:
  7024. return ctx->device->pipeline_upscale_bilinear_f32;
  7025. default:
  7026. return nullptr;
  7027. }
  7028. }
  7029. return nullptr;
  7030. case GGML_OP_SCALE:
  7031. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7032. return ctx->device->pipeline_scale_f32;
  7033. }
  7034. return nullptr;
  7035. case GGML_OP_SQR:
  7036. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7037. return ctx->device->pipeline_sqr_f32;
  7038. }
  7039. return nullptr;
  7040. case GGML_OP_SQRT:
  7041. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7042. return ctx->device->pipeline_sqrt_f32;
  7043. }
  7044. return nullptr;
  7045. case GGML_OP_SIN:
  7046. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7047. return ctx->device->pipeline_sin_f32;
  7048. }
  7049. return nullptr;
  7050. case GGML_OP_COS:
  7051. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7052. return ctx->device->pipeline_cos_f32;
  7053. }
  7054. return nullptr;
  7055. case GGML_OP_CLAMP:
  7056. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7057. return ctx->device->pipeline_clamp_f32;
  7058. }
  7059. return nullptr;
  7060. case GGML_OP_PAD:
  7061. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7062. return ctx->device->pipeline_pad_f32;
  7063. }
  7064. return nullptr;
  7065. case GGML_OP_ROLL:
  7066. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7067. return ctx->device->pipeline_roll_f32;
  7068. }
  7069. return nullptr;
  7070. case GGML_OP_REPEAT:
  7071. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  7072. return ctx->device->pipeline_repeat_f32;
  7073. }
  7074. return nullptr;
  7075. case GGML_OP_REPEAT_BACK:
  7076. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7077. return ctx->device->pipeline_repeat_back_f32;
  7078. }
  7079. return nullptr;
  7080. case GGML_OP_CPY:
  7081. case GGML_OP_CONT:
  7082. case GGML_OP_DUP:
  7083. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  7084. case GGML_OP_SET_ROWS:
  7085. if (src1->type == GGML_TYPE_I64) {
  7086. return ctx->device->pipeline_set_rows_i64[dst->type];
  7087. } else {
  7088. return ctx->device->pipeline_set_rows_i32[dst->type];
  7089. }
  7090. case GGML_OP_SILU_BACK:
  7091. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7092. return ctx->device->pipeline_silu_back_f32;
  7093. }
  7094. return nullptr;
  7095. case GGML_OP_NORM:
  7096. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7097. return ctx->device->pipeline_norm_f32;
  7098. }
  7099. return nullptr;
  7100. case GGML_OP_GROUP_NORM:
  7101. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7102. return ctx->device->pipeline_group_norm_f32;
  7103. }
  7104. return nullptr;
  7105. case GGML_OP_RMS_NORM:
  7106. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7107. if (ctx->do_add_rms_partials) {
  7108. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32;
  7109. } else {
  7110. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32;
  7111. }
  7112. }
  7113. return nullptr;
  7114. case GGML_OP_RMS_NORM_BACK:
  7115. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7116. return ctx->device->pipeline_rms_norm_back_f32;
  7117. }
  7118. return nullptr;
  7119. case GGML_OP_L2_NORM:
  7120. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7121. return ctx->device->pipeline_l2_norm_f32;
  7122. }
  7123. return nullptr;
  7124. case GGML_OP_UNARY:
  7125. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7126. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7127. (src0->type != dst->type)) {
  7128. return nullptr;
  7129. }
  7130. switch (ggml_get_unary_op(dst)) {
  7131. case GGML_UNARY_OP_EXP:
  7132. return ctx->device->pipeline_exp[dst->type == GGML_TYPE_F16];
  7133. case GGML_UNARY_OP_SILU:
  7134. return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16];
  7135. case GGML_UNARY_OP_GELU:
  7136. return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16];
  7137. case GGML_UNARY_OP_GELU_ERF:
  7138. return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16];
  7139. case GGML_UNARY_OP_GELU_QUICK:
  7140. return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16];
  7141. case GGML_UNARY_OP_RELU:
  7142. return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16];
  7143. case GGML_UNARY_OP_TANH:
  7144. return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16];
  7145. case GGML_UNARY_OP_SIGMOID:
  7146. return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16];
  7147. case GGML_UNARY_OP_HARDSIGMOID:
  7148. return ctx->device->pipeline_hardsigmoid[dst->type == GGML_TYPE_F16];
  7149. case GGML_UNARY_OP_HARDSWISH:
  7150. return ctx->device->pipeline_hardswish[dst->type == GGML_TYPE_F16];
  7151. default:
  7152. break;
  7153. }
  7154. return nullptr;
  7155. case GGML_OP_GLU:
  7156. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7157. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7158. (src0->type != dst->type)) {
  7159. return nullptr;
  7160. }
  7161. switch (ggml_get_glu_op(dst)) {
  7162. case GGML_GLU_OP_GEGLU:
  7163. return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16];
  7164. case GGML_GLU_OP_REGLU:
  7165. return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16];
  7166. case GGML_GLU_OP_SWIGLU:
  7167. return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16];
  7168. case GGML_GLU_OP_SWIGLU_OAI:
  7169. return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16];
  7170. case GGML_GLU_OP_GEGLU_ERF:
  7171. return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16];
  7172. case GGML_GLU_OP_GEGLU_QUICK:
  7173. return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16];
  7174. default:
  7175. break;
  7176. }
  7177. return nullptr;
  7178. case GGML_OP_DIAG_MASK_INF:
  7179. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7180. return ctx->device->pipeline_diag_mask_inf_f32;
  7181. }
  7182. return nullptr;
  7183. case GGML_OP_SOFT_MAX:
  7184. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  7185. GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32);
  7186. if (ctx->num_additional_fused_ops) {
  7187. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7188. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7189. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  7190. return ctx->device->pipeline_topk_moe[idx][mode];
  7191. }
  7192. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  7193. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  7194. }
  7195. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7196. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  7197. }
  7198. return nullptr;
  7199. case GGML_OP_SOFT_MAX_BACK:
  7200. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7201. return ctx->device->pipeline_soft_max_back_f32;
  7202. }
  7203. return nullptr;
  7204. case GGML_OP_ROPE:
  7205. case GGML_OP_ROPE_BACK:
  7206. {
  7207. const ggml_tensor *rope = ctx->num_additional_fused_ops == 2 ? dst->src[0]->src[0] : dst;
  7208. const int mode = ((const int32_t *) rope->op_params)[2];
  7209. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  7210. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  7211. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  7212. if (is_neox) {
  7213. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7214. return ctx->device->pipeline_rope_neox_f32;
  7215. }
  7216. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7217. return ctx->device->pipeline_rope_neox_f32_f16;
  7218. }
  7219. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7220. return ctx->device->pipeline_rope_neox_f16;
  7221. }
  7222. } else if (is_mrope && !is_vision) {
  7223. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7224. return ctx->device->pipeline_rope_multi_f32;
  7225. }
  7226. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7227. return ctx->device->pipeline_rope_multi_f16;
  7228. }
  7229. } else if (is_vision) {
  7230. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7231. return ctx->device->pipeline_rope_vision_f32;
  7232. }
  7233. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7234. return ctx->device->pipeline_rope_vision_f16;
  7235. }
  7236. } else {
  7237. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7238. return ctx->device->pipeline_rope_norm_f32;
  7239. }
  7240. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7241. return ctx->device->pipeline_rope_norm_f32_f16;
  7242. }
  7243. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7244. return ctx->device->pipeline_rope_norm_f16;
  7245. }
  7246. }
  7247. return nullptr;
  7248. }
  7249. case GGML_OP_ARGSORT:
  7250. if (ctx->num_additional_fused_ops) {
  7251. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7252. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7253. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  7254. return ctx->device->pipeline_topk_moe[idx][mode];
  7255. }
  7256. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7257. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7258. return ctx->device->pipeline_argsort_f32[idx];
  7259. }
  7260. return nullptr;
  7261. case GGML_OP_SUM:
  7262. case GGML_OP_SUM_ROWS:
  7263. case GGML_OP_MEAN:
  7264. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7265. return ctx->device->pipeline_sum_rows_f32;
  7266. }
  7267. return nullptr;
  7268. case GGML_OP_ARGMAX:
  7269. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7270. return ctx->device->pipeline_argmax_f32;
  7271. }
  7272. return nullptr;
  7273. case GGML_OP_COUNT_EQUAL:
  7274. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) {
  7275. return ctx->device->pipeline_count_equal_i32;
  7276. }
  7277. return nullptr;
  7278. case GGML_OP_IM2COL:
  7279. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7280. return ctx->device->pipeline_im2col_f32;
  7281. }
  7282. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7283. return ctx->device->pipeline_im2col_f32_f16;
  7284. }
  7285. return nullptr;
  7286. case GGML_OP_IM2COL_3D:
  7287. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7288. return ctx->device->pipeline_im2col_3d_f32;
  7289. }
  7290. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7291. return ctx->device->pipeline_im2col_3d_f32_f16;
  7292. }
  7293. return nullptr;
  7294. case GGML_OP_TIMESTEP_EMBEDDING:
  7295. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7296. return ctx->device->pipeline_timestep_embedding_f32;
  7297. }
  7298. return nullptr;
  7299. case GGML_OP_CONV_TRANSPOSE_1D:
  7300. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7301. return ctx->device->pipeline_conv_transpose_1d_f32;
  7302. }
  7303. return nullptr;
  7304. case GGML_OP_POOL_2D:
  7305. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7306. return ctx->device->pipeline_pool2d_f32;
  7307. }
  7308. return nullptr;
  7309. case GGML_OP_RWKV_WKV6:
  7310. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7311. return ctx->device->pipeline_rwkv_wkv6_f32;
  7312. }
  7313. return nullptr;
  7314. case GGML_OP_RWKV_WKV7:
  7315. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7316. return ctx->device->pipeline_rwkv_wkv7_f32;
  7317. }
  7318. return nullptr;
  7319. case GGML_OP_SSM_SCAN:
  7320. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7321. const uint32_t d_state = src0->ne[0];
  7322. if (d_state == 128) {
  7323. return ctx->device->pipeline_ssm_scan_f32_d128;
  7324. } else if (d_state == 256) {
  7325. return ctx->device->pipeline_ssm_scan_f32_d256;
  7326. }
  7327. }
  7328. return nullptr;
  7329. case GGML_OP_SSM_CONV:
  7330. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7331. return ctx->device->pipeline_ssm_conv_f32;
  7332. }
  7333. return nullptr;
  7334. case GGML_OP_OPT_STEP_ADAMW:
  7335. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7336. return ctx->device->pipeline_opt_step_adamw_f32;
  7337. }
  7338. return nullptr;
  7339. case GGML_OP_OPT_STEP_SGD:
  7340. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7341. return ctx->device->pipeline_opt_step_sgd_f32;
  7342. }
  7343. return nullptr;
  7344. case GGML_OP_LEAKY_RELU:
  7345. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7346. return ctx->device->pipeline_leaky_relu_f32;
  7347. }
  7348. return nullptr;
  7349. case GGML_OP_CONV_2D:
  7350. case GGML_OP_CONV_TRANSPOSE_2D:
  7351. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 &&
  7352. ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst)) {
  7353. std::array<uint32_t, 3> elements;
  7354. if (op == GGML_OP_CONV_2D) elements = ggml_vk_get_conv_elements(dst);
  7355. else if (op == GGML_OP_CONV_TRANSPOSE_2D) elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  7356. vk_conv_shapes shape;
  7357. uint32_t tiles[CONV_SHAPE_COUNT];
  7358. for (uint32_t i = 0; i < CONV_SHAPE_COUNT; ++i) {
  7359. tiles[i] = CEIL_DIV(elements[0], conv_shapes_wg_denoms[i][0]) * CEIL_DIV(elements[1], conv_shapes_wg_denoms[i][1]);
  7360. }
  7361. // We can't query number of shader cores on Intel, use 32 as a placeholder
  7362. // so small convolutions will still choose a smaller tile.
  7363. const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32;
  7364. if (elements[0] > 64 && tiles[CONV_SHAPE_128x128] >= shader_core_count * 2) {
  7365. shape = CONV_SHAPE_128x128;
  7366. } else if (elements[0] <= 32 && tiles[CONV_SHAPE_32x256] >= shader_core_count * 2) {
  7367. shape = CONV_SHAPE_32x256;
  7368. } else {
  7369. shape = CONV_SHAPE_64x32;
  7370. }
  7371. uint32_t KW = static_cast<uint32_t>(src0->ne[0]);
  7372. uint32_t KH = static_cast<uint32_t>(src0->ne[1]);
  7373. uint32_t s0 = static_cast<uint32_t>(dst->op_params[0]);
  7374. uint32_t s1 = op == GGML_OP_CONV_2D ? static_cast<uint32_t>(dst->op_params[1]) : static_cast<uint32_t>(dst->op_params[0]);
  7375. uint32_t p0 = op == GGML_OP_CONV_2D ? static_cast<uint32_t>(dst->op_params[2]) : 0;
  7376. uint32_t p1 = op == GGML_OP_CONV_2D ? static_cast<uint32_t>(dst->op_params[3]) : 0;
  7377. uint32_t d0 = op == GGML_OP_CONV_2D ? static_cast<uint32_t>(dst->op_params[4]) : 1;
  7378. uint32_t d1 = op == GGML_OP_CONV_2D ? static_cast<uint32_t>(dst->op_params[5]) : 1;
  7379. vk_conv2d_pipeline_state conv2d_pipeline_state(s0, s1, p0, p1, d0, d1, KW, KH);
  7380. std::map<vk_conv2d_pipeline_state, vk_pipeline> *pipelines = nullptr;
  7381. if (op == GGML_OP_CONV_2D) {
  7382. if (src0->type == GGML_TYPE_F32) {
  7383. pipelines = &ctx->device->pipeline_conv2d_f32[shape];
  7384. } else if (src0->type == GGML_TYPE_F16) {
  7385. pipelines = &ctx->device->pipeline_conv2d_f16_f32[shape];
  7386. }
  7387. } else if (op == GGML_OP_CONV_TRANSPOSE_2D) {
  7388. if (src0->type == GGML_TYPE_F32) {
  7389. pipelines = &ctx->device->pipeline_conv_transpose_2d_f32[shape];
  7390. } else if (src0->type == GGML_TYPE_F16) {
  7391. pipelines = &ctx->device->pipeline_conv_transpose_2d_f16_f32[shape];
  7392. }
  7393. }
  7394. vk_pipeline pipeline = nullptr;
  7395. {
  7396. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7397. auto it = pipelines->find(conv2d_pipeline_state);
  7398. if (it != pipelines->end()) {
  7399. pipeline = it->second;
  7400. } else {
  7401. (*pipelines)[conv2d_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7402. }
  7403. }
  7404. return pipeline;
  7405. }
  7406. return nullptr;
  7407. case GGML_OP_CONV_2D_DW:
  7408. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7409. if (ggml_is_contiguous(src1)) {
  7410. return ctx->device->pipeline_conv2d_dw_whcn_f32;
  7411. } else if (ggml_is_contiguous_channels(src1)) {
  7412. return ctx->device->pipeline_conv2d_dw_cwhn_f32;
  7413. }
  7414. } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7415. if (ggml_is_contiguous(src1)) {
  7416. return ctx->device->pipeline_conv2d_dw_whcn_f16_f32;
  7417. } else if (ggml_is_contiguous_channels(src1)) {
  7418. return ctx->device->pipeline_conv2d_dw_cwhn_f16_f32;
  7419. }
  7420. }
  7421. return nullptr;
  7422. default:
  7423. return nullptr;
  7424. }
  7425. GGML_UNUSED(src2);
  7426. }
  7427. static bool ggml_vk_op_supports_incontiguous(ggml_op op) {
  7428. switch (op) {
  7429. case GGML_OP_CPY:
  7430. case GGML_OP_GET_ROWS:
  7431. case GGML_OP_ADD:
  7432. case GGML_OP_SUB:
  7433. case GGML_OP_MUL:
  7434. case GGML_OP_DIV:
  7435. case GGML_OP_ADD_ID:
  7436. case GGML_OP_CONCAT:
  7437. case GGML_OP_UPSCALE:
  7438. case GGML_OP_SQR:
  7439. case GGML_OP_SQRT:
  7440. case GGML_OP_SIN:
  7441. case GGML_OP_COS:
  7442. case GGML_OP_CLAMP:
  7443. case GGML_OP_PAD:
  7444. case GGML_OP_REPEAT:
  7445. case GGML_OP_REPEAT_BACK:
  7446. case GGML_OP_ROPE:
  7447. case GGML_OP_RMS_NORM:
  7448. case GGML_OP_CONV_2D_DW:
  7449. case GGML_OP_IM2COL:
  7450. case GGML_OP_IM2COL_3D:
  7451. case GGML_OP_SET_ROWS:
  7452. case GGML_OP_SUM:
  7453. case GGML_OP_SUM_ROWS:
  7454. case GGML_OP_MEAN:
  7455. return true;
  7456. default:
  7457. return false;
  7458. }
  7459. }
  7460. static uint32_t get_misalign_bytes(const ggml_backend_vk_context * ctx, const ggml_tensor * t)
  7461. {
  7462. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  7463. }
  7464. 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) {
  7465. GGML_UNUSED(p);
  7466. GGML_UNUSED(src0);
  7467. GGML_UNUSED(src1);
  7468. GGML_UNUSED(src2);
  7469. GGML_UNUSED(src3);
  7470. GGML_UNUSED(dst);
  7471. static_assert(!std::is_const<T>::value, "unexpected type");
  7472. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  7473. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  7474. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  7475. GGML_ASSERT(!src3 || get_misalign_bytes(ctx, src3) == 0);
  7476. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  7477. }
  7478. 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) {
  7479. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7480. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7481. p.misalign_offsets = (a_offset << 16) | d_offset;
  7482. GGML_UNUSED(src1);
  7483. GGML_UNUSED(src2);
  7484. GGML_UNUSED(src3);
  7485. }
  7486. 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) {
  7487. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7488. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7489. p.misalign_offsets = (a_offset << 16) | d_offset;
  7490. GGML_UNUSED(src1);
  7491. GGML_UNUSED(src2);
  7492. GGML_UNUSED(src3);
  7493. }
  7494. 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) {
  7495. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7496. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7497. p.misalign_offsets = (a_offset << 16) | d_offset;
  7498. GGML_UNUSED(src1);
  7499. GGML_UNUSED(src2);
  7500. GGML_UNUSED(src3);
  7501. }
  7502. 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) {
  7503. const uint32_t a_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7504. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7505. p.misalign_offsets = (a_offset << 16) | d_offset;
  7506. GGML_UNUSED(src0);
  7507. GGML_UNUSED(src2);
  7508. GGML_UNUSED(src3);
  7509. }
  7510. 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) {
  7511. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7512. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7513. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7514. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  7515. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  7516. GGML_UNUSED(src2);
  7517. GGML_UNUSED(src3);
  7518. }
  7519. 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) {
  7520. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7521. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7522. p.a_offset = a_offset;
  7523. p.d_offset = d_offset;
  7524. GGML_UNUSED(src1);
  7525. GGML_UNUSED(src2);
  7526. GGML_UNUSED(src3);
  7527. }
  7528. template<typename PC>
  7529. 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) {
  7530. 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];
  7531. if (src1 != nullptr) {
  7532. 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];
  7533. }
  7534. if (src2 != nullptr) {
  7535. 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];
  7536. }
  7537. if (src3 != nullptr) {
  7538. 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];
  7539. }
  7540. 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];
  7541. std::cerr << "), " << ggml_op_name(op) << ")");
  7542. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  7543. GGML_ASSERT(ggml_vk_op_supports_incontiguous(op) || ggml_vk_dim01_contiguous(src0)); // NOLINT
  7544. GGML_ASSERT(dst->buffer != nullptr);
  7545. const uint64_t ne00 = src0->ne[0];
  7546. const uint64_t ne01 = src0->ne[1];
  7547. const uint64_t ne02 = src0->ne[2];
  7548. const uint64_t ne03 = src0->ne[3];
  7549. const bool use_src1 = src1 != nullptr;
  7550. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  7551. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  7552. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  7553. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  7554. const bool use_src2 = src2 != nullptr;
  7555. const bool use_src3 = src3 != nullptr;
  7556. init_pushconst_fastdiv(pc);
  7557. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  7558. if (pipeline == nullptr) {
  7559. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  7560. if (src1 != nullptr) {
  7561. std::cerr << " and " << ggml_type_name(src1->type);
  7562. }
  7563. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  7564. GGML_ABORT("fatal error");
  7565. }
  7566. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7567. const bool op_supports_incontiguous = ggml_vk_op_supports_incontiguous(op);
  7568. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0, op_supports_incontiguous);
  7569. vk_subbuffer src1_buf = use_src1 ? ggml_vk_tensor_subbuffer(ctx, src1, op_supports_incontiguous) : vk_subbuffer{};
  7570. vk_subbuffer src2_buf = use_src2 ? ggml_vk_tensor_subbuffer(ctx, src2, op_supports_incontiguous) : vk_subbuffer{};
  7571. vk_subbuffer src3_buf = use_src3 ? ggml_vk_tensor_subbuffer(ctx, src3, op_supports_incontiguous) : vk_subbuffer{};
  7572. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, op_supports_incontiguous);
  7573. // Compute misalignment offset for descriptors and store it in in push constants.
  7574. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, src3, dst);
  7575. std::array<uint32_t, 3> elements;
  7576. // Single call if dimension 2 is contiguous
  7577. GGML_ASSERT(op_supports_incontiguous || (ggml_is_contiguous(src0) && (src1 == nullptr || ggml_is_contiguous(src1))));
  7578. switch (op) {
  7579. case GGML_OP_NORM:
  7580. case GGML_OP_RMS_NORM_BACK:
  7581. case GGML_OP_L2_NORM:
  7582. case GGML_OP_SOFT_MAX:
  7583. case GGML_OP_SOFT_MAX_BACK:
  7584. case GGML_OP_SUM_ROWS:
  7585. case GGML_OP_MEAN:
  7586. case GGML_OP_ARGMAX:
  7587. {
  7588. const uint32_t nr = ggml_nrows(src0);
  7589. if (nr > 262144) {
  7590. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7591. } else if (nr > 512) {
  7592. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7593. } else {
  7594. elements = { nr, 1, 1 };
  7595. }
  7596. } break;
  7597. case GGML_OP_RMS_NORM:
  7598. if (ctx->do_add_rms_partials) {
  7599. // Run one element per thread, 128 threads per workgroup
  7600. elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 };
  7601. } else {
  7602. elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 };
  7603. }
  7604. break;
  7605. case GGML_OP_SUM:
  7606. // We use GGML_OP_SUM_ROWS with 1 row.
  7607. elements = { 1, 1, 1 };
  7608. break;
  7609. case GGML_OP_GROUP_NORM:
  7610. {
  7611. const uint32_t num_groups = dst->op_params[0];
  7612. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  7613. } break;
  7614. case GGML_OP_DIAG_MASK_INF:
  7615. case GGML_OP_ROPE:
  7616. case GGML_OP_ROPE_BACK:
  7617. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  7618. break;
  7619. case GGML_OP_GET_ROWS:
  7620. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  7621. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7622. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7623. break;
  7624. case GGML_OP_ARGSORT:
  7625. elements = { (uint32_t)ne00, (uint32_t)ggml_nrows(src0), 1 };
  7626. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7627. break;
  7628. case GGML_OP_IM2COL:
  7629. {
  7630. const bool is_2D = dst->op_params[6] == 1;
  7631. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  7632. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  7633. const uint32_t KW = src0->ne[0];
  7634. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  7635. const uint32_t OW = dst->ne[1];
  7636. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  7637. elements = { OW * KW * KH, OH, batch * IC };
  7638. } break;
  7639. case GGML_OP_IM2COL_3D:
  7640. {
  7641. const uint32_t IC = ((const uint32_t *)(dst->op_params))[9];
  7642. const uint32_t N = ne13 / IC;
  7643. const uint32_t KD = ne02;
  7644. const uint32_t KH = ne01;
  7645. const uint32_t KW = ne00;
  7646. const uint32_t OD = dst->ne[3] / N;
  7647. const uint32_t OH = dst->ne[2];
  7648. const uint32_t OW = dst->ne[1];
  7649. const uint32_t IC_KD_KH_KW = IC*KD*KH*KW;
  7650. const uint32_t N_OD_OH = N*OD*OH;
  7651. elements = { IC_KD_KH_KW, OW, N_OD_OH };
  7652. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7653. } break;
  7654. case GGML_OP_TIMESTEP_EMBEDDING:
  7655. {
  7656. const uint32_t dim = dst->op_params[0];
  7657. uint32_t half_ceil = (dim + 1) / 2;
  7658. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  7659. } break;
  7660. case GGML_OP_CONV_TRANSPOSE_1D:
  7661. {
  7662. elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1}
  7663. } break;
  7664. case GGML_OP_POOL_2D:
  7665. {
  7666. const uint32_t N = dst->ne[3];
  7667. const uint32_t OC = dst->ne[2];
  7668. const uint32_t OH = dst->ne[1];
  7669. const uint32_t OW = dst->ne[0];
  7670. elements = { N * OC * OH * OW, 1, 1};
  7671. } break;
  7672. case GGML_OP_CONV_2D:
  7673. {
  7674. elements = ggml_vk_get_conv_elements(dst);
  7675. } break;
  7676. case GGML_OP_CONV_TRANSPOSE_2D:
  7677. {
  7678. elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  7679. } break;
  7680. case GGML_OP_ADD:
  7681. case GGML_OP_SUB:
  7682. case GGML_OP_DIV:
  7683. case GGML_OP_MUL:
  7684. case GGML_OP_SCALE:
  7685. case GGML_OP_SQR:
  7686. case GGML_OP_SQRT:
  7687. case GGML_OP_SIN:
  7688. case GGML_OP_COS:
  7689. case GGML_OP_CLAMP:
  7690. case GGML_OP_PAD:
  7691. case GGML_OP_ROLL:
  7692. case GGML_OP_REPEAT:
  7693. case GGML_OP_REPEAT_BACK:
  7694. case GGML_OP_CPY:
  7695. case GGML_OP_CONCAT:
  7696. case GGML_OP_UPSCALE:
  7697. case GGML_OP_UNARY:
  7698. case GGML_OP_GLU:
  7699. case GGML_OP_CONV_2D_DW:
  7700. {
  7701. uint32_t ne = ggml_nelements(dst);
  7702. if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7703. // Convert from number of logical elements to 2- or 4-byte units.
  7704. ne /= ggml_blck_size(src0->type);
  7705. if ((ggml_type_size(src0->type) % 4) == 0) {
  7706. ne *= ggml_type_size(src0->type) / 4;
  7707. } else {
  7708. ne *= ggml_type_size(src0->type) / 2;
  7709. }
  7710. }
  7711. // copy_to_quant has block size of 32, and each thread does QUANT_K elements.
  7712. // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements.
  7713. // So divide by block size here before splitting into 512x512 groups.
  7714. if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7715. ne = CEIL_DIV(ne, ggml_blck_size(dst->type));
  7716. }
  7717. if (ne > 262144) {
  7718. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7719. } else if (ne > 512) {
  7720. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7721. } else {
  7722. elements = { ne, 1, 1 };
  7723. }
  7724. } break;
  7725. case GGML_OP_ADD_ID:
  7726. {
  7727. elements = { (uint32_t)ne01, (uint32_t)ne02, 1 };
  7728. } break;
  7729. case GGML_OP_SET_ROWS:
  7730. {
  7731. uint32_t ne = ggml_nelements(src0);
  7732. if (ggml_is_quantized(dst->type)) {
  7733. // quants run 32 threads each doing QUANT_K elements
  7734. ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type));
  7735. } else {
  7736. // scalar types do one element per thread, running 512 threads
  7737. ne = CEIL_DIV(ne, 512);
  7738. }
  7739. if (ne > 262144) {
  7740. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7741. } else if (ne > 512) {
  7742. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7743. } else {
  7744. elements = { ne, 1, 1 };
  7745. }
  7746. }
  7747. break;
  7748. case GGML_OP_SSM_CONV:
  7749. {
  7750. const uint32_t nr = src0->ne[1];
  7751. const uint32_t n_t = dst->ne[1];
  7752. const uint32_t n_s = dst->ne[2];
  7753. elements = { nr, n_t, n_s };
  7754. }
  7755. break;
  7756. default:
  7757. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  7758. break;
  7759. }
  7760. if (op == GGML_OP_ADD || op == GGML_OP_RMS_NORM) {
  7761. vk_subbuffer a_buf = src0_buf;
  7762. if (ctx->do_add_rms_partials) {
  7763. a_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset);
  7764. }
  7765. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7766. { src0_buf, src1_buf, dst_buf, a_buf }, pc, elements);
  7767. } else if (op == GGML_OP_GLU) {
  7768. // Empty src1 is possible in glu, but the shader needs a buffer
  7769. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  7770. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc, elements);
  7771. } else if (op == GGML_OP_SOFT_MAX) {
  7772. // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer
  7773. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  7774. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  7775. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, subbuf2, dst_buf }, pc, elements);
  7776. } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) {
  7777. // Empty src2 and src3 is possible in rope, but the shader needs a buffer
  7778. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  7779. vk_subbuffer subbuf3 = use_src3 ? src3_buf : src0_buf;
  7780. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, subbuf2, dst_buf, subbuf3 }, pc, elements);
  7781. } else if (op == GGML_OP_IM2COL || op == GGML_OP_IM2COL_3D) {
  7782. if (ctx->device->shader_int64 && ctx->device->buffer_device_address) {
  7783. // buffer device address path doesn't use dst buffer
  7784. dst_buf.size = 1;
  7785. }
  7786. // im2col uses only src1 and dst buffers
  7787. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src1_buf, dst_buf }, pc, elements);
  7788. } else if (op == GGML_OP_COUNT_EQUAL) {
  7789. // count_equal assumes that destination buffer is initialized with zeroes
  7790. ggml_vk_buffer_memset_async(subctx, dst_buf.buffer, dst_buf.offset, 0, dst_buf.size);
  7791. ggml_vk_sync_buffers(ctx, subctx);
  7792. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  7793. } else if (op == GGML_OP_OPT_STEP_SGD) {
  7794. // OPT_STEP_SGD works on src0, it does not need dst
  7795. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf }, pc, elements);
  7796. } else if (use_src3) {
  7797. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, src3_buf, dst_buf }, pc, elements);
  7798. } else if (use_src2) {
  7799. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, dst_buf }, pc, elements);
  7800. } else if (use_src1) {
  7801. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  7802. } else {
  7803. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, dst_buf }, pc, elements);
  7804. }
  7805. }
  7806. 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) {
  7807. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7808. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7809. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7810. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GET_ROWS, {
  7811. (uint32_t)ggml_nelements(src0),
  7812. (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,
  7813. (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,
  7814. (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,
  7815. 0,
  7816. 0.0f, 0.0f, 0,
  7817. });
  7818. }
  7819. static void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7820. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7821. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7822. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7823. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  7824. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  7825. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  7826. int offset = dst->op_params[3] / 4; // offset in bytes
  7827. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ACC, {
  7828. (uint32_t)ggml_nelements(src0),
  7829. (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,
  7830. (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,
  7831. (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,
  7832. 0,
  7833. 0.0f, 0.0f, offset,
  7834. });
  7835. }
  7836. static void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  7837. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  7838. const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  7839. // Make a list of all the tensors used by the op.
  7840. // Last element of the list is the dest tensor.
  7841. const ggml_tensor *tensors[MAX_PARAMETER_COUNT];
  7842. uint32_t num_srcs = ctx->num_additional_fused_ops + 2;
  7843. uint32_t num_tensors = num_srcs + 1;
  7844. GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT);
  7845. tensors[0] = first_node->src[0];
  7846. tensors[1] = first_node->src[1];
  7847. for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) {
  7848. // check whether the previous result is src[0] or src[1]
  7849. if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) {
  7850. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1];
  7851. } else {
  7852. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0];
  7853. }
  7854. }
  7855. tensors[num_srcs] = dst;
  7856. vk_op_multi_add_push_constants pc;
  7857. pc.ne20 = (uint32_t)dst->ne[0];
  7858. pc.ne21 = (uint32_t)dst->ne[1];
  7859. pc.ne22 = (uint32_t)dst->ne[2];
  7860. pc.ne23 = (uint32_t)dst->ne[3];
  7861. for (uint32_t i = 0; i < num_tensors; ++i) {
  7862. const ggml_tensor *t = tensors[i];
  7863. pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float);
  7864. pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float);
  7865. pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float);
  7866. pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float);
  7867. }
  7868. pc.rms_partials = ctx->do_add_rms_partials;
  7869. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, tensors[0], tensors[1], nullptr, dst, dst->op);
  7870. if (pipeline == nullptr) {
  7871. std::cerr << "ggml_vulkan: Error: Missing multi_add";
  7872. GGML_ABORT("fatal error");
  7873. }
  7874. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7875. ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT];
  7876. vk_buffer buf[MAX_PARAMETER_COUNT];
  7877. size_t offset[MAX_PARAMETER_COUNT];
  7878. bool uma[MAX_PARAMETER_COUNT];
  7879. for (uint32_t i = 0; i < num_tensors; ++i) {
  7880. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  7881. buf[i] = nullptr;
  7882. offset[i] = 0;
  7883. uma[i] = false;
  7884. if (ctx->device->uma) {
  7885. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  7886. uma[i] = buf[i] != nullptr;
  7887. }
  7888. if (!uma[i]) {
  7889. buf[i] = buf_ctx[i]->dev_buffer;
  7890. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  7891. }
  7892. GGML_ASSERT(buf[i] != nullptr);
  7893. }
  7894. // If any remaining descriptors are unused, just point them at src[0]
  7895. for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) {
  7896. buf[i] = buf[0];
  7897. offset[i] = 0;
  7898. }
  7899. if (ctx->do_add_rms_partials) {
  7900. buf[num_tensors] = ctx->prealloc_add_rms_partials;
  7901. offset[num_tensors] = ctx->prealloc_size_add_rms_partials_offset;
  7902. }
  7903. std::array<uint32_t, 3> elements;
  7904. uint32_t ne = ggml_nelements(dst);
  7905. if (ne > 262144) {
  7906. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7907. } else if (ne > 512) {
  7908. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7909. } else {
  7910. elements = { ne, 1, 1 };
  7911. }
  7912. static_assert(MAX_PARAMETER_COUNT == 12);
  7913. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7914. {
  7915. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  7916. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  7917. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  7918. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  7919. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  7920. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  7921. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  7922. ggml_vk_subbuffer(ctx, buf[7], offset[7]),
  7923. ggml_vk_subbuffer(ctx, buf[8], offset[8]),
  7924. ggml_vk_subbuffer(ctx, buf[9], offset[9]),
  7925. ggml_vk_subbuffer(ctx, buf[10], offset[10]),
  7926. ggml_vk_subbuffer(ctx, buf[11], offset[11]),
  7927. }, pc, elements);
  7928. }
  7929. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7930. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7931. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7932. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7933. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD, {
  7934. (uint32_t)ggml_nelements(src0),
  7935. (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,
  7936. (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,
  7937. (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,
  7938. 0,
  7939. 0.0f, 0.0f, ctx->do_add_rms_partials,
  7940. });
  7941. }
  7942. static void ggml_vk_sub(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7943. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7944. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7945. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7946. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SUB, {
  7947. (uint32_t)ggml_nelements(src0),
  7948. (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,
  7949. (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,
  7950. (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,
  7951. 0,
  7952. 0.0f, 0.0f, 0,
  7953. });
  7954. }
  7955. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7956. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7957. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7958. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7959. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_MUL, {
  7960. (uint32_t)ggml_nelements(src0),
  7961. (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,
  7962. (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,
  7963. (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,
  7964. 0,
  7965. 0.0f, 0.0f, 0,
  7966. });
  7967. }
  7968. static void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7969. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7970. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7971. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7972. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_DIV, {
  7973. (uint32_t)ggml_nelements(src0),
  7974. (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,
  7975. (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,
  7976. (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,
  7977. 0,
  7978. 0.0f, 0.0f, 0,
  7979. });
  7980. }
  7981. 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) {
  7982. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7983. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7984. const uint32_t src2_type_size = ggml_type_size(src2->type);
  7985. ggml_vk_op_f32<vk_op_add_id_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_ADD_ID, {
  7986. (uint32_t)dst->ne[0],
  7987. (uint32_t)dst->ne[1],
  7988. (uint32_t)src0->nb[1] / src0_type_size,
  7989. (uint32_t)src0->nb[2] / src0_type_size,
  7990. (uint32_t)src1->nb[1] / src1_type_size,
  7991. (uint32_t)src2->nb[1] / src2_type_size,
  7992. });
  7993. }
  7994. 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) {
  7995. GGML_ASSERT(version == 6 || version == 7);
  7996. int num_srcs = version == 6 ? 6 : 7;
  7997. for (int i = 0; i < num_srcs; i++) {
  7998. GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type));
  7999. }
  8000. GGML_ASSERT(dst->buffer != nullptr);
  8001. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op);
  8002. GGML_ASSERT(pipeline != nullptr);
  8003. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8004. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8005. vk_subbuffer src_buf[7] = {};
  8006. for (int i = 0; i < num_srcs; i++) {
  8007. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8008. }
  8009. std::array<uint32_t, 3> elements = {
  8010. (uint32_t)(pc.B * pc.H),
  8011. 1,
  8012. 1
  8013. };
  8014. if (version == 6) {
  8015. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8016. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf},
  8017. pc, elements);
  8018. } else if (version == 7) {
  8019. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8020. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8021. pc, elements);
  8022. } else {
  8023. // shouldn't happen
  8024. GGML_ASSERT(false);
  8025. }
  8026. }
  8027. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8028. const size_t seq_length = dst->src[0]->ne[2];
  8029. const size_t n_embed = dst->ne[0];
  8030. const size_t n_heads = dst->src[0]->ne[1];
  8031. const size_t n_seqs = dst->src[5]->ne[1];
  8032. ggml_vk_op_f32_wkv(
  8033. ctx, subctx, dst,
  8034. {
  8035. (uint32_t)n_seqs,
  8036. (uint32_t)seq_length,
  8037. (uint32_t)n_embed,
  8038. (uint32_t)n_heads,
  8039. },
  8040. 6
  8041. );
  8042. }
  8043. static void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8044. const size_t seq_length = dst->src[0]->ne[2];
  8045. const size_t n_embed = dst->ne[0];
  8046. const size_t n_heads = dst->src[0]->ne[1];
  8047. const size_t n_seqs = dst->src[6]->ne[1];
  8048. ggml_vk_op_f32_wkv(
  8049. ctx, subctx, dst,
  8050. {
  8051. (uint32_t)n_seqs,
  8052. (uint32_t)seq_length,
  8053. (uint32_t)n_embed,
  8054. (uint32_t)n_heads,
  8055. },
  8056. 7
  8057. );
  8058. }
  8059. static void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8060. const ggml_tensor * src0 = dst->src[0];
  8061. const ggml_tensor * src1 = dst->src[1];
  8062. const ggml_tensor * src2 = dst->src[2];
  8063. const ggml_tensor * src3 = dst->src[3];
  8064. const ggml_tensor * src4 = dst->src[4];
  8065. const ggml_tensor * src5 = dst->src[5];
  8066. GGML_ASSERT(dst->buffer != nullptr);
  8067. const uint32_t head_dim = src0->ne[1];
  8068. const uint32_t n_head = src1->ne[1];
  8069. const uint32_t n_group = src4->ne[1];
  8070. const uint32_t n_tok = src1->ne[2];
  8071. const uint32_t n_seq = src1->ne[3];
  8072. bool is_mamba2 = (src3->nb[1] == sizeof(float));
  8073. GGML_ASSERT(is_mamba2);
  8074. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op);
  8075. GGML_ASSERT(pipeline != nullptr);
  8076. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8077. const int64_t s_off = ggml_nelements(src1) * sizeof(float);
  8078. const vk_op_ssm_scan_push_constants pc = {
  8079. (uint32_t)src0->nb[2], (uint32_t)src0->nb[3],
  8080. (uint32_t)src1->nb[2], (uint32_t)src1->nb[3],
  8081. (uint32_t)src2->nb[1], (uint32_t)src2->nb[2],
  8082. (uint32_t)src3->nb[1],
  8083. (uint32_t)src4->nb[2], (uint32_t)src4->nb[3],
  8084. (uint32_t)src5->nb[2], (uint32_t)src5->nb[3],
  8085. (uint32_t)s_off,
  8086. n_head, head_dim, n_group, n_tok
  8087. };
  8088. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8089. vk_subbuffer src_buf[7] = {};
  8090. for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
  8091. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8092. }
  8093. std::array<uint32_t, 3> elements;
  8094. const int splitH = 16;
  8095. const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, splitH);
  8096. const uint32_t num_workgroups_y = n_seq;
  8097. elements = { num_workgroups_x, num_workgroups_y, 1 };
  8098. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8099. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8100. pc, elements);
  8101. }
  8102. static void ggml_vk_ssm_conv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8103. const ggml_tensor * src0 = dst->src[0];
  8104. const ggml_tensor * src1 = dst->src[1];
  8105. ggml_vk_op_f32<vk_op_ssm_conv_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SSM_CONV, {
  8106. (uint32_t)src0->nb[1], (uint32_t)src0->nb[2],
  8107. (uint32_t)src1->nb[1],
  8108. (uint32_t)dst->nb[0], (uint32_t)dst->nb[1], (uint32_t)dst->nb[2],
  8109. (uint32_t)src1->ne[0],
  8110. (uint32_t)src0->ne[0],
  8111. (uint32_t)src0->ne[1],
  8112. (uint32_t)dst->ne[1],
  8113. (uint32_t)dst->ne[2],
  8114. });
  8115. }
  8116. 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) {
  8117. const ggml_tensor * x = dst->src[0];
  8118. const ggml_tensor * g = dst->src[1];
  8119. const ggml_tensor * gm = dst->src[2];
  8120. const ggml_tensor * gv = dst->src[3];
  8121. const ggml_tensor * p = dst->src[4];
  8122. GGML_ASSERT(x->type == GGML_TYPE_F32);
  8123. GGML_ASSERT(g->type == GGML_TYPE_F32);
  8124. GGML_ASSERT(gm->type == GGML_TYPE_F32);
  8125. GGML_ASSERT(gv->type == GGML_TYPE_F32);
  8126. GGML_ASSERT(p->type == GGML_TYPE_F32);
  8127. GGML_ASSERT(dst->buffer != nullptr);
  8128. GGML_ASSERT(ggml_is_contiguous(x));
  8129. GGML_ASSERT(ggml_is_contiguous(g));
  8130. GGML_ASSERT(ggml_is_contiguous(gm));
  8131. GGML_ASSERT(ggml_is_contiguous(gv));
  8132. GGML_ASSERT(ggml_is_contiguous(p));
  8133. GGML_ASSERT(ggml_are_same_shape(x, g));
  8134. GGML_ASSERT(ggml_are_same_shape(x, gm));
  8135. GGML_ASSERT(ggml_are_same_shape(x, gv));
  8136. GGML_ASSERT(ggml_nelements(p) == 7);
  8137. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW);
  8138. GGML_ASSERT(pipeline != nullptr);
  8139. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8140. vk_subbuffer x_buf = ggml_vk_tensor_subbuffer(ctx, x);
  8141. vk_subbuffer g_buf = ggml_vk_tensor_subbuffer(ctx, g);
  8142. vk_subbuffer gm_buf = ggml_vk_tensor_subbuffer(ctx, gm);
  8143. vk_subbuffer gv_buf = ggml_vk_tensor_subbuffer(ctx, gv);
  8144. vk_subbuffer p_buf = ggml_vk_tensor_subbuffer(ctx, p);
  8145. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(x), 1, 1 };
  8146. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8147. {x_buf, g_buf, gm_buf, gv_buf, p_buf},
  8148. pc, elements);
  8149. }
  8150. static void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8151. const size_t n = ggml_nelements(dst->src[0]);
  8152. ggml_vk_op_f32_opt_step_adamw(
  8153. ctx, subctx, dst,
  8154. { (uint32_t)n, 0, 0.0f, 0.0f }
  8155. );
  8156. }
  8157. 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) {
  8158. const size_t n = ggml_nelements(dst->src[0]);
  8159. 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 });
  8160. }
  8161. static void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8162. int * op_params = (int *)dst->op_params;
  8163. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8164. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8165. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8166. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONCAT, {
  8167. (uint32_t)ggml_nelements(dst),
  8168. (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,
  8169. (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,
  8170. (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,
  8171. 0,
  8172. 0.0f, 0.0f, op_params[0],
  8173. });
  8174. }
  8175. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8176. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8177. const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0);
  8178. GGML_TENSOR_UNARY_OP_LOCALS
  8179. float sf0 = (float)ne0 / ne00;
  8180. float sf1 = (float)ne1 / ne01;
  8181. float sf2 = (float)ne2 / ne02;
  8182. float sf3 = (float)ne3 / ne03;
  8183. float pixel_offset = 0.5f;
  8184. if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) {
  8185. sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0;
  8186. sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1;
  8187. pixel_offset = 0.0f;
  8188. }
  8189. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  8190. (uint32_t)ggml_nelements(dst), 0, 0,
  8191. (uint32_t)ne00, (uint32_t)ne01,
  8192. (uint32_t)nb00 / src0_type_size, (uint32_t)nb01 / src0_type_size, (uint32_t)nb02 / src0_type_size, (uint32_t)nb03 / src0_type_size,
  8193. (uint32_t)ne0, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  8194. sf0, sf1, sf2, sf3, pixel_offset
  8195. });
  8196. }
  8197. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8198. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8199. p.param1 = ggml_get_op_params_f32(dst, 0);
  8200. p.param2 = ggml_get_op_params_f32(dst, 1);
  8201. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p));
  8202. }
  8203. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8204. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst));
  8205. }
  8206. static void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8207. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst));
  8208. }
  8209. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8210. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst));
  8211. }
  8212. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8213. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst));
  8214. }
  8215. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8216. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8217. p.param1 = ggml_get_op_params_f32(dst, 0);
  8218. p.param2 = ggml_get_op_params_f32(dst, 1);
  8219. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p));
  8220. }
  8221. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8222. vk_op_pad_push_constants p = vk_op_pad_push_constants_init(src0, dst);
  8223. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p));
  8224. }
  8225. static void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8226. const int32_t s0 = ggml_get_op_params_i32(dst, 0);
  8227. const int32_t s1 = ggml_get_op_params_i32(dst, 1);
  8228. const int32_t s2 = ggml_get_op_params_i32(dst, 2);
  8229. const int32_t s3 = ggml_get_op_params_i32(dst, 3);
  8230. const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
  8231. const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
  8232. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8233. memcpy(&p.param1, &s01_packed, sizeof(float));
  8234. memcpy(&p.param2, &s23_packed, sizeof(float));
  8235. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p));
  8236. }
  8237. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8238. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8239. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p));
  8240. }
  8241. static void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8242. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8243. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p));
  8244. }
  8245. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8246. uint32_t ne = (uint32_t)ggml_nelements(src0);
  8247. if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8248. // Convert from number of logical elements to 2- or 4-byte units.
  8249. ne /= ggml_blck_size(src0->type);
  8250. if ((ggml_type_size(src0->type) % 4) == 0) {
  8251. ne *= ggml_type_size(src0->type) / 4;
  8252. } else {
  8253. ne *= ggml_type_size(src0->type) / 2;
  8254. }
  8255. }
  8256. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne);
  8257. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p));
  8258. }
  8259. 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) {
  8260. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8261. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8262. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8263. // Skip empty skip_rows operations. For most ops the empty check at the start
  8264. // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst
  8265. // with empty srcs.
  8266. if (ggml_is_empty(src0) || ggml_is_empty(src1)) {
  8267. return;
  8268. }
  8269. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SET_ROWS, {
  8270. (uint32_t)ggml_nelements(src0),
  8271. (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,
  8272. (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,
  8273. (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,
  8274. 0,
  8275. 0.0f, 0.0f, 0,
  8276. });
  8277. }
  8278. 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) {
  8279. 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 });
  8280. }
  8281. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8282. float * op_params = (float *)dst->op_params;
  8283. 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 });
  8284. }
  8285. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8286. const int * int_op_params = (const int *)dst->op_params;
  8287. const float * float_op_params = (const float *)dst->op_params;
  8288. const uint32_t num_groups = int_op_params[0];
  8289. const float eps = float_op_params[1];
  8290. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  8291. 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 });
  8292. }
  8293. static uint32_t ggml_vk_rms_num_partials(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8294. const uint32_t ne = (uint32_t)node->ne[0];
  8295. const uint32_t denom = ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0];
  8296. const uint32_t num_partials = CEIL_DIV(ne, denom);
  8297. return num_partials;
  8298. }
  8299. static uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8300. const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node);
  8301. const uint32_t num_bytes = ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment);
  8302. return num_bytes;
  8303. }
  8304. 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) {
  8305. const int n_dims = ((const int32_t *) dst->op_params)[1];
  8306. const int mode = ((const int32_t *) dst->op_params)[2];
  8307. // const int n_ctx = ((const int32_t *) dst->op_params)[3];
  8308. const int n_ctx_orig = ((const int32_t *) dst->op_params)[4];
  8309. const float freq_base = ((const float *) dst->op_params)[5];
  8310. const float freq_scale = ((const float *) dst->op_params)[6];
  8311. const float ext_factor = ((const float *) dst->op_params)[7];
  8312. const float attn_factor = ((const float *) dst->op_params)[8];
  8313. const float beta_fast = ((const float *) dst->op_params)[9];
  8314. const float beta_slow = ((const float *) dst->op_params)[10];
  8315. int sections[4] {};
  8316. if (mode & GGML_ROPE_TYPE_MROPE) {
  8317. memcpy(sections, (const int32_t *) dst->op_params + 11, sizeof(int)*4);
  8318. }
  8319. const bool is_imrope = mode == GGML_ROPE_TYPE_IMROPE;
  8320. float corr_dims[2];
  8321. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8322. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  8323. uint32_t nb01 = src0->nb[1] / ggml_type_size(src0->type);
  8324. uint32_t nb02 = src0->nb[2] / ggml_type_size(src0->type);
  8325. vk_op_rope_push_constants rope {
  8326. (uint32_t)mode, (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  8327. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  8328. has_ff, (uint32_t)src0->ne[2], nb01, nb02,
  8329. { sections[0], sections[1], sections[2], sections[3] }, is_imrope, backprop, set_rows_stride,
  8330. };
  8331. return rope;
  8332. }
  8333. 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) {
  8334. ggml_tensor * dst;
  8335. const ggml_tensor * src0;
  8336. const ggml_tensor * src1;
  8337. if (ctx->num_additional_fused_ops > 0) {
  8338. // fused rms_norm + mul
  8339. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8340. ggml_tensor *other_src = mul->src[0] == cgraph->nodes[node_idx + 0] ? mul->src[1] : mul->src[0];
  8341. dst = mul;
  8342. src0 = cgraph->nodes[node_idx]->src[0];
  8343. src1 = other_src;
  8344. } else {
  8345. dst = cgraph->nodes[node_idx];
  8346. src0 = src1 = dst->src[0];
  8347. }
  8348. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8349. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8350. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8351. uint32_t param3 = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0;
  8352. vk_op_binary_push_constants bin {
  8353. (uint32_t)ggml_nelements(src0),
  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. op_params[0], 0.0f, (int32_t)param3,
  8359. };
  8360. // more than one fused op means rms_norm+mul+rope
  8361. if (ctx->num_additional_fused_ops > 1) {
  8362. static constexpr uint32_t max_tensors = 7;
  8363. const ggml_tensor *tensors[max_tensors] {};
  8364. ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  8365. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8366. ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  8367. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  8368. bool do_set_rows = ctx->num_additional_fused_ops == 4;
  8369. tensors[0] = rms->src[0];
  8370. tensors[1] = other_src;
  8371. tensors[2] = mul;
  8372. tensors[3] = rope->src[1]; // pos
  8373. tensors[4] = rope->src[2]; // ff
  8374. tensors[5] = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; // dst
  8375. tensors[6] = do_set_rows ? tensors[5]->src[1] : nullptr;
  8376. const uint32_t set_rows_stride = do_set_rows ? tensors[5]->nb[1] / ggml_type_size(tensors[5]->type) : 0;
  8377. vk_op_rms_norm_mul_rope_push_constants pc;
  8378. pc.bin = bin;
  8379. pc.rope = ggml_vk_make_rope_constants(rope, rope->src[0], tensors[4] != nullptr, false, set_rows_stride);
  8380. 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;
  8381. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8382. ggml_backend_vk_buffer_context * buf_ctx[max_tensors];
  8383. vk_buffer buf[max_tensors];
  8384. size_t offset[max_tensors];
  8385. bool uma[max_tensors];
  8386. for (uint32_t i = 0; i < max_tensors; ++i) {
  8387. if (!tensors[i]) {
  8388. // If any remaining descriptors are unused, just point them at src[0]
  8389. buf[i] = buf[0];
  8390. offset[i] = 0;
  8391. continue;
  8392. }
  8393. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8394. buf[i] = nullptr;
  8395. offset[i] = 0;
  8396. uma[i] = false;
  8397. if (ctx->device->uma) {
  8398. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8399. uma[i] = buf[i] != nullptr;
  8400. }
  8401. if (!uma[i]) {
  8402. buf[i] = buf_ctx[i]->dev_buffer;
  8403. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8404. }
  8405. GGML_ASSERT(buf[i] != nullptr);
  8406. }
  8407. std::array<uint32_t, 3> elements;
  8408. elements = { (uint32_t)rms->src[0]->ne[1], (uint32_t)rms->src[0]->ne[2], (uint32_t)rms->src[0]->ne[3] };
  8409. static_assert(max_tensors == 7);
  8410. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8411. {
  8412. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8413. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8414. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8415. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8416. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8417. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8418. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8419. }, pc, elements);
  8420. } else {
  8421. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM, std::move(bin));
  8422. }
  8423. if (ctx->do_add_rms_partials_offset_calculation) {
  8424. ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0);
  8425. ctx->do_add_rms_partials = false;
  8426. ctx->do_add_rms_partials_offset_calculation = false;
  8427. }
  8428. }
  8429. 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) {
  8430. float * op_params = (float *)dst->op_params;
  8431. 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 });
  8432. }
  8433. static void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8434. float * op_params = (float *)dst->op_params;
  8435. 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 });
  8436. }
  8437. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8438. 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 });
  8439. }
  8440. static void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8441. const float * op_params_f = (const float *)dst->op_params;
  8442. const bool swapped = (bool)dst->op_params[1];
  8443. const bool split = src1 != nullptr;
  8444. const float alpha = op_params_f[2];
  8445. const float limit = op_params_f[3];
  8446. GGML_ASSERT(ggml_is_contiguous(src0));
  8447. if (!split) {
  8448. GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]);
  8449. } else {
  8450. GGML_ASSERT(src0->ne[0] == src1->ne[0]);
  8451. GGML_ASSERT(src0->ne[0] == dst->ne[0]);
  8452. GGML_ASSERT(src0->type == src1->type);
  8453. }
  8454. const uint32_t mode = split ? 2 : (swapped ? 1 : 0);
  8455. ggml_vk_op_f32<vk_op_glu_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GLU,
  8456. {
  8457. (uint32_t)ggml_nelements(dst),
  8458. (uint32_t)src0->ne[0],
  8459. (uint32_t)dst->ne[0],
  8460. mode,
  8461. alpha,
  8462. limit
  8463. });
  8464. }
  8465. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8466. int32_t * op_params = (int32_t *)dst->op_params;
  8467. 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] });
  8468. }
  8469. 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) {
  8470. float * op_params = (float *)dst->op_params;
  8471. float scale = op_params[0];
  8472. float max_bias = op_params[1];
  8473. const uint32_t ncols = (uint32_t)src0->ne[0];
  8474. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  8475. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  8476. const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u;
  8477. const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u;
  8478. const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u;
  8479. const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u;
  8480. const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u;
  8481. const uint32_t n_head_kv = src0->ne[2];
  8482. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  8483. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  8484. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  8485. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_SOFT_MAX, {
  8486. ncols,
  8487. src1 != nullptr ? nrows_y : (uint32_t)0,
  8488. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],
  8489. ne12, ne13,
  8490. nb11, nb12, nb13,
  8491. scale, max_bias,
  8492. m0, m1,
  8493. n_head_log2,
  8494. nrows_x,
  8495. src2 != nullptr
  8496. });
  8497. }
  8498. 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) {
  8499. float * op_params = (float *)dst->op_params;
  8500. 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] });
  8501. }
  8502. static void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  8503. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  8504. ggml_tensor * logits = cgraph->nodes[node_idx + 0]->src[0];
  8505. ggml_tensor * weights = (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) ? cgraph->nodes[node_idx + 9] :
  8506. (mode == TOPK_MOE_EARLY_SOFTMAX) ? cgraph->nodes[node_idx + 4] :
  8507. cgraph->nodes[node_idx + 5];
  8508. ggml_tensor * ids = (mode == TOPK_MOE_LATE_SOFTMAX) ? cgraph->nodes[node_idx + 1] : cgraph->nodes[node_idx + 3];
  8509. GGML_ASSERT(logits->type == GGML_TYPE_F32);
  8510. GGML_ASSERT(weights->type == GGML_TYPE_F32);
  8511. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  8512. const int n_experts = logits->ne[0];
  8513. const int n_rows = logits->ne[1];
  8514. const int n_expert_used = weights->ne[1];
  8515. GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) n_experts);
  8516. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, cgraph->nodes[node_idx], GGML_OP_SOFT_MAX);
  8517. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8518. vk_subbuffer logits_buf = ggml_vk_tensor_subbuffer(ctx, logits);
  8519. vk_subbuffer weights_buf = ggml_vk_tensor_subbuffer(ctx, weights);
  8520. vk_subbuffer ids_buf = ggml_vk_tensor_subbuffer(ctx, ids);
  8521. vk_op_topk_moe_push_constants pc {};
  8522. pc.n_rows = n_rows;
  8523. pc.n_expert_used = n_expert_used;
  8524. if (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) {
  8525. ggml_tensor * clamp = cgraph->nodes[node_idx + 7];
  8526. pc.clamp_min = ggml_get_op_params_f32(clamp, 0);
  8527. pc.clamp_max = ggml_get_op_params_f32(clamp, 1);
  8528. }
  8529. GGML_ASSERT(n_expert_used <= n_experts);
  8530. const uint32_t rows_per_block = 4;
  8531. std::array<uint32_t, 3> elements = { CEIL_DIV(n_rows, rows_per_block), 1, 1 };
  8532. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {logits_buf, weights_buf, ids_buf}, pc, elements);
  8533. }
  8534. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_cgraph * cgraph, int node_idx, bool backprop) {
  8535. ggml_tensor * dst = cgraph->nodes[node_idx];
  8536. const ggml_tensor * src0 = dst->src[0];
  8537. const ggml_tensor * src1 = dst->src[1];
  8538. const ggml_tensor * src2 = dst->src[2];
  8539. const ggml_tensor * src3 = nullptr;
  8540. const int n_dims = ((int32_t *) dst->op_params)[1];
  8541. const int mode = ((int32_t *) dst->op_params)[2];
  8542. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  8543. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  8544. const float freq_base = ((float *) dst->op_params)[5];
  8545. const float beta_fast = ((float *) dst->op_params)[9];
  8546. const float beta_slow = ((float *) dst->op_params)[10];
  8547. int sections[4] {};
  8548. if (mode & GGML_ROPE_TYPE_MROPE) {
  8549. memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4);
  8550. }
  8551. float corr_dims[2];
  8552. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8553. uint32_t set_rows_stride = 0;
  8554. // Fused rope + view + set_rows passes the set_rows destination stride in set_rows_stride
  8555. // and overrides the dst and sets src3=row_indices
  8556. if (ctx->num_additional_fused_ops > 0) {
  8557. set_rows_stride = cgraph->nodes[node_idx + 2]->nb[1] / ggml_type_size(cgraph->nodes[node_idx + 2]->type);
  8558. src3 = cgraph->nodes[node_idx + 2]->src[1];
  8559. dst = cgraph->nodes[node_idx + 2];
  8560. }
  8561. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, src3, dst, GGML_OP_ROPE,
  8562. ggml_vk_make_rope_constants(cgraph->nodes[node_idx], src0, src2 != nullptr, backprop, set_rows_stride));
  8563. }
  8564. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8565. int32_t * op_params = (int32_t *)dst->op_params;
  8566. uint32_t ncols = src0->ne[0];
  8567. uint32_t nrows = ggml_nrows(src0);
  8568. ggml_vk_op_f32<vk_op_argsort_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ARGSORT, {
  8569. ncols,
  8570. nrows,
  8571. op_params[0],
  8572. });
  8573. }
  8574. static void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8575. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, ggml_nelements(src0));
  8576. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM, p);
  8577. }
  8578. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8579. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8580. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, p);
  8581. }
  8582. static void ggml_vk_mean(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8583. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8584. p.weight = 1.0f / (float)src0->ne[0];
  8585. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_MEAN, p);
  8586. }
  8587. static void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8588. 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 });
  8589. }
  8590. 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) {
  8591. 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 });
  8592. }
  8593. static void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8594. const int32_t s0 = dst->op_params[0];
  8595. const int32_t s1 = dst->op_params[1];
  8596. const int32_t p0 = dst->op_params[2];
  8597. const int32_t p1 = dst->op_params[3];
  8598. const int32_t d0 = dst->op_params[4];
  8599. const int32_t d1 = dst->op_params[5];
  8600. const bool is_2D = dst->op_params[6] == 1;
  8601. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  8602. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  8603. const uint32_t IW = src1->ne[0];
  8604. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  8605. const uint32_t KW = src0->ne[0];
  8606. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  8607. const uint32_t OW = dst->ne[1];
  8608. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  8609. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  8610. const uint32_t pelements = OW * KW * KH;
  8611. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8612. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  8613. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  8614. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL, {
  8615. dst_addr,
  8616. batch_offset, offset_delta,
  8617. IC, IW, IH, OW, OH, KW, KH,
  8618. pelements,
  8619. IC * KH * KW,
  8620. s0, s1, p0, p1, d0, d1,
  8621. });
  8622. }
  8623. 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) {
  8624. GGML_TENSOR_BINARY_OP_LOCALS
  8625. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  8626. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  8627. const int32_t s2 = ((const int32_t *)(dst->op_params))[2];
  8628. const int32_t p0 = ((const int32_t *)(dst->op_params))[3];
  8629. const int32_t p1 = ((const int32_t *)(dst->op_params))[4];
  8630. const int32_t p2 = ((const int32_t *)(dst->op_params))[5];
  8631. const int32_t d0 = ((const int32_t *)(dst->op_params))[6];
  8632. const int32_t d1 = ((const int32_t *)(dst->op_params))[7];
  8633. const int32_t d2 = ((const int32_t *)(dst->op_params))[8];
  8634. const int32_t IC = ((const int32_t *)(dst->op_params))[9];
  8635. const int64_t N = ne13 / IC;
  8636. const int64_t ID = ne12;
  8637. const int64_t IH = ne11;
  8638. const int64_t IW = ne10;
  8639. const int64_t KD = ne02;
  8640. const int64_t KH = ne01;
  8641. const int64_t KW = ne00;
  8642. const int64_t OD = ne3 / N;
  8643. const int64_t OH = ne2;
  8644. const int64_t OW = ne1;
  8645. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8646. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  8647. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  8648. vk_op_im2col_3d_push_constants pc {};
  8649. pc.dst_addr = dst_addr;
  8650. pc.nb10 = nb10 / ggml_type_size(src1->type);
  8651. pc.nb11 = nb11 / ggml_type_size(src1->type);
  8652. pc.nb12 = nb12 / ggml_type_size(src1->type);
  8653. pc.nb13 = nb13 / ggml_type_size(src1->type);
  8654. pc.s0 = s0;
  8655. pc.s1 = s1;
  8656. pc.s2 = s2;
  8657. pc.p0 = p0;
  8658. pc.p1 = p1;
  8659. pc.p2 = p2;
  8660. pc.d0 = d0;
  8661. pc.d1 = d1;
  8662. pc.d2 = d2;
  8663. pc.IW = IW;
  8664. pc.IH = IH;
  8665. pc.ID = ID;
  8666. pc.IC = IC;
  8667. pc.KW = KW;
  8668. pc.OH = OH;
  8669. pc.KD_KH_KW = KD*KH*KW;
  8670. pc.KH_KW = KH*KW;
  8671. pc.IC_KD_KH_KW = IC*KD*KH*KW;
  8672. pc.N_OD_OH = N*OD*OH;
  8673. pc.OD_OH = OD*OH;
  8674. pc.OD_OH_OW_IC_KD_KH_KW = OD*OH*OW*IC*KD*KH*KW;
  8675. pc.OH_OW_IC_KD_KH_KW = OH*OW*IC*KD*KH*KW;
  8676. pc.OW_IC_KD_KH_KW = OW*IC*KD*KH*KW;
  8677. ggml_vk_op_f32<vk_op_im2col_3d_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL_3D, std::move(pc));
  8678. }
  8679. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8680. const uint32_t dim = dst->op_params[0];
  8681. const uint32_t max_period = dst->op_params[1];
  8682. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  8683. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  8684. nb1, dim, max_period,
  8685. });
  8686. }
  8687. 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) {
  8688. // src0: (K, Cout, Cin, 1) -- kernel
  8689. // src1: (L, Cin, 1, 1) -- input
  8690. // dst: (*, Cout, 1, 1)
  8691. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  8692. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8693. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  8694. GGML_TENSOR_BINARY_OP_LOCALS
  8695. GGML_ASSERT(nb00 == sizeof(float));
  8696. GGML_ASSERT(nb10 == sizeof(float));
  8697. const int32_t s0 = dst->op_params[0];
  8698. vk_op_conv_transpose_1d_push_constants p{};
  8699. p.Cout = static_cast<uint32_t>(ne01);
  8700. p.Cin = static_cast<uint32_t>(ne02);
  8701. p.K = static_cast<uint32_t>(ne00);
  8702. p.L = static_cast<uint32_t>(ne10);
  8703. p.KL = static_cast<uint32_t>(ne0);
  8704. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8705. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8706. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8707. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8708. p.s0 = static_cast<uint32_t>(s0);
  8709. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p));
  8710. }
  8711. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8712. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  8713. const int32_t k1 = dst->op_params[1];
  8714. const int32_t k0 = dst->op_params[2];
  8715. const int32_t s1 = dst->op_params[3];
  8716. const int32_t s0 = dst->op_params[4];
  8717. const int32_t p1 = dst->op_params[5];
  8718. const int32_t p0 = dst->op_params[6];
  8719. const uint32_t IH = src0->ne[1];
  8720. const uint32_t IW = src0->ne[0];
  8721. const uint32_t N = dst->ne[3];
  8722. const uint32_t OC = dst->ne[2];
  8723. const uint32_t OH = dst->ne[1];
  8724. const uint32_t OW = dst->ne[0];
  8725. const uint32_t parallel_elements = N * OC * OH * OW;
  8726. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  8727. IW, IH, OW, OH, OC,
  8728. parallel_elements,
  8729. op,
  8730. k0, k1, s0, s1, p0, p1,
  8731. });
  8732. }
  8733. static void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8734. const ggml_tensor * src1, ggml_tensor * dst) {
  8735. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8736. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8737. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8738. GGML_TENSOR_BINARY_OP_LOCALS
  8739. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8740. GGML_ASSERT(nb10 == sizeof(float));
  8741. GGML_ASSERT(nb0 == sizeof(float));
  8742. vk_op_conv2d_push_constants p{};
  8743. p.Cout = static_cast<uint32_t>(ne03);
  8744. p.Cin = static_cast<uint32_t>(ne02);
  8745. p.N = static_cast<uint32_t>(ne13);
  8746. p.KW = static_cast<uint32_t>(ne00);
  8747. p.KH = static_cast<uint32_t>(ne01);
  8748. p.W = static_cast<uint32_t>(ne10);
  8749. p.H = static_cast<uint32_t>(ne11);
  8750. p.OW = static_cast<uint32_t>(ne0);
  8751. p.OH = static_cast<uint32_t>(ne1);
  8752. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8753. p.s1 = static_cast<uint32_t>(dst->op_params[1]);
  8754. p.p0 = static_cast<uint32_t>(dst->op_params[2]);
  8755. p.p1 = static_cast<uint32_t>(dst->op_params[3]);
  8756. p.d0 = static_cast<uint32_t>(dst->op_params[4]);
  8757. p.d1 = static_cast<uint32_t>(dst->op_params[5]);
  8758. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8759. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8760. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  8761. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8762. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  8763. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  8764. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8765. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  8766. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  8767. GGML_ASSERT(ne03 == ne2);
  8768. GGML_ASSERT(ne02 == ne12);
  8769. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D, std::move(p));
  8770. }
  8771. static void ggml_vk_conv_transpose_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8772. const ggml_tensor * src1, ggml_tensor * dst) {
  8773. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8774. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8775. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8776. GGML_TENSOR_BINARY_OP_LOCALS
  8777. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8778. GGML_ASSERT(nb10 == sizeof(float));
  8779. GGML_ASSERT(nb0 == sizeof(float));
  8780. vk_op_conv_transpose_2d_push_constants p{};
  8781. p.Cout = static_cast<uint32_t>(ne02);
  8782. p.Cin = static_cast<uint32_t>(ne03);
  8783. p.N = static_cast<uint32_t>(ne13);
  8784. p.KW = static_cast<uint32_t>(ne00);
  8785. p.KH = static_cast<uint32_t>(ne01);
  8786. p.W = static_cast<uint32_t>(ne10);
  8787. p.H = static_cast<uint32_t>(ne11);
  8788. p.OW = static_cast<uint32_t>(ne0);
  8789. p.OH = static_cast<uint32_t>(ne1);
  8790. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8791. p.s1 = static_cast<uint32_t>(dst->op_params[0]);
  8792. p.p0 = 0;
  8793. p.p1 = 0;
  8794. p.d0 = 1;
  8795. p.d1 = 1;
  8796. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8797. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8798. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  8799. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8800. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  8801. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  8802. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8803. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  8804. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  8805. GGML_ASSERT(ne02 == ne2);
  8806. GGML_ASSERT(ne03 == ne12);
  8807. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_2D, std::move(p));
  8808. }
  8809. 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) {
  8810. vk_op_conv2d_dw_push_constants p{};
  8811. p.ne = ggml_nelements(dst);
  8812. p.channels = dst->ne[2];
  8813. p.batches = dst->ne[3];
  8814. p.dst_w = dst->ne[0];
  8815. p.dst_h = dst->ne[1];
  8816. p.src_w = src1->ne[0];
  8817. p.src_h = src1->ne[1];
  8818. p.knl_w = src0->ne[0];
  8819. p.knl_h = src0->ne[1];
  8820. p.stride_x = dst->op_params[0];
  8821. p.stride_y = dst->op_params[1];
  8822. p.pad_x = dst->op_params[2];
  8823. p.pad_y = dst->op_params[3];
  8824. p.dilation_x = dst->op_params[4];
  8825. p.dilation_y = dst->op_params[5];
  8826. GGML_ASSERT(src0->ne[3] == p.channels);
  8827. GGML_ASSERT(src1->ne[3] == p.batches);
  8828. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p));
  8829. }
  8830. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8831. const float * op_params = (const float *)dst->op_params;
  8832. 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 });
  8833. }
  8834. #ifdef GGML_VULKAN_RUN_TESTS
  8835. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  8836. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  8837. return;
  8838. }
  8839. i0 = std::max(i0, 5);
  8840. i1 = std::max(i1, 5);
  8841. i2 = std::max(i2, 0);
  8842. fprintf(stderr, " ");
  8843. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8844. fprintf(stderr, "%7d ", idx1);
  8845. }
  8846. fprintf(stderr, "\n");
  8847. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  8848. fprintf(stderr, "%7d: ", idx0);
  8849. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8850. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  8851. float val;
  8852. if (type == GGML_TYPE_F32) {
  8853. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  8854. } else if (type == GGML_TYPE_F16) {
  8855. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  8856. } else {
  8857. GGML_ABORT("fatal error");
  8858. }
  8859. fprintf(stderr, "% 7.2f ", val);
  8860. } else {
  8861. fprintf(stderr, " ");
  8862. }
  8863. }
  8864. fprintf(stderr, "\n");
  8865. }
  8866. }
  8867. template <typename X_TYPE, typename Y_TYPE>
  8868. 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) {
  8869. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  8870. const size_t x_ne = m * k * batch;
  8871. const size_t y_ne = k * n * batch;
  8872. const size_t d_ne = m * n * batch;
  8873. vk_pipeline p;
  8874. std::string shname;
  8875. if (shader_size == 0) {
  8876. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8877. p = ctx->device->pipeline_matmul_f32->a_s;
  8878. shname = "F32_ALIGNED_S";
  8879. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8880. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  8881. shname = "F32_F16_ALIGNED_S";
  8882. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8883. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  8884. shname = "F16_F32_ALIGNED_S";
  8885. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8886. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  8887. shname = "F16_ALIGNED_S";
  8888. } else {
  8889. GGML_ABORT("fatal error");
  8890. }
  8891. } else if (shader_size == 1) {
  8892. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8893. p = ctx->device->pipeline_matmul_f32->a_m;
  8894. shname = "F32_ALIGNED_M";
  8895. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8896. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  8897. shname = "F32_F16_ALIGNED_M";
  8898. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8899. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  8900. shname = "F16_F32_ALIGNED_M";
  8901. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8902. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  8903. shname = "F16_ALIGNED_M";
  8904. } else {
  8905. GGML_ABORT("fatal error");
  8906. }
  8907. } else if (shader_size == 2) {
  8908. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8909. p = ctx->device->pipeline_matmul_f32->a_l;
  8910. shname = "F32_ALIGNED_L";
  8911. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8912. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  8913. shname = "F32_F16_ALIGNED_L";
  8914. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8915. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  8916. shname = "F16_F32_ALIGNED_L";
  8917. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8918. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  8919. shname = "F16_ALIGNED_L";
  8920. } else {
  8921. GGML_ABORT("fatal error");
  8922. }
  8923. } else {
  8924. GGML_ASSERT(0);
  8925. }
  8926. const size_t kpad = ggml_vk_align_size(k, p->align);
  8927. if (k != kpad) {
  8928. if (shader_size == 0) {
  8929. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8930. p = ctx->device->pipeline_matmul_f32->s;
  8931. shname = "F32_S";
  8932. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8933. p = ctx->device->pipeline_matmul_f32_f16->s;
  8934. shname = "F32_F16_S";
  8935. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8936. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  8937. shname = "F16_F32_S";
  8938. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8939. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  8940. shname = "F16_S";
  8941. }
  8942. } else if (shader_size == 1) {
  8943. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8944. p = ctx->device->pipeline_matmul_f32->m;
  8945. shname = "F32_M";
  8946. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8947. p = ctx->device->pipeline_matmul_f32_f16->m;
  8948. shname = "F32_F16_M";
  8949. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8950. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  8951. shname = "F16_F32_M";
  8952. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8953. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  8954. shname = "F16_M";
  8955. }
  8956. } else if (shader_size == 2) {
  8957. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8958. p = ctx->device->pipeline_matmul_f32->l;
  8959. shname = "F32_L";
  8960. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8961. p = ctx->device->pipeline_matmul_f32_f16->l;
  8962. shname = "F32_F16_L";
  8963. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8964. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  8965. shname = "F16_F32_L";
  8966. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8967. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  8968. shname = "F16_L";
  8969. }
  8970. }
  8971. }
  8972. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  8973. if (split_k > 1) {
  8974. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  8975. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  8976. // Resize buffer
  8977. if (ctx->prealloc_split_k != nullptr) {
  8978. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  8979. }
  8980. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8981. }
  8982. }
  8983. ggml_pipeline_allocate_descriptor_sets(ctx);
  8984. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8985. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8986. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8987. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  8988. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  8989. float* d = (float *) malloc(sizeof(float) * d_ne);
  8990. for (size_t i = 0; i < x_ne; i++) {
  8991. if (std::is_same<float, X_TYPE>()) {
  8992. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  8993. // x[i] = 1.0f;
  8994. // x[i] = i + 1;
  8995. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  8996. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  8997. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  8998. // x[i] = ggml_fp32_to_fp16(1.0f);
  8999. // x[i] = ggml_fp32_to_fp16(i + 1);
  9000. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9001. } else {
  9002. GGML_ABORT("fatal error");
  9003. }
  9004. }
  9005. for (size_t i = 0; i < y_ne; i++) {
  9006. if (std::is_same<float, Y_TYPE>()) {
  9007. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9008. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9009. // y[i] = i + 1;
  9010. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9011. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9012. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9013. // y[i] = ggml_fp32_to_fp16(i + 1);
  9014. } else {
  9015. GGML_ABORT("fatal error");
  9016. }
  9017. }
  9018. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  9019. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  9020. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9021. ggml_vk_ctx_begin(ctx->device, subctx);
  9022. for (size_t i = 0; i < num_it; i++) {
  9023. ggml_vk_matmul(
  9024. 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),
  9025. m, n, k,
  9026. k, k, m, k*m, k*n, m*n,
  9027. split_k, batch, batch, batch, 1, 1, n
  9028. );
  9029. }
  9030. ggml_vk_ctx_end(subctx);
  9031. auto begin = std::chrono::high_resolution_clock::now();
  9032. ggml_vk_submit(subctx, ctx->fence);
  9033. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  9034. ctx->device->device.resetFences({ ctx->fence });
  9035. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9036. auto end = std::chrono::high_resolution_clock::now();
  9037. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9038. // copy dst to host
  9039. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  9040. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  9041. ggml_init_params iparams = {
  9042. /*.mem_size =*/ 1024*1024*1024,
  9043. /*.mem_buffer =*/ NULL,
  9044. /*.no_alloc =*/ true,
  9045. };
  9046. ggml_context * ggml_ctx = ggml_init(iparams);
  9047. ggml_type src0_type;
  9048. ggml_type src1_type;
  9049. if (std::is_same<float, X_TYPE>()) {
  9050. src0_type = GGML_TYPE_F32;
  9051. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9052. src0_type = GGML_TYPE_F16;
  9053. } else {
  9054. GGML_ABORT("fatal error");
  9055. }
  9056. if (std::is_same<float, Y_TYPE>()) {
  9057. src1_type = GGML_TYPE_F32;
  9058. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9059. src1_type = GGML_TYPE_F16;
  9060. } else {
  9061. GGML_ABORT("fatal error");
  9062. }
  9063. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  9064. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  9065. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9066. src0_ggml->data = x;
  9067. src1_ggml->data = y;
  9068. tensor_ggml->data = d_chk;
  9069. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9070. ggml_build_forward_expand(cgraph, tensor_ggml);
  9071. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9072. ggml_free(ggml_ctx);
  9073. double avg_err = 0.0;
  9074. int first_err_n = -1;
  9075. int first_err_m = -1;
  9076. int first_err_b = -1;
  9077. for (size_t i = 0; i < m*n*batch; i++) {
  9078. double err = std::fabs(d[i] - d_chk[i]);
  9079. avg_err += err;
  9080. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9081. first_err_b = i / (m * n);
  9082. first_err_n = (i % (m * n)) / m;
  9083. first_err_m = (i % (m * n)) % m;
  9084. }
  9085. }
  9086. avg_err /= m * n;
  9087. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9088. 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;
  9089. if (avg_err > 0.1 || std::isnan(avg_err)) {
  9090. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9091. std::cerr << "Actual result: " << std::endl << std::endl;
  9092. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9093. std::cerr << "Expected result: " << std::endl << std::endl;
  9094. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9095. if (split_k > 1) {
  9096. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9097. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9098. std::cerr << "d_buf0: " << std::endl << std::endl;
  9099. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9100. std::cerr << "d_buf1: " << std::endl << std::endl;
  9101. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9102. std::cerr << "d_buf2: " << std::endl << std::endl;
  9103. 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);
  9104. std::cerr << "d_buf3: " << std::endl << std::endl;
  9105. 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);
  9106. free(split_k_buf);
  9107. }
  9108. }
  9109. free(d_chk);
  9110. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  9111. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  9112. ggml_vk_destroy_buffer(d_X);
  9113. ggml_vk_destroy_buffer(d_Y);
  9114. ggml_vk_destroy_buffer(d_D);
  9115. free(x);
  9116. free(y);
  9117. free(d);
  9118. }
  9119. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  9120. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  9121. return;
  9122. }
  9123. i0 = std::max(i0, 5);
  9124. i1 = std::max(i1, 5);
  9125. i2 = std::max(i2, 0);
  9126. i3 = std::max(i3, 0);
  9127. fprintf(stderr, " ");
  9128. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9129. fprintf(stderr, "%7d ", idx1);
  9130. }
  9131. fprintf(stderr, "\n");
  9132. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9133. fprintf(stderr, "%7d: ", idx0);
  9134. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9135. 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]) {
  9136. float val;
  9137. if (tensor->type == GGML_TYPE_F32) {
  9138. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  9139. } else if (tensor->type == GGML_TYPE_F16) {
  9140. 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]));
  9141. } else {
  9142. GGML_ABORT("fatal error");
  9143. }
  9144. fprintf(stderr, "% 7.2f ", val);
  9145. } else {
  9146. fprintf(stderr, " ");
  9147. }
  9148. }
  9149. fprintf(stderr, "\n");
  9150. }
  9151. }
  9152. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  9153. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  9154. }
  9155. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  9156. if (quant == GGML_TYPE_F32) {
  9157. memcpy(to, from, sizeof(float) * ne);
  9158. return;
  9159. }
  9160. const auto * tt = ggml_get_type_traits(quant);
  9161. ggml_to_float_t dequant_fn = tt->to_float;
  9162. dequant_fn(from, to, ne);
  9163. }
  9164. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9165. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  9166. const size_t x_sz = sizeof(float) * ne;
  9167. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  9168. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9169. float * x = (float *) malloc(x_sz);
  9170. void * qx = malloc(qx_sz);
  9171. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9172. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9173. float * x_ref = (float *) malloc(x_sz);
  9174. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  9175. for (size_t i = 0; i < ne; i++) {
  9176. x[i] = rand() / (float)RAND_MAX;
  9177. }
  9178. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  9179. ggml_vk_quantize_data(x, qx, ne, quant);
  9180. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  9181. ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9182. ggml_pipeline_allocate_descriptor_sets(ctx);
  9183. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9184. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9185. ggml_vk_ctx_begin(ctx->device, subctx);
  9186. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  9187. 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});
  9188. ggml_vk_ctx_end(subctx);
  9189. auto begin = std::chrono::high_resolution_clock::now();
  9190. ggml_vk_submit(subctx, ctx->fence);
  9191. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9192. ctx->device->device.resetFences({ ctx->fence });
  9193. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9194. auto end = std::chrono::high_resolution_clock::now();
  9195. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9196. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  9197. int first_err = -1;
  9198. double avg_err = 0.0;
  9199. for (size_t i = 0; i < ne; i++) {
  9200. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  9201. avg_err += error;
  9202. if (first_err < 0 && error > 0.05) {
  9203. first_err = i;
  9204. }
  9205. }
  9206. avg_err /= ne;
  9207. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  9208. if (avg_err > 0.1) {
  9209. std::cerr << "first_error = " << first_err << std::endl;
  9210. std::cerr << "Actual result: " << std::endl << std::endl;
  9211. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9212. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  9213. }
  9214. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  9215. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9216. std::cerr << x_ref[i] << ", ";
  9217. }
  9218. std::cerr << std::endl;
  9219. }
  9220. ggml_vk_destroy_buffer(x_buf);
  9221. ggml_vk_destroy_buffer(qx_buf);
  9222. free(x);
  9223. free(qx);
  9224. free(x_ref);
  9225. free(x_chk);
  9226. }
  9227. // This does not work without ggml q8_1 quantization support
  9228. //
  9229. // typedef uint16_t ggml_half;
  9230. // typedef uint32_t ggml_half2;
  9231. //
  9232. // #define QK8_1 32
  9233. // typedef struct {
  9234. // union {
  9235. // struct {
  9236. // ggml_half d; // delta
  9237. // ggml_half s; // d * sum(qs[i])
  9238. // } GGML_COMMON_AGGR_S;
  9239. // ggml_half2 ds;
  9240. // } GGML_COMMON_AGGR_U;
  9241. // int8_t qs[QK8_1]; // quants
  9242. // } block_q8_1;
  9243. //
  9244. // static void ggml_vk_test_quantize(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9245. // VK_LOG_DEBUG("ggml_vk_test_quantize(" << ne << ")");
  9246. // GGML_ASSERT(quant == GGML_TYPE_Q8_1);
  9247. //
  9248. // const size_t x_sz = sizeof(float) * ne;
  9249. // const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9250. // float * x = (float *) malloc(x_sz);
  9251. // block_q8_1 * qx = (block_q8_1 *)malloc(qx_sz);
  9252. // block_q8_1 * qx_res = (block_q8_1 *)malloc(qx_sz);
  9253. // vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9254. // vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9255. //
  9256. // for (size_t i = 0; i < ne; i++) {
  9257. // x[i] = rand() / (float)RAND_MAX;
  9258. // }
  9259. //
  9260. // vk_pipeline p = ggml_vk_get_quantize_pipeline(ctx, quant);
  9261. //
  9262. // ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9263. //
  9264. // ggml_pipeline_allocate_descriptor_sets(ctx);
  9265. //
  9266. // ggml_vk_buffer_write(x_buf, 0, x, x_sz);
  9267. //
  9268. // vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9269. // ggml_vk_ctx_begin(ctx->device, subctx);
  9270. // ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, x_buf), ggml_vk_subbuffer(ctx, qx_buf), ne);
  9271. // ggml_vk_ctx_end(subctx);
  9272. //
  9273. // auto begin = std::chrono::high_resolution_clock::now();
  9274. //
  9275. // ggml_vk_submit(subctx, ctx->fence);
  9276. // VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_quantize waitForFences");
  9277. // ctx->device->device.resetFences({ ctx->fence });
  9278. // ggml_vk_queue_command_pools_cleanup(ctx->device);
  9279. //
  9280. // auto end = std::chrono::high_resolution_clock::now();
  9281. //
  9282. // double ms_quant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9283. // ggml_vk_buffer_read(qx_buf, 0, qx, qx_sz);
  9284. //
  9285. // ggml_vk_quantize_data(x, qx_res, ne, quant);
  9286. //
  9287. // int first_err = -1;
  9288. //
  9289. // for (size_t i = 0; i < ne / 32; i++) {
  9290. // 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));
  9291. //
  9292. // if (first_err < 0 && error > 0.1) {
  9293. // first_err = i;
  9294. // }
  9295. //
  9296. // 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));
  9297. //
  9298. // if (first_err < 0 && error > 0.1) {
  9299. // first_err = i;
  9300. // }
  9301. //
  9302. // for (size_t j = 0; j < 32; j++) {
  9303. // uint64_t error = std::abs(qx_res[i].qs[j] - qx[i].qs[j]);
  9304. //
  9305. // if (first_err < 0 && error > 1) {
  9306. // first_err = i;
  9307. // }
  9308. // }
  9309. // }
  9310. //
  9311. // std::cerr << "TEST QUANTIZE " << ggml_type_name(quant) << " time=" << ms_quant << "ms " << (first_err == -1 ? "CORRECT" : "INCORRECT") << std::endl;
  9312. //
  9313. // if (first_err != -1) {
  9314. // std::cerr << "first_error = " << first_err << std::endl;
  9315. // std::cerr << "Actual result: " << std::endl << std::endl;
  9316. // 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) << " ";
  9317. // for (size_t j = 0; j < 32; j++) {
  9318. // std::cout << " qs" << j << "=" << (uint32_t)qx[first_err].qs[j] << " ";
  9319. // }
  9320. // std::cerr << std::endl << std::endl << "Expected result: " << std::endl << std::endl;
  9321. // 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) << " ";
  9322. // for (size_t j = 0; j < 32; j++) {
  9323. // std::cout << " qs" << j << "=" << (uint32_t)qx_res[first_err].qs[j] << " ";
  9324. // }
  9325. // std::cerr << std::endl;
  9326. // }
  9327. //
  9328. // ggml_vk_destroy_buffer(x_buf);
  9329. // ggml_vk_destroy_buffer(qx_buf);
  9330. //
  9331. // free(x);
  9332. // free(qx);
  9333. // free(qx_res);
  9334. // }
  9335. 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) {
  9336. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  9337. const size_t x_ne = m * k * batch;
  9338. const size_t y_ne = k * n * batch;
  9339. const size_t d_ne = m * n * batch;
  9340. vk_matmul_pipeline2 * pipelines;
  9341. if (mmq) {
  9342. pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1;
  9343. } else {
  9344. pipelines = ctx->device->pipeline_dequant_mul_mat_mat;
  9345. }
  9346. const bool fp16acc = ctx->device->fp16;
  9347. vk_pipeline p;
  9348. std::string shname;
  9349. if (shader_size == 0) {
  9350. p = fp16acc ? pipelines[quant].f16acc->a_s : pipelines[quant].f32acc->a_s;
  9351. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  9352. } else if (shader_size == 1) {
  9353. p = fp16acc ? pipelines[quant].f16acc->a_m : pipelines[quant].f32acc->a_m;
  9354. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  9355. } else if (shader_size == 2) {
  9356. p = fp16acc ? pipelines[quant].f16acc->a_l : pipelines[quant].f32acc->a_l;
  9357. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  9358. } else {
  9359. GGML_ASSERT(0);
  9360. }
  9361. const size_t kpad = mmq ? 0 : ggml_vk_align_size(k, p->align);
  9362. if (mmq || k != kpad) {
  9363. if (shader_size == 0) {
  9364. p = fp16acc ? pipelines[quant].f16acc->s : pipelines[quant].f32acc->s;
  9365. shname = std::string(ggml_type_name(quant)) + "_S";
  9366. } else if (shader_size == 1) {
  9367. p = fp16acc ? pipelines[quant].f16acc->m : pipelines[quant].f32acc->m;
  9368. shname = std::string(ggml_type_name(quant)) + "_M";
  9369. } else if (shader_size == 2) {
  9370. p = fp16acc ? pipelines[quant].f16acc->l : pipelines[quant].f32acc->l;
  9371. shname = std::string(ggml_type_name(quant)) + "_L";
  9372. } else {
  9373. GGML_ASSERT(0);
  9374. }
  9375. }
  9376. if (p == nullptr) {
  9377. std::cerr << "error: no pipeline for ggml_vk_test_dequant_matmul " << ggml_type_name(quant) << std::endl;
  9378. return;
  9379. }
  9380. const size_t x_sz = sizeof(float) * x_ne;
  9381. const size_t y_sz = sizeof(float) * y_ne;
  9382. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9383. const size_t qy_sz = mmq ? y_ne * ggml_type_size(GGML_TYPE_Q8_1)/ggml_blck_size(GGML_TYPE_Q8_1) : y_sz;
  9384. const size_t d_sz = sizeof(float) * d_ne;
  9385. float * x = (float *) malloc(x_sz);
  9386. float * y = (float *) malloc(y_sz);
  9387. void * qx = malloc(qx_sz);
  9388. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9389. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9390. vk_buffer qy_buf = ggml_vk_create_buffer_check(ctx->device, qy_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9391. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9392. float * d = (float *) malloc(d_sz);
  9393. float * d_chk = (float *) malloc(d_sz);
  9394. for (size_t i = 0; i < x_ne; i++) {
  9395. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9396. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9397. // x[i] = i % k;
  9398. }
  9399. ggml_vk_quantize_data(x, qx, x_ne, quant);
  9400. for (size_t i = 0; i < y_ne; i++) {
  9401. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9402. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9403. // y[i] = i % k;
  9404. }
  9405. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9406. if (split_k > 1) {
  9407. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9408. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9409. // Resize buffer
  9410. if (ctx->prealloc_split_k != nullptr) {
  9411. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9412. }
  9413. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9414. }
  9415. }
  9416. if (mmq) {
  9417. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_quantize_q8_1, num_it);
  9418. }
  9419. ggml_pipeline_allocate_descriptor_sets(ctx);
  9420. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9421. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  9422. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9423. ggml_vk_ctx_begin(ctx->device, subctx);
  9424. if (mmq) {
  9425. for (size_t i = 0; i < num_it; i++) {
  9426. ggml_vk_quantize_q8_1(ctx, subctx, { y_buf, 0, y_sz }, { qy_buf, 0, qy_sz }, y_ne);
  9427. ggml_vk_matmul(
  9428. 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 },
  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. } else {
  9435. for (size_t i = 0; i < num_it; i++) {
  9436. ggml_vk_matmul(
  9437. 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 },
  9438. m, n, k,
  9439. k, k, m, k*m, k*n, m*n,
  9440. split_k, batch, batch, batch, 1, 1, n
  9441. );
  9442. }
  9443. }
  9444. ggml_vk_ctx_end(subctx);
  9445. auto begin = std::chrono::high_resolution_clock::now();
  9446. ggml_vk_submit(subctx, ctx->fence);
  9447. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9448. ctx->device->device.resetFences({ ctx->fence });
  9449. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9450. auto end = std::chrono::high_resolution_clock::now();
  9451. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9452. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  9453. ggml_init_params iparams = {
  9454. /*.mem_size =*/ 1024*1024*1024,
  9455. /*.mem_buffer =*/ NULL,
  9456. /*.no_alloc =*/ true,
  9457. };
  9458. ggml_context * ggml_ctx = ggml_init(iparams);
  9459. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  9460. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  9461. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9462. src0_ggml->data = qx;
  9463. src1_ggml->data = y;
  9464. tensor_ggml->data = d_chk;
  9465. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9466. ggml_build_forward_expand(cgraph, tensor_ggml);
  9467. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9468. ggml_free(ggml_ctx);
  9469. double avg_err = 0.0;
  9470. int first_err_n = -1;
  9471. int first_err_m = -1;
  9472. int first_err_b = -1;
  9473. for (size_t i = 0; i < m*n*batch; i++) {
  9474. double err = std::fabs(d[i] - d_chk[i]);
  9475. avg_err += err;
  9476. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9477. first_err_b = i / (m * n);
  9478. first_err_n = (i % (m * n)) / m;
  9479. first_err_m = (i % (m * n)) % m;
  9480. }
  9481. }
  9482. avg_err /= m * n;
  9483. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9484. std::cerr << "TEST dequant matmul " << shname;
  9485. if (mmq) {
  9486. std::cerr << " mmq";
  9487. }
  9488. 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;
  9489. if (avg_err > 0.01 || std::isnan(avg_err)) {
  9490. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9491. std::cerr << "Actual result: " << std::endl << std::endl;
  9492. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9493. std::cerr << std::endl;
  9494. std::cerr << "Expected result: " << std::endl << std::endl;
  9495. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9496. std::cerr << "src0: " << std::endl << std::endl;
  9497. ggml_vk_print_matrix_area(x, GGML_TYPE_F32, k, m, first_err_m, first_err_n, first_err_b);
  9498. std::cerr << std::endl;
  9499. std::cerr << "src1: " << std::endl << std::endl;
  9500. ggml_vk_print_matrix_area(y, GGML_TYPE_F32, k, n, first_err_m, first_err_n, first_err_b);
  9501. if (split_k > 1) {
  9502. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9503. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9504. std::cerr << "d_buf0: " << std::endl << std::endl;
  9505. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9506. std::cerr << "d_buf1: " << std::endl << std::endl;
  9507. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9508. std::cerr << "d_buf2: " << std::endl << std::endl;
  9509. 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);
  9510. std::cerr << "d_buf3: " << std::endl << std::endl;
  9511. 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);
  9512. free(split_k_buf);
  9513. }
  9514. }
  9515. ggml_vk_destroy_buffer(qx_buf);
  9516. ggml_vk_destroy_buffer(y_buf);
  9517. ggml_vk_destroy_buffer(qy_buf);
  9518. ggml_vk_destroy_buffer(d_buf);
  9519. free(x);
  9520. free(qx);
  9521. free(y);
  9522. free(d);
  9523. free(d_chk);
  9524. }
  9525. #endif
  9526. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx) {
  9527. #if defined(GGML_VULKAN_RUN_TESTS)
  9528. const std::vector<size_t> vals {
  9529. 512, 512, 128,
  9530. 128, 512, 512,
  9531. 4096, 512, 4096,
  9532. 11008, 512, 4096,
  9533. 4096, 512, 11008,
  9534. 32000, 512, 4096,
  9535. 8, 8, 8,
  9536. 100, 46, 576,
  9537. 623, 111, 128,
  9538. 100, 46, 558,
  9539. 512, 1, 256,
  9540. 128, 110, 622,
  9541. 511, 511, 127,
  9542. 511, 511, 7,
  9543. 511, 511, 17,
  9544. 49, 49, 128,
  9545. 128, 49, 49,
  9546. 4096, 49, 4096,
  9547. };
  9548. const size_t num_it = 100;
  9549. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9550. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9551. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9552. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true);
  9553. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true);
  9554. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true);
  9555. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0);
  9556. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0);
  9557. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0);
  9558. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true);
  9559. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true);
  9560. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true);
  9561. abort();
  9562. for (size_t i = 0; i < vals.size(); i += 3) {
  9563. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  9564. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  9565. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  9566. std::cerr << '\n';
  9567. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  9568. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  9569. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  9570. std::cerr << '\n';
  9571. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  9572. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  9573. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  9574. std::cerr << '\n' << std::endl;
  9575. if (vals[i + 2] % 32 == 0) {
  9576. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9577. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9578. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9579. std::cerr << '\n';
  9580. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  9581. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  9582. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  9583. std::cerr << '\n';
  9584. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  9585. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  9586. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  9587. std::cerr << '\n' << std::endl;
  9588. }
  9589. if (vals[i + 2] % 256 == 0) {
  9590. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  9591. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  9592. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  9593. std::cerr << '\n';
  9594. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  9595. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  9596. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  9597. std::cerr << '\n';
  9598. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  9599. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  9600. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  9601. std::cerr << '\n' << std::endl;
  9602. }
  9603. }
  9604. GGML_ABORT("fatal error");
  9605. #endif
  9606. if (subctx) {
  9607. // Submit and wait for any pending work before reallocating the buffers
  9608. ggml_vk_ctx_end(subctx);
  9609. ggml_vk_submit(subctx, ctx->fence);
  9610. ggml_vk_wait_for_fence(ctx);
  9611. ggml_vk_ctx_begin(ctx->device, subctx);
  9612. }
  9613. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  9614. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  9615. // Resize buffer
  9616. if (ctx->prealloc_x != nullptr) {
  9617. ggml_vk_destroy_buffer(ctx->prealloc_x);
  9618. }
  9619. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  9620. }
  9621. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  9622. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  9623. // Resize buffer
  9624. if (ctx->prealloc_y != nullptr) {
  9625. ggml_vk_destroy_buffer(ctx->prealloc_y);
  9626. }
  9627. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  9628. }
  9629. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  9630. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  9631. // Resize buffer
  9632. if (ctx->prealloc_split_k != nullptr) {
  9633. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9634. }
  9635. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  9636. }
  9637. 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)) {
  9638. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")");
  9639. // Resize buffer
  9640. if (ctx->prealloc_add_rms_partials != nullptr) {
  9641. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  9642. }
  9643. ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials);
  9644. }
  9645. }
  9646. static bool ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_cgraph * cgraph, ggml_tensor* tensor, int tensor_idx, bool use_fence, bool almost_ready);
  9647. // Returns true if node has enqueued work into the queue, false otherwise
  9648. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  9649. 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){
  9650. ggml_tensor * node = cgraph->nodes[node_idx];
  9651. if (ggml_is_empty(node) || !node->buffer) {
  9652. return false;
  9653. }
  9654. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  9655. ctx->semaphore_idx = 0;
  9656. ggml_tensor * src0 = node->src[0];
  9657. ggml_tensor * src1 = node->src[1];
  9658. ggml_tensor * src2 = node->src[2];
  9659. ggml_tensor * src3 = node->src[3];
  9660. switch (node->op) {
  9661. // Return on empty ops to avoid generating a compute_ctx and setting exit_tensor
  9662. case GGML_OP_RESHAPE:
  9663. case GGML_OP_VIEW:
  9664. case GGML_OP_PERMUTE:
  9665. case GGML_OP_TRANSPOSE:
  9666. case GGML_OP_NONE:
  9667. return false;
  9668. case GGML_OP_UNARY:
  9669. switch (ggml_get_unary_op(node)) {
  9670. case GGML_UNARY_OP_EXP:
  9671. case GGML_UNARY_OP_SILU:
  9672. case GGML_UNARY_OP_GELU:
  9673. case GGML_UNARY_OP_GELU_ERF:
  9674. case GGML_UNARY_OP_GELU_QUICK:
  9675. case GGML_UNARY_OP_RELU:
  9676. case GGML_UNARY_OP_TANH:
  9677. case GGML_UNARY_OP_SIGMOID:
  9678. case GGML_UNARY_OP_HARDSIGMOID:
  9679. case GGML_UNARY_OP_HARDSWISH:
  9680. break;
  9681. default:
  9682. return false;
  9683. }
  9684. break;
  9685. case GGML_OP_GLU:
  9686. switch (ggml_get_glu_op(node)) {
  9687. case GGML_GLU_OP_GEGLU:
  9688. case GGML_GLU_OP_REGLU:
  9689. case GGML_GLU_OP_SWIGLU:
  9690. case GGML_GLU_OP_SWIGLU_OAI:
  9691. case GGML_GLU_OP_GEGLU_ERF:
  9692. case GGML_GLU_OP_GEGLU_QUICK:
  9693. break;
  9694. default:
  9695. return false;
  9696. }
  9697. break;
  9698. case GGML_OP_ADD:
  9699. {
  9700. int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops;
  9701. if (next_node_idx < cgraph->n_nodes &&
  9702. cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM &&
  9703. cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] &&
  9704. ggml_nrows(cgraph->nodes[next_node_idx]) == 1 &&
  9705. ctx->device->add_rms_fusion) {
  9706. uint32_t size = ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]);
  9707. ctx->do_add_rms_partials_offset_calculation = true;
  9708. if (ctx->prealloc_size_add_rms_partials_offset + size <= ctx->prealloc_size_add_rms_partials) {
  9709. ctx->do_add_rms_partials = true;
  9710. }
  9711. }
  9712. } break;
  9713. case GGML_OP_REPEAT:
  9714. case GGML_OP_REPEAT_BACK:
  9715. case GGML_OP_GET_ROWS:
  9716. case GGML_OP_ADD_ID:
  9717. case GGML_OP_ACC:
  9718. case GGML_OP_SUB:
  9719. case GGML_OP_MUL:
  9720. case GGML_OP_DIV:
  9721. case GGML_OP_CONCAT:
  9722. case GGML_OP_UPSCALE:
  9723. case GGML_OP_SCALE:
  9724. case GGML_OP_SQR:
  9725. case GGML_OP_SQRT:
  9726. case GGML_OP_SIN:
  9727. case GGML_OP_COS:
  9728. case GGML_OP_CLAMP:
  9729. case GGML_OP_PAD:
  9730. case GGML_OP_ROLL:
  9731. case GGML_OP_CPY:
  9732. case GGML_OP_SET_ROWS:
  9733. case GGML_OP_CONT:
  9734. case GGML_OP_DUP:
  9735. case GGML_OP_SILU_BACK:
  9736. case GGML_OP_NORM:
  9737. case GGML_OP_GROUP_NORM:
  9738. case GGML_OP_RMS_NORM:
  9739. case GGML_OP_RMS_NORM_BACK:
  9740. case GGML_OP_L2_NORM:
  9741. case GGML_OP_DIAG_MASK_INF:
  9742. case GGML_OP_SOFT_MAX:
  9743. case GGML_OP_SOFT_MAX_BACK:
  9744. case GGML_OP_ROPE:
  9745. case GGML_OP_ROPE_BACK:
  9746. case GGML_OP_MUL_MAT:
  9747. case GGML_OP_MUL_MAT_ID:
  9748. case GGML_OP_ARGSORT:
  9749. case GGML_OP_SUM:
  9750. case GGML_OP_SUM_ROWS:
  9751. case GGML_OP_MEAN:
  9752. case GGML_OP_ARGMAX:
  9753. case GGML_OP_COUNT_EQUAL:
  9754. case GGML_OP_IM2COL:
  9755. case GGML_OP_IM2COL_3D:
  9756. case GGML_OP_TIMESTEP_EMBEDDING:
  9757. case GGML_OP_CONV_TRANSPOSE_1D:
  9758. case GGML_OP_POOL_2D:
  9759. case GGML_OP_CONV_2D:
  9760. case GGML_OP_CONV_TRANSPOSE_2D:
  9761. case GGML_OP_CONV_2D_DW:
  9762. case GGML_OP_RWKV_WKV6:
  9763. case GGML_OP_RWKV_WKV7:
  9764. case GGML_OP_SSM_SCAN:
  9765. case GGML_OP_SSM_CONV:
  9766. case GGML_OP_LEAKY_RELU:
  9767. case GGML_OP_FLASH_ATTN_EXT:
  9768. case GGML_OP_OPT_STEP_ADAMW:
  9769. case GGML_OP_OPT_STEP_SGD:
  9770. break;
  9771. default:
  9772. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(node->op) << std::endl;
  9773. GGML_ABORT("fatal error");
  9774. }
  9775. vk_context compute_ctx;
  9776. if (ctx->compute_ctx.expired()) {
  9777. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9778. ctx->compute_ctx = compute_ctx;
  9779. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  9780. } else {
  9781. compute_ctx = ctx->compute_ctx.lock();
  9782. }
  9783. {
  9784. // This logic detects dependencies between modes in the graph and calls ggml_vk_sync_buffers
  9785. // to synchronize them. This handles most "normal" synchronization when computing the graph, and when
  9786. // there is no auxiliary memory use, it shouldn't be necessary to call ggml_vk_sync_buffers
  9787. // outside of this logic. When a node uses one of the prealloc buffers for something like
  9788. // dequantization or split_k, additional synchronization is needed between those passes.
  9789. bool need_sync = false;
  9790. // Check whether "node" requires synchronization. The node requires synchronization if it
  9791. // overlaps in memory with another unsynchronized node and at least one of them is a write.
  9792. // Destination nodes are checked against both the written/read lists. Source nodes are only
  9793. // checked against the written list. Two nodes overlap in memory if they come from the same
  9794. // buffer and the tensor or view ranges overlap.
  9795. auto const &overlaps_unsynced = [&](const ggml_tensor *node, const std::vector<const ggml_tensor *> &unsynced_nodes) -> bool {
  9796. if (unsynced_nodes.size() == 0) {
  9797. return false;
  9798. }
  9799. auto n_base = vk_tensor_offset(node) + node->view_offs;
  9800. auto n_size = ggml_nbytes(node);
  9801. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context;
  9802. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  9803. for (auto &other : unsynced_nodes) {
  9804. ggml_backend_vk_buffer_context * o_buf_ctx = (ggml_backend_vk_buffer_context *)other->buffer->context;
  9805. vk_buffer o_buf = o_buf_ctx->dev_buffer;
  9806. if (a_buf == o_buf) {
  9807. auto o_base = vk_tensor_offset(other) + other->view_offs;
  9808. auto o_size = ggml_nbytes(other);
  9809. if ((o_base <= n_base && n_base < o_base + o_size) ||
  9810. (n_base <= o_base && o_base < n_base + n_size)) {
  9811. return true;
  9812. }
  9813. }
  9814. }
  9815. return false;
  9816. };
  9817. // For all fused ops, check if the destination node or any of the source
  9818. // nodes require synchronization.
  9819. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) {
  9820. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  9821. // If the node actually writes to memory, then check if it needs to sync
  9822. if (ctx->fused_ops_write_mask & (1 << i)) {
  9823. if (overlaps_unsynced(cur_node, ctx->unsynced_nodes_read) || overlaps_unsynced(cur_node, ctx->unsynced_nodes_written)) {
  9824. need_sync = true;
  9825. break;
  9826. }
  9827. }
  9828. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  9829. if (!cur_node->src[j]) {
  9830. continue;
  9831. }
  9832. if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) {
  9833. need_sync = true;
  9834. break;
  9835. }
  9836. }
  9837. }
  9838. #define ENABLE_SYNC_LOGGING 0
  9839. if (need_sync) {
  9840. #if ENABLE_SYNC_LOGGING
  9841. std::cerr << "sync" << std::endl;
  9842. #endif
  9843. ctx->unsynced_nodes_written.clear();
  9844. ctx->unsynced_nodes_read.clear();
  9845. ggml_vk_sync_buffers(ctx, compute_ctx);
  9846. }
  9847. // Add all fused nodes to the unsynchronized lists.
  9848. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  9849. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  9850. // Multiple outputs could be written, e.g. in topk_moe. Add them all to the list.
  9851. if (ctx->fused_ops_write_mask & (1 << i)) {
  9852. ctx->unsynced_nodes_written.push_back(cur_node);
  9853. }
  9854. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  9855. if (!cur_node->src[j]) {
  9856. continue;
  9857. }
  9858. ctx->unsynced_nodes_read.push_back(cur_node->src[j]);
  9859. }
  9860. }
  9861. }
  9862. #if ENABLE_SYNC_LOGGING
  9863. for (int i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  9864. auto *n = cgraph->nodes[node_idx + i];
  9865. std::cerr << node_idx + i << " " << ggml_op_name(n->op) << " " << n->name;
  9866. if (n->op == GGML_OP_GLU) {
  9867. std::cerr << " " << ggml_glu_op_name(ggml_get_glu_op(n)) << " " << (n->src[1] ? "split" : "single") << " ";
  9868. }
  9869. if (n->op == GGML_OP_ROPE) {
  9870. const int mode = ((const int32_t *) n->op_params)[2];
  9871. std::cerr << " rope mode: " << mode;
  9872. }
  9873. std::cerr << std::endl;
  9874. }
  9875. #endif
  9876. switch (node->op) {
  9877. case GGML_OP_REPEAT:
  9878. ggml_vk_repeat(ctx, compute_ctx, src0, node);
  9879. break;
  9880. case GGML_OP_REPEAT_BACK:
  9881. ggml_vk_repeat_back(ctx, compute_ctx, src0, node);
  9882. break;
  9883. case GGML_OP_ACC:
  9884. ggml_vk_acc(ctx, compute_ctx, src0, src1, node);
  9885. break;
  9886. case GGML_OP_GET_ROWS:
  9887. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node);
  9888. break;
  9889. case GGML_OP_ADD:
  9890. if (ctx->num_additional_fused_ops) {
  9891. ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx);
  9892. } else {
  9893. ggml_vk_add(ctx, compute_ctx, src0, src1, node);
  9894. }
  9895. break;
  9896. case GGML_OP_SUB:
  9897. ggml_vk_sub(ctx, compute_ctx, src0, src1, node);
  9898. break;
  9899. case GGML_OP_MUL:
  9900. ggml_vk_mul(ctx, compute_ctx, src0, src1, node);
  9901. break;
  9902. case GGML_OP_DIV:
  9903. ggml_vk_div(ctx, compute_ctx, src0, src1, node);
  9904. break;
  9905. case GGML_OP_ADD_ID:
  9906. ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node);
  9907. break;
  9908. case GGML_OP_CONCAT:
  9909. ggml_vk_concat(ctx, compute_ctx, src0, src1, node);
  9910. break;
  9911. case GGML_OP_UPSCALE:
  9912. ggml_vk_upscale(ctx, compute_ctx, src0, node);
  9913. break;
  9914. case GGML_OP_SCALE:
  9915. ggml_vk_scale(ctx, compute_ctx, src0, node);
  9916. break;
  9917. case GGML_OP_SQR:
  9918. ggml_vk_sqr(ctx, compute_ctx, src0, node);
  9919. break;
  9920. case GGML_OP_SQRT:
  9921. ggml_vk_sqrt(ctx, compute_ctx, src0, node);
  9922. break;
  9923. case GGML_OP_SIN:
  9924. ggml_vk_sin(ctx, compute_ctx, src0, node);
  9925. break;
  9926. case GGML_OP_COS:
  9927. ggml_vk_cos(ctx, compute_ctx, src0, node);
  9928. break;
  9929. case GGML_OP_CLAMP:
  9930. ggml_vk_clamp(ctx, compute_ctx, src0, node);
  9931. break;
  9932. case GGML_OP_PAD:
  9933. ggml_vk_pad(ctx, compute_ctx, src0, node);
  9934. break;
  9935. case GGML_OP_ROLL:
  9936. ggml_vk_roll(ctx, compute_ctx, src0, node);
  9937. break;
  9938. case GGML_OP_CPY:
  9939. case GGML_OP_CONT:
  9940. case GGML_OP_DUP:
  9941. ggml_vk_cpy(ctx, compute_ctx, src0, node);
  9942. break;
  9943. case GGML_OP_SET_ROWS:
  9944. ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node);
  9945. break;
  9946. case GGML_OP_SILU_BACK:
  9947. ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node);
  9948. break;
  9949. case GGML_OP_NORM:
  9950. ggml_vk_norm(ctx, compute_ctx, src0, node);
  9951. break;
  9952. case GGML_OP_GROUP_NORM:
  9953. ggml_vk_group_norm(ctx, compute_ctx, src0, node);
  9954. break;
  9955. case GGML_OP_RMS_NORM:
  9956. ggml_vk_rms_norm(ctx, compute_ctx, cgraph, node_idx, (float *)node->op_params);
  9957. break;
  9958. case GGML_OP_RMS_NORM_BACK:
  9959. ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node);
  9960. break;
  9961. case GGML_OP_L2_NORM:
  9962. ggml_vk_l2_norm(ctx, compute_ctx, src0, node);
  9963. break;
  9964. case GGML_OP_UNARY:
  9965. switch (ggml_get_unary_op(node)) {
  9966. case GGML_UNARY_OP_EXP:
  9967. case GGML_UNARY_OP_SILU:
  9968. case GGML_UNARY_OP_GELU:
  9969. case GGML_UNARY_OP_GELU_ERF:
  9970. case GGML_UNARY_OP_GELU_QUICK:
  9971. case GGML_UNARY_OP_RELU:
  9972. case GGML_UNARY_OP_TANH:
  9973. case GGML_UNARY_OP_SIGMOID:
  9974. case GGML_UNARY_OP_HARDSIGMOID:
  9975. case GGML_UNARY_OP_HARDSWISH:
  9976. ggml_vk_unary(ctx, compute_ctx, src0, node);
  9977. break;
  9978. default:
  9979. return false;
  9980. }
  9981. break;
  9982. case GGML_OP_GLU:
  9983. switch (ggml_get_glu_op(node)) {
  9984. case GGML_GLU_OP_GEGLU:
  9985. case GGML_GLU_OP_REGLU:
  9986. case GGML_GLU_OP_SWIGLU:
  9987. case GGML_GLU_OP_SWIGLU_OAI:
  9988. case GGML_GLU_OP_GEGLU_ERF:
  9989. case GGML_GLU_OP_GEGLU_QUICK:
  9990. ggml_vk_glu(ctx, compute_ctx, src0, src1, node);
  9991. break;
  9992. default:
  9993. return false;
  9994. }
  9995. break;
  9996. case GGML_OP_DIAG_MASK_INF:
  9997. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node);
  9998. break;
  9999. case GGML_OP_SOFT_MAX:
  10000. if (ctx->num_additional_fused_ops) {
  10001. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10002. } else {
  10003. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node);
  10004. }
  10005. break;
  10006. case GGML_OP_SOFT_MAX_BACK:
  10007. ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node);
  10008. break;
  10009. case GGML_OP_ROPE:
  10010. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, false);
  10011. break;
  10012. case GGML_OP_ROPE_BACK:
  10013. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, true);
  10014. break;
  10015. case GGML_OP_ARGSORT:
  10016. if (ctx->num_additional_fused_ops) {
  10017. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10018. } else {
  10019. ggml_vk_argsort(ctx, compute_ctx, src0, node);
  10020. }
  10021. break;
  10022. case GGML_OP_SUM:
  10023. ggml_vk_sum(ctx, compute_ctx, src0, node);
  10024. break;
  10025. case GGML_OP_SUM_ROWS:
  10026. ggml_vk_sum_rows(ctx, compute_ctx, src0, node);
  10027. break;
  10028. case GGML_OP_MEAN:
  10029. ggml_vk_mean(ctx, compute_ctx, src0, node);
  10030. break;
  10031. case GGML_OP_ARGMAX:
  10032. ggml_vk_argmax(ctx, compute_ctx, src0, node);
  10033. break;
  10034. case GGML_OP_COUNT_EQUAL:
  10035. ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node);
  10036. break;
  10037. case GGML_OP_IM2COL:
  10038. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node);
  10039. break;
  10040. case GGML_OP_IM2COL_3D:
  10041. ggml_vk_im2col_3d(ctx, compute_ctx, src0, src1, node);
  10042. break;
  10043. case GGML_OP_TIMESTEP_EMBEDDING:
  10044. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node);
  10045. break;
  10046. case GGML_OP_CONV_TRANSPOSE_1D:
  10047. ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node);
  10048. break;
  10049. case GGML_OP_POOL_2D:
  10050. ggml_vk_pool_2d(ctx, compute_ctx, src0, node);
  10051. break;
  10052. case GGML_OP_CONV_2D:
  10053. ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node);
  10054. break;
  10055. case GGML_OP_CONV_TRANSPOSE_2D:
  10056. ggml_vk_conv_transpose_2d(ctx, compute_ctx, src0, src1, node);
  10057. break;
  10058. case GGML_OP_CONV_2D_DW:
  10059. ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node);
  10060. break;
  10061. case GGML_OP_LEAKY_RELU:
  10062. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node);
  10063. break;
  10064. case GGML_OP_MUL_MAT:
  10065. ggml_vk_mul_mat(ctx, compute_ctx, cgraph, node_idx);
  10066. break;
  10067. case GGML_OP_MUL_MAT_ID:
  10068. ggml_vk_mul_mat_id(ctx, compute_ctx, cgraph, node_idx);
  10069. break;
  10070. case GGML_OP_FLASH_ATTN_EXT:
  10071. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node);
  10072. break;
  10073. case GGML_OP_RWKV_WKV6:
  10074. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node);
  10075. break;
  10076. case GGML_OP_RWKV_WKV7:
  10077. ggml_vk_rwkv_wkv7(ctx, compute_ctx, node);
  10078. break;
  10079. case GGML_OP_SSM_SCAN:
  10080. ggml_vk_ssm_scan(ctx, compute_ctx, node);
  10081. break;
  10082. case GGML_OP_SSM_CONV:
  10083. ggml_vk_ssm_conv(ctx, compute_ctx, node);
  10084. break;
  10085. case GGML_OP_OPT_STEP_ADAMW:
  10086. ggml_vk_opt_step_adamw(ctx, compute_ctx, node);
  10087. break;
  10088. case GGML_OP_OPT_STEP_SGD:
  10089. ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node);
  10090. break;
  10091. default:
  10092. return false;
  10093. }
  10094. ctx->tensor_ctxs[node_idx] = compute_ctx;
  10095. #if defined(GGML_VULKAN_CHECK_RESULTS)
  10096. // Force context reset on each node so that each tensor ends up in its own context
  10097. // and can be run and compared to its CPU equivalent separately
  10098. last_node = true;
  10099. #endif
  10100. if (submit || last_node) {
  10101. ggml_vk_ctx_end(compute_ctx);
  10102. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  10103. if (last_node) {
  10104. compute_ctx->exit_tensor_idx = node_idx_begin;
  10105. }
  10106. else {
  10107. compute_ctx->exit_tensor_idx = -1;
  10108. }
  10109. ctx->compute_ctx.reset();
  10110. bool ok = ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, false, almost_ready);
  10111. if (!ok) {
  10112. if (node->op == GGML_OP_UNARY) {
  10113. std::cerr << __func__ << ": error: op not supported UNARY " << node->name << " (" << ggml_unary_op_name(static_cast<ggml_unary_op>(node->op_params[0])) << ")" << std::endl;
  10114. } else if (node->op == GGML_OP_GLU) {
  10115. std::cerr << __func__ << ": error: op not supported GLU " << node->name << " (" << ggml_glu_op_name(static_cast<ggml_glu_op>(node->op_params[0])) << ")" << std::endl;
  10116. } else {
  10117. std::cerr << __func__ << ": error: op not supported " << node->name << " (" << ggml_op_name(node->op) << ")" << std::endl;
  10118. }
  10119. }
  10120. }
  10121. return true;
  10122. }
  10123. static bool ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, ggml_tensor * tensor, int tensor_idx, bool use_fence = true, bool almost_ready = false) {
  10124. GGML_UNUSED(cgraph);
  10125. ggml_backend_buffer * buf = nullptr;
  10126. switch (tensor->op) {
  10127. case GGML_OP_ADD:
  10128. case GGML_OP_ACC:
  10129. case GGML_OP_GET_ROWS:
  10130. case GGML_OP_SUB:
  10131. case GGML_OP_MUL:
  10132. case GGML_OP_DIV:
  10133. case GGML_OP_ADD_ID:
  10134. case GGML_OP_CONCAT:
  10135. case GGML_OP_UPSCALE:
  10136. case GGML_OP_SCALE:
  10137. case GGML_OP_SQR:
  10138. case GGML_OP_SQRT:
  10139. case GGML_OP_SIN:
  10140. case GGML_OP_COS:
  10141. case GGML_OP_CLAMP:
  10142. case GGML_OP_PAD:
  10143. case GGML_OP_ROLL:
  10144. case GGML_OP_CPY:
  10145. case GGML_OP_SET_ROWS:
  10146. case GGML_OP_CONT:
  10147. case GGML_OP_DUP:
  10148. case GGML_OP_SILU_BACK:
  10149. case GGML_OP_NORM:
  10150. case GGML_OP_GROUP_NORM:
  10151. case GGML_OP_RMS_NORM:
  10152. case GGML_OP_RMS_NORM_BACK:
  10153. case GGML_OP_L2_NORM:
  10154. case GGML_OP_DIAG_MASK_INF:
  10155. case GGML_OP_SOFT_MAX:
  10156. case GGML_OP_SOFT_MAX_BACK:
  10157. case GGML_OP_ROPE:
  10158. case GGML_OP_ROPE_BACK:
  10159. case GGML_OP_RESHAPE:
  10160. case GGML_OP_VIEW:
  10161. case GGML_OP_PERMUTE:
  10162. case GGML_OP_TRANSPOSE:
  10163. case GGML_OP_NONE:
  10164. case GGML_OP_ARGSORT:
  10165. case GGML_OP_SUM:
  10166. case GGML_OP_SUM_ROWS:
  10167. case GGML_OP_MEAN:
  10168. case GGML_OP_ARGMAX:
  10169. case GGML_OP_COUNT_EQUAL:
  10170. case GGML_OP_IM2COL:
  10171. case GGML_OP_IM2COL_3D:
  10172. case GGML_OP_TIMESTEP_EMBEDDING:
  10173. case GGML_OP_CONV_TRANSPOSE_1D:
  10174. case GGML_OP_POOL_2D:
  10175. case GGML_OP_CONV_2D:
  10176. case GGML_OP_CONV_TRANSPOSE_2D:
  10177. case GGML_OP_CONV_2D_DW:
  10178. case GGML_OP_RWKV_WKV6:
  10179. case GGML_OP_RWKV_WKV7:
  10180. case GGML_OP_SSM_SCAN:
  10181. case GGML_OP_SSM_CONV:
  10182. case GGML_OP_LEAKY_RELU:
  10183. case GGML_OP_REPEAT:
  10184. case GGML_OP_REPEAT_BACK:
  10185. case GGML_OP_OPT_STEP_ADAMW:
  10186. case GGML_OP_OPT_STEP_SGD:
  10187. buf = tensor->buffer;
  10188. break;
  10189. case GGML_OP_UNARY:
  10190. switch (ggml_get_unary_op(tensor)) {
  10191. case GGML_UNARY_OP_EXP:
  10192. case GGML_UNARY_OP_SILU:
  10193. case GGML_UNARY_OP_GELU:
  10194. case GGML_UNARY_OP_GELU_ERF:
  10195. case GGML_UNARY_OP_GELU_QUICK:
  10196. case GGML_UNARY_OP_RELU:
  10197. case GGML_UNARY_OP_TANH:
  10198. case GGML_UNARY_OP_SIGMOID:
  10199. case GGML_UNARY_OP_HARDSIGMOID:
  10200. case GGML_UNARY_OP_HARDSWISH:
  10201. buf = tensor->buffer;
  10202. break;
  10203. default:
  10204. return false;
  10205. }
  10206. break;
  10207. case GGML_OP_GLU:
  10208. switch (ggml_get_glu_op(tensor)) {
  10209. case GGML_GLU_OP_GEGLU:
  10210. case GGML_GLU_OP_REGLU:
  10211. case GGML_GLU_OP_SWIGLU:
  10212. case GGML_GLU_OP_SWIGLU_OAI:
  10213. case GGML_GLU_OP_GEGLU_ERF:
  10214. case GGML_GLU_OP_GEGLU_QUICK:
  10215. buf = tensor->buffer;
  10216. break;
  10217. default:
  10218. return false;
  10219. }
  10220. break;
  10221. case GGML_OP_MUL_MAT:
  10222. case GGML_OP_MUL_MAT_ID:
  10223. case GGML_OP_FLASH_ATTN_EXT:
  10224. buf = tensor->buffer;
  10225. break;
  10226. default:
  10227. return false;
  10228. }
  10229. if (buf == nullptr) {
  10230. return false;
  10231. }
  10232. 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 << ")");
  10233. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  10234. // always wait for the GPU work to be done for the last submit
  10235. if (tensor_idx == subctx->exit_tensor_idx) {
  10236. use_fence = true;
  10237. }
  10238. // Only run if ctx hasn't been submitted yet
  10239. if (!subctx->seqs.empty()) {
  10240. #ifdef GGML_VULKAN_CHECK_RESULTS
  10241. ggml_vk_check_results_0(ctx, cgraph, tensor_idx);
  10242. use_fence = true;
  10243. #endif
  10244. // Do staging buffer copies
  10245. for (auto& cpy : subctx->in_memcpys) {
  10246. memcpy(cpy.dst, cpy.src, cpy.n);
  10247. }
  10248. for (auto& mset : subctx->memsets) {
  10249. memset(mset.dst, mset.val, mset.n);
  10250. }
  10251. if (almost_ready && !ctx->almost_ready_fence_pending && !use_fence) {
  10252. ggml_vk_submit(subctx, ctx->almost_ready_fence);
  10253. ctx->almost_ready_fence_pending = true;
  10254. } else {
  10255. ggml_vk_submit(subctx, use_fence ? ctx->fence : vk::Fence{});
  10256. }
  10257. if (use_fence) {
  10258. ggml_vk_wait_for_fence(ctx);
  10259. }
  10260. #ifdef GGML_VULKAN_CHECK_RESULTS
  10261. ggml_vk_check_results_1(ctx, cgraph, tensor_idx);
  10262. #endif
  10263. }
  10264. if (tensor_idx == subctx->exit_tensor_idx) {
  10265. // Do staging buffer copies
  10266. for (auto& cpy : subctx->out_memcpys) {
  10267. memcpy(cpy.dst, cpy.src, cpy.n);
  10268. }
  10269. subctx->in_memcpys.clear();
  10270. subctx->out_memcpys.clear();
  10271. subctx->memsets.clear();
  10272. }
  10273. return true;
  10274. }
  10275. // Clean up after graph processing is done
  10276. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  10277. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  10278. ctx->prealloc_y_last_pipeline_used = {};
  10279. ctx->unsynced_nodes_written.clear();
  10280. ctx->unsynced_nodes_read.clear();
  10281. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  10282. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  10283. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  10284. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  10285. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  10286. }
  10287. ctx->gc.semaphores.clear();
  10288. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  10289. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  10290. }
  10291. ctx->gc.tl_semaphores.clear();
  10292. ctx->semaphore_idx = 0;
  10293. ctx->event_idx = 0;
  10294. for (auto& event : ctx->gc.events) {
  10295. ctx->device->device.resetEvent(event);
  10296. }
  10297. ctx->tensor_ctxs.clear();
  10298. ctx->gc.contexts.clear();
  10299. ctx->pipeline_descriptor_set_requirements = 0;
  10300. ctx->descriptor_set_idx = 0;
  10301. }
  10302. // Clean up on backend free
  10303. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  10304. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  10305. ggml_vk_graph_cleanup(ctx);
  10306. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10307. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10308. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10309. ctx->prealloc_y_last_pipeline_used = nullptr;
  10310. ctx->prealloc_size_x = 0;
  10311. ctx->prealloc_size_y = 0;
  10312. ctx->prealloc_size_split_k = 0;
  10313. for (auto& event : ctx->gc.events) {
  10314. ctx->device->device.destroyEvent(event);
  10315. }
  10316. ctx->gc.events.clear();
  10317. ctx->device->device.destroyFence(ctx->fence);
  10318. ctx->device->device.destroyFence(ctx->almost_ready_fence);
  10319. for (auto& pool : ctx->descriptor_pools) {
  10320. ctx->device->device.destroyDescriptorPool(pool);
  10321. }
  10322. ctx->descriptor_pools.clear();
  10323. ctx->descriptor_sets.clear();
  10324. ctx->compute_cmd_pool.destroy(ctx->device->device);
  10325. ctx->transfer_cmd_pool.destroy(ctx->device->device);
  10326. }
  10327. static int ggml_vk_get_device_count() {
  10328. ggml_vk_instance_init();
  10329. return vk_instance.device_indices.size();
  10330. }
  10331. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  10332. ggml_vk_instance_init();
  10333. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  10334. vk::PhysicalDeviceProperties props;
  10335. devices[device].getProperties(&props);
  10336. snprintf(description, description_size, "%s", props.deviceName.data());
  10337. }
  10338. // backend interface
  10339. #define UNUSED GGML_UNUSED
  10340. // device backend
  10341. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  10342. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  10343. }
  10344. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10345. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  10346. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10347. ggml_vk_destroy_buffer(ctx->dev_buffer);
  10348. delete ctx;
  10349. }
  10350. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  10351. return vk_ptr_base;
  10352. UNUSED(buffer);
  10353. }
  10354. static enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  10355. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  10356. if (tensor->view_src != nullptr) {
  10357. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  10358. }
  10359. return GGML_STATUS_SUCCESS;
  10360. }
  10361. 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) {
  10362. VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")");
  10363. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10364. vk_buffer buf = buf_ctx->dev_buffer;
  10365. uint32_t val32 = (uint32_t)value * 0x01010101;
  10366. ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size);
  10367. }
  10368. 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) {
  10369. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10370. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10371. vk_buffer buf = buf_ctx->dev_buffer;
  10372. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10373. }
  10374. 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) {
  10375. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10376. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10377. vk_buffer buf = buf_ctx->dev_buffer;
  10378. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10379. }
  10380. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  10381. if (ggml_backend_buffer_is_vk(src->buffer)) {
  10382. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10383. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10384. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10385. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10386. 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));
  10387. return true;
  10388. }
  10389. return false;
  10390. UNUSED(buffer);
  10391. }
  10392. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  10393. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10394. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  10395. }
  10396. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  10397. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  10398. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  10399. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  10400. /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor,
  10401. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  10402. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  10403. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  10404. /* .clear = */ ggml_backend_vk_buffer_clear,
  10405. /* .reset = */ NULL,
  10406. };
  10407. // vk buffer type
  10408. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10409. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  10410. return ctx->name.c_str();
  10411. }
  10412. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10413. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  10414. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10415. vk_buffer dev_buffer = nullptr;
  10416. try {
  10417. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  10418. } catch (const vk::SystemError& e) {
  10419. return nullptr;
  10420. }
  10421. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  10422. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  10423. }
  10424. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10425. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10426. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  10427. }
  10428. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10429. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10430. return ctx->device->suballocation_block_size;
  10431. }
  10432. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  10433. return ggml_nbytes(tensor);
  10434. UNUSED(buft);
  10435. }
  10436. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  10437. ggml_vk_instance_init();
  10438. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  10439. vk_device dev = ggml_vk_get_device(dev_num);
  10440. return &dev->buffer_type;
  10441. }
  10442. // host buffer type
  10443. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10444. return GGML_VK_NAME "_Host";
  10445. UNUSED(buft);
  10446. }
  10447. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  10448. return GGML_VK_NAME "_Host";
  10449. UNUSED(buffer);
  10450. }
  10451. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10452. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  10453. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  10454. }
  10455. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10456. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  10457. size += 32; // Behave like the CPU buffer type
  10458. void * ptr = nullptr;
  10459. try {
  10460. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  10461. } catch (vk::SystemError& e) {
  10462. GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory (%s)\n", e.what());
  10463. // fallback to cpu buffer
  10464. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  10465. }
  10466. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  10467. buffer->buft = buft;
  10468. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  10469. return buffer;
  10470. UNUSED(buft);
  10471. }
  10472. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10473. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  10474. UNUSED(buft);
  10475. }
  10476. static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10477. return vk_instance.devices[0]->suballocation_block_size;
  10478. UNUSED(buft);
  10479. }
  10480. // Should be changed to return device-specific host buffer type
  10481. // but that probably requires changes in llama.cpp
  10482. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  10483. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  10484. /* .iface = */ {
  10485. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  10486. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  10487. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  10488. /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size,
  10489. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  10490. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  10491. },
  10492. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  10493. /* .context = */ nullptr,
  10494. };
  10495. // Make sure device 0 is initialized
  10496. ggml_vk_instance_init();
  10497. ggml_vk_get_device(0);
  10498. return &ggml_backend_vk_buffer_type_host;
  10499. }
  10500. // backend
  10501. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  10502. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10503. return ctx->name.c_str();
  10504. }
  10505. static void ggml_backend_vk_free(ggml_backend_t backend) {
  10506. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10507. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  10508. ggml_vk_cleanup(ctx);
  10509. delete ctx;
  10510. delete backend;
  10511. }
  10512. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  10513. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10514. return &ctx->device->buffer_type;
  10515. }
  10516. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  10517. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  10518. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10519. 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");
  10520. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10521. vk_context transfer_ctx;
  10522. if (ctx->transfer_ctx.expired()) {
  10523. // Initialize new transfer context
  10524. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10525. ctx->transfer_ctx = transfer_ctx;
  10526. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10527. } else {
  10528. transfer_ctx = ctx->transfer_ctx.lock();
  10529. }
  10530. vk_buffer buf = buf_ctx->dev_buffer;
  10531. ggml_vk_buffer_write_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10532. }
  10533. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  10534. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  10535. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10536. 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");
  10537. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10538. vk_context transfer_ctx;
  10539. if (ctx->transfer_ctx.expired()) {
  10540. // Initialize new transfer context
  10541. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10542. ctx->transfer_ctx = transfer_ctx;
  10543. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10544. } else {
  10545. transfer_ctx = ctx->transfer_ctx.lock();
  10546. }
  10547. vk_buffer buf = buf_ctx->dev_buffer;
  10548. ggml_vk_buffer_read_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10549. }
  10550. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  10551. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  10552. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10553. 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)) {
  10554. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10555. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10556. vk_context transfer_ctx;
  10557. if (ctx->transfer_ctx.expired()) {
  10558. // Initialize new transfer context
  10559. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10560. ctx->transfer_ctx = transfer_ctx;
  10561. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10562. } else {
  10563. transfer_ctx = ctx->transfer_ctx.lock();
  10564. }
  10565. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10566. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10567. 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));
  10568. return true;
  10569. }
  10570. return false;
  10571. }
  10572. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  10573. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  10574. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10575. if(ctx->transfer_ctx.expired()) {
  10576. return;
  10577. }
  10578. vk_context transfer_ctx = ctx->transfer_ctx.lock();
  10579. ggml_vk_ctx_end(transfer_ctx);
  10580. for (auto& cpy : transfer_ctx->in_memcpys) {
  10581. memcpy(cpy.dst, cpy.src, cpy.n);
  10582. }
  10583. ggml_vk_submit(transfer_ctx, ctx->fence);
  10584. ggml_vk_wait_for_fence(ctx);
  10585. for (auto& cpy : transfer_ctx->out_memcpys) {
  10586. memcpy(cpy.dst, cpy.src, cpy.n);
  10587. }
  10588. ctx->transfer_ctx.reset();
  10589. }
  10590. static bool ggml_vk_is_empty(ggml_tensor * node) {
  10591. 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;
  10592. }
  10593. 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) {
  10594. if (!ggml_can_fuse(cgraph, node_idx, ops)) {
  10595. return false;
  10596. }
  10597. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
  10598. // additional constraints specific to this fusion
  10599. const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
  10600. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10601. GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
  10602. GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
  10603. // rms_norm only supports f32
  10604. if (mul->src[0]->type != GGML_TYPE_F32 ||
  10605. mul->src[1]->type != GGML_TYPE_F32 ||
  10606. mul->type != GGML_TYPE_F32) {
  10607. return false;
  10608. }
  10609. // if rms_norm is the B operand, then we don't handle broadcast
  10610. if (rms_norm == mul->src[1] &&
  10611. !ggml_are_same_shape(mul->src[0], rms_norm)) {
  10612. return false;
  10613. }
  10614. // rms_norm shader assumes contiguous rows
  10615. if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
  10616. return false;
  10617. }
  10618. }
  10619. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT && ops.begin()[1] == GGML_OP_ADD) {
  10620. // additional constraints specific to this fusion
  10621. const ggml_tensor *mul = cgraph->nodes[node_idx];
  10622. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  10623. const ggml_tensor *bias = add->src[0] == mul ? add->src[1] : add->src[0];
  10624. // mat-vec only
  10625. if (ggml_nrows(mul) != 1) {
  10626. return false;
  10627. }
  10628. // shaders assume the types match
  10629. if (mul->type != bias->type) {
  10630. return false;
  10631. }
  10632. // shaders reuse the D shape for bias
  10633. if (!ggml_are_same_shape(mul, bias) ||
  10634. !ggml_are_same_stride(mul, bias)) {
  10635. return false;
  10636. }
  10637. // unaligned bias isn't handled
  10638. if (get_misalign_bytes(ctx, bias) != 0) {
  10639. return false;
  10640. }
  10641. }
  10642. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_ADD_ID) {
  10643. // additional constraints specific to this fusion
  10644. const ggml_tensor *mul = cgraph->nodes[node_idx];
  10645. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  10646. const ggml_tensor *bias = add->src[1];
  10647. if (mul != add->src[0]) {
  10648. return false;
  10649. }
  10650. // mat-vec only
  10651. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  10652. return false;
  10653. }
  10654. // shaders assume the types match
  10655. if (mul->type != bias->type) {
  10656. return false;
  10657. }
  10658. // shaders assume the bias is contiguous
  10659. if (!ggml_is_contiguous(bias)) {
  10660. return false;
  10661. }
  10662. // the ID tensor must be the same for mul_mat_id and add_id
  10663. if (mul->src[2] != add->src[2]) {
  10664. return false;
  10665. }
  10666. // unaligned bias isn't handled
  10667. if (get_misalign_bytes(ctx, bias) != 0) {
  10668. return false;
  10669. }
  10670. }
  10671. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_MUL) {
  10672. // additional constraints specific to this fusion
  10673. const ggml_tensor *mmid = cgraph->nodes[node_idx];
  10674. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10675. const ggml_tensor *scale = mul->src[1];
  10676. if (mmid != mul->src[0]) {
  10677. return false;
  10678. }
  10679. // mat-vec only
  10680. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  10681. return false;
  10682. }
  10683. // shaders assume the types match
  10684. if (mmid->type != scale->type) {
  10685. return false;
  10686. }
  10687. // shaders assume the bias is contiguous
  10688. if (!ggml_is_contiguous(scale)) {
  10689. return false;
  10690. }
  10691. // unaligned bias isn't handled
  10692. if (get_misalign_bytes(ctx, scale) != 0) {
  10693. return false;
  10694. }
  10695. // shader only indexes by expert index
  10696. if (scale->ne[0] != 1 ||
  10697. scale->ne[1] != mul->ne[1] ||
  10698. scale->ne[2] != 1 ||
  10699. scale->ne[3] != 1) {
  10700. return false;
  10701. }
  10702. }
  10703. return true;
  10704. }
  10705. static bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10706. int node_idx, topk_moe_mode mode) {
  10707. const ggml_tensor * softmax;
  10708. const ggml_tensor * weights;
  10709. switch (mode) {
  10710. case TOPK_MOE_EARLY_SOFTMAX_NORM:
  10711. softmax = cgraph->nodes[node_idx + 0];
  10712. weights = cgraph->nodes[node_idx + 9];
  10713. break;
  10714. case TOPK_MOE_EARLY_SOFTMAX:
  10715. softmax = cgraph->nodes[node_idx + 0];
  10716. weights = cgraph->nodes[node_idx + 4];
  10717. break;
  10718. case TOPK_MOE_LATE_SOFTMAX:
  10719. softmax = cgraph->nodes[node_idx + 4];
  10720. weights = cgraph->nodes[node_idx + 5];
  10721. break;
  10722. default:
  10723. return false;
  10724. }
  10725. const float * op_params = (const float *)softmax->op_params;
  10726. float scale = op_params[0];
  10727. float max_bias = op_params[1];
  10728. if (!ggml_is_contiguous(softmax->src[0]) || !ggml_is_contiguous(weights)) {
  10729. return false;
  10730. }
  10731. if (scale != 1.0f || max_bias != 0.0f) {
  10732. return false;
  10733. }
  10734. // don't fuse when masks or sinks are present
  10735. if (softmax->src[1] || softmax->src[2]) {
  10736. return false;
  10737. }
  10738. const int n_expert = softmax->ne[0];
  10739. // n_expert must be a power of 2
  10740. if (!is_pow2(n_expert) || n_expert > (1 << (num_topk_moe_pipelines-1))) {
  10741. return false;
  10742. }
  10743. if (!ctx->device->subgroup_arithmetic ||
  10744. !ctx->device->subgroup_shuffle ||
  10745. !ctx->device->subgroup_require_full_support ||
  10746. ctx->device->disable_fusion) {
  10747. return false;
  10748. }
  10749. return true;
  10750. }
  10751. static bool ggml_vk_can_fuse_rope_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10752. int node_idx) {
  10753. GGML_UNUSED(ctx);
  10754. const ggml_tensor *rope = cgraph->nodes[node_idx + 0];
  10755. const ggml_tensor *view = cgraph->nodes[node_idx + 1];
  10756. const ggml_tensor *set_rows = cgraph->nodes[node_idx + 2];
  10757. // ne3 not tested
  10758. if (rope->src[0]->ne[3] != 1) {
  10759. return false;
  10760. }
  10761. if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) {
  10762. return false;
  10763. }
  10764. if (set_rows->src[1]->type != GGML_TYPE_I64) {
  10765. return false;
  10766. }
  10767. // The view should flatten two dims of rope into one dim
  10768. if (!ggml_is_contiguous(view) ||
  10769. view->ne[0] != rope->ne[0] * rope->ne[1]) {
  10770. return false;
  10771. }
  10772. // Only norm/neox shaders have the fusion code
  10773. const int mode = ((const int32_t *) rope->op_params)[2];
  10774. if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX) {
  10775. return false;
  10776. }
  10777. return true;
  10778. }
  10779. // Check whether the tensors overlap in memory but are not equal.
  10780. // Fusions can potenitally overwrite src tensors in ways that are not prevented
  10781. // by ggml-alloc. If the fusion is entirely elementwise, then it's OK for them
  10782. // to overlap if they are exactly equal.
  10783. // XXX TODO this check is probably missing from several fusion optimizations.
  10784. static bool ggml_vk_tensors_overlap_but_not_equal(const ggml_tensor * a, const ggml_tensor * b) {
  10785. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)a->buffer->context;
  10786. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  10787. ggml_backend_vk_buffer_context * b_buf_ctx = (ggml_backend_vk_buffer_context *)b->buffer->context;
  10788. vk_buffer b_buf = b_buf_ctx->dev_buffer;
  10789. if (a_buf == b_buf) {
  10790. auto a_base = vk_tensor_offset(a) + a->view_offs;
  10791. auto a_size = ggml_nbytes(a);
  10792. auto b_base = vk_tensor_offset(b) + b->view_offs;
  10793. auto b_size = ggml_nbytes(b);
  10794. if (a_base == b_base && a_size == b_size) {
  10795. return false;
  10796. }
  10797. if ((b_base <= a_base && a_base < b_base + b_size) ||
  10798. (a_base <= b_base && b_base < a_base + a_size)) {
  10799. return true;
  10800. }
  10801. }
  10802. return false;
  10803. }
  10804. static bool ggml_vk_can_fuse_rms_norm_mul_rope(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10805. int node_idx) {
  10806. GGML_UNUSED(ctx);
  10807. const ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  10808. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10809. const ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  10810. const int mode = ((const int32_t *) rope->op_params)[2];
  10811. // noncontig tensors aren't tested, and don't seem common in practice
  10812. if (!ggml_is_contiguous(rms) ||
  10813. !ggml_is_contiguous(mul) ||
  10814. !ggml_is_contiguous(rope)) {
  10815. return false;
  10816. }
  10817. // only norm/neox are handled in the shader
  10818. if (mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_NORMAL) {
  10819. return false;
  10820. }
  10821. // shared memory size for passing data from mul->rope
  10822. if (mul->ne[0] > 1024) {
  10823. return false;
  10824. }
  10825. // must not overwrite srcs in a way that's not elementwise
  10826. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  10827. if (ggml_vk_tensors_overlap_but_not_equal(rms->src[0], rope) ||
  10828. ggml_vk_tensors_overlap_but_not_equal(other_src, rope)) {
  10829. return false;
  10830. }
  10831. return true;
  10832. }
  10833. static uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) {
  10834. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  10835. if (first_node->op != GGML_OP_ADD) {
  10836. return 0;
  10837. }
  10838. if (!ctx->device->multi_add) {
  10839. return 0;
  10840. }
  10841. int32_t num_adds = 1;
  10842. while (node_idx + num_adds < cgraph->n_nodes &&
  10843. cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD &&
  10844. num_adds < MAX_FUSED_ADDS) {
  10845. num_adds++;
  10846. }
  10847. // The shader currently requires same shapes (but different strides are allowed),
  10848. // everything f32, and no misalignment
  10849. for (int32_t i = 0; i < num_adds; ++i) {
  10850. const ggml_tensor *next_node = cgraph->nodes[node_idx + i];
  10851. if (!ggml_are_same_shape(first_node, next_node->src[0]) ||
  10852. !ggml_are_same_shape(first_node, next_node->src[1]) ||
  10853. next_node->type != GGML_TYPE_F32 ||
  10854. next_node->src[0]->type != GGML_TYPE_F32 ||
  10855. next_node->src[1]->type != GGML_TYPE_F32 ||
  10856. get_misalign_bytes(ctx, next_node) ||
  10857. get_misalign_bytes(ctx, next_node->src[0]) ||
  10858. get_misalign_bytes(ctx, next_node->src[1])) {
  10859. num_adds = i;
  10860. }
  10861. }
  10862. // Verify we can fuse these
  10863. ggml_op adds[MAX_FUSED_ADDS];
  10864. for (int32_t i = 0; i < num_adds; ++i) {
  10865. adds[i] = GGML_OP_ADD;
  10866. }
  10867. // decrease num_adds if they can't all be fused
  10868. while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) {
  10869. num_adds--;
  10870. }
  10871. // a single add is not "fused", so just return zero
  10872. if (num_adds == 1) {
  10873. return 0;
  10874. }
  10875. return num_adds;
  10876. }
  10877. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  10878. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  10879. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10880. if (vk_instance.debug_utils_support) {
  10881. vk::DebugUtilsLabelEXT dul = {};
  10882. dul.pLabelName = "ggml_backend_vk_graph_compute";
  10883. dul.color = std::array<float,4>{1.0f, 1.0f, 1.0f, 1.0f};
  10884. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(ctx->device->compute_queue.queue, reinterpret_cast<VkDebugUtilsLabelEXT*>(&dul));
  10885. }
  10886. ctx->prealloc_size_add_rms_partials_offset = 0;
  10887. ctx->do_add_rms_partials = false;
  10888. ctx->do_add_rms_partials_offset_calculation = false;
  10889. int last_node = cgraph->n_nodes - 1;
  10890. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  10891. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  10892. last_node -= 1;
  10893. }
  10894. // Reserve tensor context space for all nodes
  10895. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  10896. bool first_node_in_batch = true; // true if next node will be first node in a batch
  10897. int submit_node_idx = 0; // index to first node in a batch
  10898. vk_context compute_ctx;
  10899. if (vk_perf_logger_enabled) {
  10900. // allocate/resize the query pool
  10901. if (ctx->device->num_queries < cgraph->n_nodes + 1) {
  10902. if (ctx->device->query_pool) {
  10903. ctx->device->device.destroyQueryPool(ctx->device->query_pool);
  10904. }
  10905. vk::QueryPoolCreateInfo query_create_info;
  10906. query_create_info.queryType = vk::QueryType::eTimestamp;
  10907. query_create_info.queryCount = cgraph->n_nodes + 100;
  10908. ctx->device->query_pool = ctx->device->device.createQueryPool(query_create_info);
  10909. ctx->device->num_queries = query_create_info.queryCount;
  10910. }
  10911. ctx->device->device.resetQueryPool(ctx->device->query_pool, 0, cgraph->n_nodes+1);
  10912. GGML_ASSERT(ctx->compute_ctx.expired());
  10913. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10914. ctx->compute_ctx = compute_ctx;
  10915. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10916. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, 0);
  10917. }
  10918. ctx->prealloc_y_last_pipeline_used = nullptr;
  10919. ctx->prealloc_y_last_tensor_used = nullptr;
  10920. if (ctx->prealloc_size_add_rms_partials) {
  10921. ggml_vk_preallocate_buffers(ctx, nullptr);
  10922. if (ctx->compute_ctx.expired()) {
  10923. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10924. ctx->compute_ctx = compute_ctx;
  10925. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10926. } else {
  10927. compute_ctx = ctx->compute_ctx.lock();
  10928. }
  10929. // initialize partial sums to zero.
  10930. ggml_vk_buffer_memset_async(compute_ctx, ctx->prealloc_add_rms_partials, 0, 0, ctx->prealloc_size_add_rms_partials);
  10931. ggml_vk_sync_buffers(ctx, compute_ctx);
  10932. }
  10933. // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution.
  10934. // Estimate the amount of matmul work by looking at the weight matrix size, and submit every 100MB
  10935. // (and scaled down based on model size, so smaller models submit earlier).
  10936. // Also submit at least every 100 nodes, in case there are workloads without as much matmul.
  10937. int nodes_per_submit = 100;
  10938. int submitted_nodes = 0;
  10939. int submit_count = 0;
  10940. uint64_t mul_mat_bytes = 0;
  10941. uint64_t total_mul_mat_bytes = 0;
  10942. uint64_t mul_mat_bytes_per_submit = std::min(uint64_t(100*1000*1000), ctx->last_total_mul_mat_bytes / 40u);
  10943. for (int i = 0; i < cgraph->n_nodes; i++) {
  10944. if (first_node_in_batch) {
  10945. submit_node_idx = i;
  10946. }
  10947. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  10948. auto bytes = ggml_nbytes(cgraph->nodes[i]->src[0]);
  10949. mul_mat_bytes += bytes;
  10950. total_mul_mat_bytes += bytes;
  10951. }
  10952. if (!ctx->device->disable_fusion) {
  10953. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  10954. if (num_adds) {
  10955. ctx->num_additional_fused_ops = num_adds - 1;
  10956. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD })) {
  10957. ctx->num_additional_fused_ops = 1;
  10958. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID })) {
  10959. ctx->num_additional_fused_ops = 1;
  10960. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_MUL })) {
  10961. ctx->num_additional_fused_ops = 1;
  10962. } 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 }) &&
  10963. ggml_check_edges(cgraph, i, rms_norm_mul_rope_view_set_rows_edges) &&
  10964. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i) &&
  10965. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i + 2)) {
  10966. ctx->num_additional_fused_ops = 4;
  10967. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE })&&
  10968. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i)) {
  10969. ctx->num_additional_fused_ops = 2;
  10970. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  10971. ctx->num_additional_fused_ops = 1;
  10972. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 2 }) &&
  10973. ggml_check_edges(cgraph, i, rope_view_set_rows_edges) &&
  10974. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i)) {
  10975. ctx->num_additional_fused_ops = 2;
  10976. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax_norm, { i + 3, i + 9 }) &&
  10977. ggml_check_edges(cgraph, i, topk_moe_early_softmax_norm_edges) &&
  10978. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX_NORM)) {
  10979. ctx->num_additional_fused_ops = topk_moe_early_softmax_norm.size() - 1;
  10980. // view of argsort writes to memory
  10981. ctx->fused_ops_write_mask |= 1 << 3;
  10982. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax, { i + 3, i + 4 }) &&
  10983. ggml_check_edges(cgraph, i, topk_moe_early_softmax_edges) &&
  10984. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX)) {
  10985. ctx->num_additional_fused_ops = topk_moe_early_softmax.size() - 1;
  10986. // view of argsort writes to memory
  10987. ctx->fused_ops_write_mask |= 1 << 3;
  10988. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_late_softmax, { i + 1, i + 5 }) &&
  10989. ggml_check_edges(cgraph, i, topk_moe_late_softmax_edges) &&
  10990. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_LATE_SOFTMAX)) {
  10991. ctx->num_additional_fused_ops = topk_moe_late_softmax.size() - 1;
  10992. // view of argsort writes to memory
  10993. ctx->fused_ops_write_mask |= 1 << 1;
  10994. }
  10995. }
  10996. ctx->fused_ops_write_mask |= 1 << ctx->num_additional_fused_ops;
  10997. // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining)
  10998. bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5;
  10999. bool submit = (submitted_nodes >= nodes_per_submit) ||
  11000. (mul_mat_bytes_per_submit != 0 && mul_mat_bytes >= mul_mat_bytes_per_submit) ||
  11001. (i + ctx->num_additional_fused_ops >= last_node) ||
  11002. (almost_ready && !ctx->almost_ready_fence_pending);
  11003. 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);
  11004. if (vk_perf_logger_enabled) {
  11005. if (ctx->compute_ctx.expired()) {
  11006. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11007. ctx->compute_ctx = compute_ctx;
  11008. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11009. } else {
  11010. compute_ctx = ctx->compute_ctx.lock();
  11011. }
  11012. // If there are fused ops, just write out timestamps for all nodes to keep the accounting simple
  11013. for (int j = 0; j < ctx->num_additional_fused_ops + 1; ++j) {
  11014. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, i+j+1);
  11015. }
  11016. }
  11017. if (enqueued) {
  11018. ++submitted_nodes;
  11019. #ifndef GGML_VULKAN_CHECK_RESULTS
  11020. if (first_node_in_batch) {
  11021. first_node_in_batch = false;
  11022. }
  11023. #endif
  11024. }
  11025. if (submit && enqueued) {
  11026. first_node_in_batch = true;
  11027. submitted_nodes = 0;
  11028. mul_mat_bytes = 0;
  11029. if (submit_count < 3) {
  11030. mul_mat_bytes_per_submit *= 2;
  11031. }
  11032. submit_count++;
  11033. }
  11034. i += ctx->num_additional_fused_ops;
  11035. ctx->num_additional_fused_ops = 0;
  11036. ctx->fused_ops_write_mask = 0;
  11037. }
  11038. ctx->prealloc_size_add_rms_partials = std::max(ctx->prealloc_size_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset);
  11039. ctx->last_total_mul_mat_bytes = total_mul_mat_bytes;
  11040. if (vk_perf_logger_enabled) {
  11041. // End the command buffer and submit/wait
  11042. GGML_ASSERT(!ctx->compute_ctx.expired());
  11043. compute_ctx = ctx->compute_ctx.lock();
  11044. ggml_vk_ctx_end(compute_ctx);
  11045. ggml_vk_submit(compute_ctx, ctx->device->fence);
  11046. VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences");
  11047. ctx->device->device.resetFences({ ctx->device->fence });
  11048. // Get the results and pass them to the logger
  11049. std::vector<uint64_t> timestamps(cgraph->n_nodes + 1);
  11050. VK_CHECK(ctx->device->device.getQueryPoolResults(ctx->device->query_pool, 0, cgraph->n_nodes + 1, (cgraph->n_nodes + 1)*sizeof(uint64_t), timestamps.data(), sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait), "get timestamp results");
  11051. for (int i = 0; i < cgraph->n_nodes; i++) {
  11052. if (!ggml_vk_is_empty(cgraph->nodes[i])) {
  11053. ctx->device->perf_logger->log_timing(cgraph->nodes[i], uint64_t((timestamps[i+1] - timestamps[i]) * ctx->device->properties.limits.timestampPeriod));
  11054. }
  11055. }
  11056. ctx->device->perf_logger->print_timings();
  11057. }
  11058. ggml_vk_graph_cleanup(ctx);
  11059. return GGML_STATUS_SUCCESS;
  11060. UNUSED(backend);
  11061. }
  11062. // Sort the graph for improved parallelism.
  11063. static void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph)
  11064. {
  11065. VK_LOG_DEBUG("ggml_vk_graph_optimize(" << graph->n_nodes << " nodes)");
  11066. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11067. if (ctx->device->disable_graph_optimize) {
  11068. return;
  11069. }
  11070. auto const &is_empty = [](ggml_tensor * node) -> bool {
  11071. 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;
  11072. };
  11073. auto const &is_src_of = [](const ggml_tensor *dst, const ggml_tensor *src) -> bool {
  11074. for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) {
  11075. if (dst->src[s] == src) {
  11076. return true;
  11077. }
  11078. }
  11079. // implicit dependency if they view the same tensor
  11080. const ggml_tensor *dst2 = dst->view_src ? dst->view_src : dst;
  11081. const ggml_tensor *src2 = src->view_src ? src->view_src : src;
  11082. if (dst2 == src2) {
  11083. return true;
  11084. }
  11085. return false;
  11086. };
  11087. // This function tries to reorder the graph to allow nodes to run in parallel.
  11088. // This helps with small batches, but for large batches its a slowdown, probably
  11089. // due to cache contention. So only reorder if the majority of nodes have few rows.
  11090. int num_small_nodes = 0;
  11091. int num_counted_nodes = 0;
  11092. for (int i = 0; i < graph->n_nodes; ++i) {
  11093. if (!is_empty(graph->nodes[i]) &&
  11094. graph->nodes[i]->op != GGML_OP_SET_ROWS) {
  11095. if (ggml_nrows(graph->nodes[i]) <= 8) {
  11096. num_small_nodes++;
  11097. }
  11098. num_counted_nodes++;
  11099. }
  11100. }
  11101. if (num_small_nodes < num_counted_nodes / 2) {
  11102. return;
  11103. }
  11104. std::vector<ggml_tensor *> new_order;
  11105. std::vector<bool> used(graph->n_nodes, false);
  11106. int first_unused = 0;
  11107. while (first_unused < graph->n_nodes) {
  11108. std::vector<int> current_set;
  11109. // Check for fusion patterns and avoid reordering them
  11110. auto const &match_pattern = [&](const std::initializer_list<ggml_op> &pattern, int start) -> bool {
  11111. if (start + (int)pattern.size() <= graph->n_nodes) {
  11112. bool is_pattern = true;
  11113. for (size_t j = 0; j < pattern.size(); ++j) {
  11114. if (graph->nodes[start + j]->op != pattern.begin()[j] || used[start + j]) {
  11115. is_pattern = false;
  11116. }
  11117. }
  11118. return is_pattern;
  11119. }
  11120. return false;
  11121. };
  11122. auto const &keep_pattern = [&](const std::initializer_list<ggml_op> &pattern) -> bool {
  11123. if (match_pattern(pattern, first_unused)) {
  11124. for (size_t j = 0; j < pattern.size(); ++j) {
  11125. new_order.push_back(graph->nodes[first_unused + j]);
  11126. used[first_unused + j] = true;
  11127. }
  11128. while (first_unused < graph->n_nodes && used[first_unused]) {
  11129. first_unused++;
  11130. }
  11131. return true;
  11132. }
  11133. return false;
  11134. };
  11135. if (keep_pattern(topk_moe_early_softmax_norm)) {
  11136. continue;
  11137. }
  11138. if (keep_pattern(topk_moe_early_softmax)) {
  11139. continue;
  11140. }
  11141. if (keep_pattern(topk_moe_late_softmax)) {
  11142. continue;
  11143. }
  11144. // First, grab the next unused node.
  11145. current_set.push_back(first_unused);
  11146. // Loop through the next N nodes. Grab any that don't depend on other nodes that
  11147. // haven't already been run. Nodes that have already been run have used[i] set
  11148. // to true. Allow nodes that depend on the previous node if it's a fusion pattern
  11149. // that we support (e.g. RMS_NORM + MUL).
  11150. // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes.
  11151. // The goal is to not interleave real and view nodes in a way that breaks fusion.
  11152. const int NUM_TO_CHECK = 20;
  11153. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11154. if (used[j]) {
  11155. continue;
  11156. }
  11157. if (is_empty(graph->nodes[j])) {
  11158. continue;
  11159. }
  11160. // Don't pull forward nodes from fusion patterns
  11161. if (match_pattern(topk_moe_early_softmax_norm, j) ||
  11162. match_pattern(topk_moe_early_softmax, j) ||
  11163. match_pattern(topk_moe_late_softmax, j)) {
  11164. continue;
  11165. }
  11166. bool ok = true;
  11167. for (int c = first_unused; c < j; ++c) {
  11168. if (!used[c] &&
  11169. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11170. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL) &&
  11171. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT && graph->nodes[j]->op == GGML_OP_ADD) &&
  11172. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_ADD_ID) &&
  11173. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_MUL)) {
  11174. ok = false;
  11175. break;
  11176. }
  11177. }
  11178. if (ok) {
  11179. current_set.push_back(j);
  11180. int rope_idx = j;
  11181. // When we've found RMS_NORM + MUL, try to find a ROPE that uses it
  11182. if (j > 0 &&
  11183. graph->nodes[j]->op == GGML_OP_MUL &&
  11184. graph->nodes[j-1]->op == GGML_OP_RMS_NORM) {
  11185. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11186. if (graph->nodes[k]->op == GGML_OP_ROPE &&
  11187. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11188. // Check that other srcs are already valid
  11189. graph->nodes[k]->src[1]->op == GGML_OP_NONE &&
  11190. (graph->nodes[k]->src[2] == nullptr || graph->nodes[k]->src[2]->op == GGML_OP_NONE)) {
  11191. rope_idx = k;
  11192. current_set.push_back(rope_idx);
  11193. used[rope_idx] = true;
  11194. break;
  11195. }
  11196. }
  11197. }
  11198. // Look for ROPE + VIEW + SET_ROWS and make them consecutive
  11199. if (graph->nodes[rope_idx]->op == GGML_OP_ROPE) {
  11200. int view_idx = -1;
  11201. int set_rows_idx = -1;
  11202. for (int k = rope_idx+1; k < std::min(rope_idx + 10, graph->n_nodes); ++k) {
  11203. if (view_idx == -1 &&
  11204. graph->nodes[k]->op == GGML_OP_VIEW &&
  11205. graph->nodes[k]->src[0] == graph->nodes[rope_idx]) {
  11206. view_idx = k;
  11207. continue;
  11208. }
  11209. if (view_idx != -1 &&
  11210. set_rows_idx == -1 &&
  11211. graph->nodes[k]->op == GGML_OP_SET_ROWS &&
  11212. graph->nodes[k]->src[0] == graph->nodes[view_idx]) {
  11213. set_rows_idx = k;
  11214. break;
  11215. }
  11216. }
  11217. if (set_rows_idx != -1) {
  11218. current_set.push_back(view_idx);
  11219. current_set.push_back(set_rows_idx);
  11220. used[view_idx] = true;
  11221. used[set_rows_idx] = true;
  11222. }
  11223. }
  11224. }
  11225. }
  11226. // Second pass grabs view nodes.
  11227. // Skip this if it would break a fusion optimization (don't split up add->rms_norm or add->add).
  11228. if (graph->nodes[current_set.back()]->op != GGML_OP_ADD) {
  11229. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11230. if (used[j]) {
  11231. continue;
  11232. }
  11233. if (!is_empty(graph->nodes[j])) {
  11234. continue;
  11235. }
  11236. bool ok = true;
  11237. for (int c = first_unused; c < j; ++c) {
  11238. bool c_in_current_set = std::find(current_set.begin(), current_set.end(), c) != current_set.end();
  11239. // skip views whose srcs haven't been processed.
  11240. if (!used[c] &&
  11241. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11242. !c_in_current_set) {
  11243. ok = false;
  11244. break;
  11245. }
  11246. }
  11247. if (ok) {
  11248. current_set.push_back(j);
  11249. }
  11250. }
  11251. }
  11252. // Push the current set into new_order
  11253. for (auto c : current_set) {
  11254. new_order.push_back(graph->nodes[c]);
  11255. used[c] = true;
  11256. }
  11257. while (first_unused < graph->n_nodes && used[first_unused]) {
  11258. first_unused++;
  11259. }
  11260. }
  11261. // Replace the graph with the new order.
  11262. for (int i = 0; i < graph->n_nodes; ++i) {
  11263. graph->nodes[i] = new_order[i];
  11264. }
  11265. }
  11266. // TODO: enable async and synchronize
  11267. static ggml_backend_i ggml_backend_vk_interface = {
  11268. /* .get_name = */ ggml_backend_vk_name,
  11269. /* .free = */ ggml_backend_vk_free,
  11270. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  11271. /* .get_tensor_async = */ NULL, // ggml_backend_vk_get_tensor_async,
  11272. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  11273. /* .synchronize = */ NULL, // ggml_backend_vk_synchronize,
  11274. /* .graph_plan_create = */ NULL,
  11275. /* .graph_plan_free = */ NULL,
  11276. /* .graph_plan_update = */ NULL,
  11277. /* .graph_plan_compute = */ NULL,
  11278. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  11279. /* .event_record = */ NULL,
  11280. /* .event_wait = */ NULL,
  11281. /* .graph_optimize = */ ggml_vk_graph_optimize,
  11282. };
  11283. static ggml_guid_t ggml_backend_vk_guid() {
  11284. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  11285. return &guid;
  11286. }
  11287. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  11288. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  11289. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  11290. ggml_vk_init(ctx, dev_num);
  11291. ggml_backend_t vk_backend = new ggml_backend {
  11292. /* .guid = */ ggml_backend_vk_guid(),
  11293. /* .iface = */ ggml_backend_vk_interface,
  11294. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  11295. /* .context = */ ctx,
  11296. };
  11297. return vk_backend;
  11298. }
  11299. bool ggml_backend_is_vk(ggml_backend_t backend) {
  11300. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  11301. }
  11302. int ggml_backend_vk_get_device_count() {
  11303. return ggml_vk_get_device_count();
  11304. }
  11305. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  11306. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11307. int dev_idx = vk_instance.device_indices[device];
  11308. ggml_vk_get_device_description(dev_idx, description, description_size);
  11309. }
  11310. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  11311. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11312. GGML_ASSERT(device < (int) vk_instance.device_supports_membudget.size());
  11313. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  11314. vk::PhysicalDeviceMemoryBudgetPropertiesEXT budgetprops;
  11315. vk::PhysicalDeviceMemoryProperties2 memprops = {};
  11316. const bool membudget_supported = vk_instance.device_supports_membudget[device];
  11317. const bool is_integrated_gpu = vkdev.getProperties().deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  11318. if (membudget_supported) {
  11319. memprops.pNext = &budgetprops;
  11320. }
  11321. vkdev.getMemoryProperties2(&memprops);
  11322. *total = 0;
  11323. *free = 0;
  11324. for (uint32_t i = 0; i < memprops.memoryProperties.memoryHeapCount; ++i) {
  11325. const vk::MemoryHeap & heap = memprops.memoryProperties.memoryHeaps[i];
  11326. if (is_integrated_gpu || (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal)) {
  11327. *total += heap.size;
  11328. if (membudget_supported && i < budgetprops.heapUsage.size()) {
  11329. *free += budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
  11330. } else {
  11331. *free += heap.size;
  11332. }
  11333. }
  11334. }
  11335. }
  11336. static vk::PhysicalDeviceType ggml_backend_vk_get_device_type(int device_idx) {
  11337. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11338. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11339. vk::PhysicalDeviceProperties2 props = {};
  11340. device.getProperties2(&props);
  11341. return props.properties.deviceType;
  11342. }
  11343. static std::string ggml_backend_vk_get_device_pci_id(int device_idx) {
  11344. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11345. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11346. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  11347. bool ext_support = false;
  11348. for (const auto& properties : ext_props) {
  11349. if (strcmp("VK_EXT_pci_bus_info", properties.extensionName) == 0) {
  11350. ext_support = true;
  11351. break;
  11352. }
  11353. }
  11354. if (!ext_support) {
  11355. return "";
  11356. }
  11357. vk::PhysicalDeviceProperties2 props = {};
  11358. vk::PhysicalDevicePCIBusInfoPropertiesEXT pci_bus_info = {};
  11359. props.pNext = &pci_bus_info;
  11360. device.getProperties2(&props);
  11361. const uint32_t pci_domain = pci_bus_info.pciDomain;
  11362. const uint32_t pci_bus = pci_bus_info.pciBus;
  11363. const uint32_t pci_device = pci_bus_info.pciDevice;
  11364. const uint8_t pci_function = (uint8_t) pci_bus_info.pciFunction; // pci function is between 0 and 7, prevent printf overflow warning
  11365. char pci_bus_id[16] = {};
  11366. snprintf(pci_bus_id, sizeof(pci_bus_id), "%04x:%02x:%02x.%x", pci_domain, pci_bus, pci_device, pci_function);
  11367. return std::string(pci_bus_id);
  11368. }
  11369. //////////////////////////
  11370. struct ggml_backend_vk_device_context {
  11371. size_t device;
  11372. std::string name;
  11373. std::string description;
  11374. bool is_integrated_gpu;
  11375. std::string pci_bus_id;
  11376. };
  11377. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  11378. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11379. return ctx->name.c_str();
  11380. }
  11381. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  11382. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11383. return ctx->description.c_str();
  11384. }
  11385. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  11386. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  11387. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  11388. }
  11389. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  11390. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11391. return ggml_backend_vk_buffer_type(ctx->device);
  11392. }
  11393. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  11394. UNUSED(dev);
  11395. return ggml_backend_vk_host_buffer_type();
  11396. }
  11397. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  11398. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11399. return ctx->is_integrated_gpu ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
  11400. }
  11401. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  11402. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11403. props->name = ggml_backend_vk_device_get_name(dev);
  11404. props->description = ggml_backend_vk_device_get_description(dev);
  11405. props->type = ggml_backend_vk_device_get_type(dev);
  11406. props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str();
  11407. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  11408. props->caps = {
  11409. /* .async = */ false,
  11410. /* .host_buffer = */ true,
  11411. /* .buffer_from_host_ptr = */ false,
  11412. /* .events = */ false,
  11413. };
  11414. }
  11415. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  11416. UNUSED(params);
  11417. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11418. return ggml_backend_vk_init(ctx->device);
  11419. }
  11420. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  11421. switch (op->op) {
  11422. case GGML_OP_UNARY:
  11423. switch (ggml_get_unary_op(op)) {
  11424. case GGML_UNARY_OP_EXP:
  11425. case GGML_UNARY_OP_GELU:
  11426. case GGML_UNARY_OP_GELU_ERF:
  11427. case GGML_UNARY_OP_GELU_QUICK:
  11428. case GGML_UNARY_OP_SILU:
  11429. case GGML_UNARY_OP_RELU:
  11430. case GGML_UNARY_OP_TANH:
  11431. case GGML_UNARY_OP_SIGMOID:
  11432. case GGML_UNARY_OP_HARDSIGMOID:
  11433. case GGML_UNARY_OP_HARDSWISH:
  11434. return ggml_is_contiguous(op->src[0]) &&
  11435. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11436. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11437. (op->src[0]->type == op->type);
  11438. default:
  11439. return false;
  11440. }
  11441. case GGML_OP_GLU:
  11442. switch (ggml_get_glu_op(op)) {
  11443. case GGML_GLU_OP_GEGLU:
  11444. case GGML_GLU_OP_REGLU:
  11445. case GGML_GLU_OP_SWIGLU:
  11446. case GGML_GLU_OP_SWIGLU_OAI:
  11447. case GGML_GLU_OP_GEGLU_ERF:
  11448. case GGML_GLU_OP_GEGLU_QUICK:
  11449. return ggml_is_contiguous(op->src[0]) &&
  11450. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11451. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11452. (op->src[0]->type == op->type);
  11453. default:
  11454. return false;
  11455. }
  11456. case GGML_OP_MUL_MAT:
  11457. case GGML_OP_MUL_MAT_ID:
  11458. {
  11459. ggml_type src0_type = op->src[0]->type;
  11460. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11461. const vk_device& device = ggml_vk_get_device(ctx->device);
  11462. if (op->op == GGML_OP_MUL_MAT_ID) {
  11463. if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) {
  11464. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  11465. return false;
  11466. }
  11467. }
  11468. switch (src0_type) {
  11469. case GGML_TYPE_F32:
  11470. case GGML_TYPE_F16:
  11471. case GGML_TYPE_BF16:
  11472. case GGML_TYPE_Q4_0:
  11473. case GGML_TYPE_Q4_1:
  11474. case GGML_TYPE_Q5_0:
  11475. case GGML_TYPE_Q5_1:
  11476. case GGML_TYPE_Q8_0:
  11477. case GGML_TYPE_Q2_K:
  11478. case GGML_TYPE_Q3_K:
  11479. case GGML_TYPE_Q4_K:
  11480. case GGML_TYPE_Q5_K:
  11481. case GGML_TYPE_Q6_K:
  11482. case GGML_TYPE_IQ1_S:
  11483. case GGML_TYPE_IQ1_M:
  11484. case GGML_TYPE_IQ2_XXS:
  11485. case GGML_TYPE_IQ2_XS:
  11486. case GGML_TYPE_IQ2_S:
  11487. case GGML_TYPE_IQ3_XXS:
  11488. case GGML_TYPE_IQ3_S:
  11489. case GGML_TYPE_IQ4_XS:
  11490. case GGML_TYPE_IQ4_NL:
  11491. case GGML_TYPE_MXFP4:
  11492. break;
  11493. default:
  11494. return false;
  11495. }
  11496. struct ggml_tensor * a;
  11497. struct ggml_tensor * b;
  11498. if (op->op == GGML_OP_MUL_MAT) {
  11499. a = op->src[0];
  11500. b = op->src[1];
  11501. } else {
  11502. a = op->src[2];
  11503. b = op->src[1];
  11504. }
  11505. if (a->ne[3] != b->ne[3]) {
  11506. return false;
  11507. }
  11508. 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) ||
  11509. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  11510. return false;
  11511. }
  11512. if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) {
  11513. // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader.
  11514. // So don't support this combination for now.
  11515. return false;
  11516. }
  11517. return true;
  11518. }
  11519. case GGML_OP_FLASH_ATTN_EXT:
  11520. {
  11521. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11522. auto device = ggml_vk_get_device(ctx->device);
  11523. bool coopmat2 = device->coopmat2;
  11524. uint32_t HSK = op->src[1]->ne[0];
  11525. uint32_t HSV = op->src[2]->ne[0];
  11526. if ((HSK % 8) != 0 || (HSV % 8) != 0) {
  11527. return false;
  11528. }
  11529. if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) {
  11530. return false;
  11531. }
  11532. if (op->src[0]->type != GGML_TYPE_F32) {
  11533. return false;
  11534. }
  11535. if (op->type != GGML_TYPE_F32) {
  11536. return false;
  11537. }
  11538. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  11539. return false;
  11540. }
  11541. // It's straightforward to support different K/V dequant, but would
  11542. // significantly increase the number of pipelines
  11543. if (op->src[1]->type != op->src[2]->type) {
  11544. return false;
  11545. }
  11546. switch (op->src[1]->type) {
  11547. case GGML_TYPE_F16:
  11548. case GGML_TYPE_F32:
  11549. case GGML_TYPE_Q4_0:
  11550. case GGML_TYPE_Q8_0:
  11551. // supported in scalar and coopmat2 paths
  11552. break;
  11553. case GGML_TYPE_Q4_1:
  11554. case GGML_TYPE_Q5_0:
  11555. case GGML_TYPE_Q5_1:
  11556. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  11557. //case GGML_TYPE_Q2_K:
  11558. //case GGML_TYPE_Q3_K:
  11559. //case GGML_TYPE_Q4_K:
  11560. //case GGML_TYPE_Q5_K:
  11561. //case GGML_TYPE_Q6_K:
  11562. //case GGML_TYPE_IQ1_S:
  11563. //case GGML_TYPE_IQ1_M:
  11564. //case GGML_TYPE_IQ2_XXS:
  11565. //case GGML_TYPE_IQ2_XS:
  11566. //case GGML_TYPE_IQ2_S:
  11567. //case GGML_TYPE_IQ3_XXS:
  11568. //case GGML_TYPE_IQ3_S:
  11569. //case GGML_TYPE_IQ4_XS:
  11570. case GGML_TYPE_IQ4_NL:
  11571. // currently supported only in coopmat2 path
  11572. if (!coopmat2) {
  11573. return false;
  11574. }
  11575. break;
  11576. default:
  11577. return false;
  11578. }
  11579. if (!coopmat2 && !device->subgroup_shuffle) {
  11580. // scalar FA uses subgroupShuffle
  11581. return false;
  11582. }
  11583. return true;
  11584. }
  11585. case GGML_OP_GET_ROWS:
  11586. {
  11587. switch (op->src[0]->type) {
  11588. case GGML_TYPE_F32:
  11589. case GGML_TYPE_F16:
  11590. case GGML_TYPE_BF16:
  11591. case GGML_TYPE_Q4_0:
  11592. case GGML_TYPE_Q4_1:
  11593. case GGML_TYPE_Q5_0:
  11594. case GGML_TYPE_Q5_1:
  11595. case GGML_TYPE_Q8_0:
  11596. case GGML_TYPE_Q2_K:
  11597. case GGML_TYPE_Q3_K:
  11598. case GGML_TYPE_Q4_K:
  11599. case GGML_TYPE_Q5_K:
  11600. case GGML_TYPE_Q6_K:
  11601. case GGML_TYPE_IQ1_S:
  11602. case GGML_TYPE_IQ1_M:
  11603. case GGML_TYPE_IQ2_XXS:
  11604. case GGML_TYPE_IQ2_XS:
  11605. case GGML_TYPE_IQ2_S:
  11606. case GGML_TYPE_IQ3_XXS:
  11607. case GGML_TYPE_IQ3_S:
  11608. case GGML_TYPE_IQ4_XS:
  11609. case GGML_TYPE_IQ4_NL:
  11610. case GGML_TYPE_MXFP4:
  11611. return true;
  11612. default:
  11613. return false;
  11614. }
  11615. }
  11616. case GGML_OP_SET_ROWS:
  11617. {
  11618. switch (op->type) {
  11619. case GGML_TYPE_F32:
  11620. case GGML_TYPE_F16:
  11621. case GGML_TYPE_BF16:
  11622. case GGML_TYPE_Q4_0:
  11623. case GGML_TYPE_Q4_1:
  11624. case GGML_TYPE_Q5_0:
  11625. case GGML_TYPE_Q5_1:
  11626. case GGML_TYPE_Q8_0:
  11627. case GGML_TYPE_IQ4_NL:
  11628. return true;
  11629. default:
  11630. return false;
  11631. }
  11632. }
  11633. case GGML_OP_CONT:
  11634. case GGML_OP_CPY:
  11635. case GGML_OP_DUP:
  11636. {
  11637. ggml_type src0_type = op->src[0]->type;
  11638. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  11639. if (src0_type == GGML_TYPE_F32) {
  11640. switch (src1_type) {
  11641. case GGML_TYPE_F32:
  11642. case GGML_TYPE_F16:
  11643. case GGML_TYPE_BF16:
  11644. case GGML_TYPE_Q4_0:
  11645. case GGML_TYPE_Q4_1:
  11646. case GGML_TYPE_Q5_0:
  11647. case GGML_TYPE_Q5_1:
  11648. case GGML_TYPE_Q8_0:
  11649. case GGML_TYPE_IQ4_NL:
  11650. return true;
  11651. default:
  11652. break;
  11653. }
  11654. }
  11655. if (src1_type == GGML_TYPE_F32) {
  11656. switch (src0_type) {
  11657. case GGML_TYPE_F16:
  11658. case GGML_TYPE_Q4_0:
  11659. case GGML_TYPE_Q4_1:
  11660. case GGML_TYPE_Q5_0:
  11661. case GGML_TYPE_Q5_1:
  11662. case GGML_TYPE_Q8_0:
  11663. case GGML_TYPE_IQ4_NL:
  11664. return true;
  11665. default:
  11666. break;
  11667. }
  11668. }
  11669. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  11670. return true;
  11671. }
  11672. if (
  11673. (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) ||
  11674. (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32)
  11675. ) {
  11676. return true;
  11677. }
  11678. // We can handle copying from a type to the same type if it's
  11679. // contiguous (memcpy). We use f16 or f32 shaders to do the copy,
  11680. // so the type/block size must be a multiple of 4.
  11681. if (src0_type == src1_type &&
  11682. ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op) &&
  11683. (ggml_type_size(src0_type) % 2) == 0) {
  11684. return true;
  11685. }
  11686. return false;
  11687. }
  11688. case GGML_OP_REPEAT:
  11689. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  11690. case GGML_OP_REPEAT_BACK:
  11691. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32;
  11692. case GGML_OP_ROPE:
  11693. case GGML_OP_ROPE_BACK:
  11694. case GGML_OP_NONE:
  11695. case GGML_OP_RESHAPE:
  11696. case GGML_OP_VIEW:
  11697. case GGML_OP_PERMUTE:
  11698. case GGML_OP_TRANSPOSE:
  11699. case GGML_OP_RMS_NORM:
  11700. return true;
  11701. case GGML_OP_NORM:
  11702. case GGML_OP_GROUP_NORM:
  11703. case GGML_OP_L2_NORM:
  11704. return ggml_is_contiguous(op->src[0]);
  11705. case GGML_OP_ADD:
  11706. case GGML_OP_SUB:
  11707. case GGML_OP_MUL:
  11708. case GGML_OP_DIV:
  11709. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11710. (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
  11711. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  11712. case GGML_OP_ADD_ID:
  11713. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 &&
  11714. op->type == GGML_TYPE_F32;
  11715. case GGML_OP_SILU_BACK:
  11716. case GGML_OP_RMS_NORM_BACK:
  11717. case GGML_OP_SQR:
  11718. case GGML_OP_SQRT:
  11719. case GGML_OP_SIN:
  11720. case GGML_OP_COS:
  11721. case GGML_OP_CLAMP:
  11722. case GGML_OP_LEAKY_RELU:
  11723. case GGML_OP_OPT_STEP_ADAMW:
  11724. case GGML_OP_OPT_STEP_SGD:
  11725. return op->src[0]->type == GGML_TYPE_F32;
  11726. case GGML_OP_ARGSORT:
  11727. return op->ne[0] <= max_argsort_cols;
  11728. case GGML_OP_UPSCALE:
  11729. case GGML_OP_ACC:
  11730. case GGML_OP_CONCAT:
  11731. case GGML_OP_SCALE:
  11732. case GGML_OP_PAD:
  11733. case GGML_OP_ROLL:
  11734. case GGML_OP_DIAG_MASK_INF:
  11735. case GGML_OP_SOFT_MAX:
  11736. case GGML_OP_SOFT_MAX_BACK:
  11737. return true;
  11738. case GGML_OP_SUM:
  11739. case GGML_OP_SUM_ROWS:
  11740. case GGML_OP_MEAN:
  11741. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  11742. case GGML_OP_ARGMAX:
  11743. case GGML_OP_COUNT_EQUAL:
  11744. case GGML_OP_IM2COL:
  11745. case GGML_OP_IM2COL_3D:
  11746. case GGML_OP_TIMESTEP_EMBEDDING:
  11747. case GGML_OP_CONV_2D_DW:
  11748. case GGML_OP_POOL_2D:
  11749. case GGML_OP_RWKV_WKV6:
  11750. case GGML_OP_RWKV_WKV7:
  11751. return true;
  11752. case GGML_OP_SSM_SCAN:
  11753. {
  11754. for (int i = 0; i < 6; i++) {
  11755. if (op->src[i] && ggml_is_quantized(op->src[i]->type)) {
  11756. return false;
  11757. }
  11758. }
  11759. if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) {
  11760. return false;
  11761. }
  11762. if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
  11763. return false;
  11764. }
  11765. const uint32_t d_state = op->src[0]->ne[0];
  11766. const uint32_t head_dim = op->src[0]->ne[1];
  11767. bool is_mamba2 = (op->src[3] && op->src[3]->nb[1] == sizeof(float));
  11768. if (!is_mamba2) {
  11769. return false;
  11770. }
  11771. if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
  11772. return false;
  11773. }
  11774. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11775. const vk_device& device = ggml_vk_get_device(ctx->device);
  11776. const uint32_t SPLIT_H = 16;
  11777. size_t stateC_size = SPLIT_H * d_state * sizeof(float);
  11778. if (stateC_size > device->properties.limits.maxComputeSharedMemorySize) {
  11779. return false;
  11780. }
  11781. return true;
  11782. }
  11783. case GGML_OP_SSM_CONV:
  11784. return true;
  11785. case GGML_OP_CONV_TRANSPOSE_1D:
  11786. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  11787. case GGML_OP_CONV_2D:
  11788. case GGML_OP_CONV_TRANSPOSE_2D:
  11789. {
  11790. // Op is disabled for Apple because it segfaults at pipeline create time on MoltenVK
  11791. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11792. const vk_device& device = ggml_vk_get_device(ctx->device);
  11793. if (op->op == GGML_OP_CONV_TRANSPOSE_2D &&
  11794. device->properties.limits.maxPushConstantsSize < sizeof(vk_op_conv_transpose_2d_push_constants)) {
  11795. return false;
  11796. }
  11797. // Channel-contiguous format is not supported yet.
  11798. return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11799. op->src[1]->type == GGML_TYPE_F32 &&
  11800. op->type == GGML_TYPE_F32 &&
  11801. ggml_is_contiguous(op->src[0]) &&
  11802. ggml_is_contiguous(op->src[1]) &&
  11803. ggml_is_contiguous(op));
  11804. }
  11805. default:
  11806. return false;
  11807. }
  11808. UNUSED(dev);
  11809. }
  11810. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  11811. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  11812. return false;
  11813. }
  11814. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11815. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  11816. return buft_ctx->device->idx == ctx->device;
  11817. }
  11818. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  11819. const int min_batch_size = 32;
  11820. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  11821. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  11822. UNUSED(dev);
  11823. }
  11824. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  11825. /* .get_name = */ ggml_backend_vk_device_get_name,
  11826. /* .get_description = */ ggml_backend_vk_device_get_description,
  11827. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  11828. /* .get_type = */ ggml_backend_vk_device_get_type,
  11829. /* .get_props = */ ggml_backend_vk_device_get_props,
  11830. /* .init_backend = */ ggml_backend_vk_device_init,
  11831. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  11832. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  11833. /* .buffer_from_host_ptr = */ NULL,
  11834. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  11835. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  11836. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  11837. /* .event_new = */ NULL,
  11838. /* .event_free = */ NULL,
  11839. /* .event_synchronize = */ NULL,
  11840. };
  11841. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  11842. UNUSED(reg);
  11843. return GGML_VK_NAME;
  11844. }
  11845. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  11846. UNUSED(reg);
  11847. return ggml_backend_vk_get_device_count();
  11848. }
  11849. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  11850. static std::vector<ggml_backend_dev_t> devices;
  11851. static bool initialized = false;
  11852. {
  11853. static std::mutex mutex;
  11854. std::lock_guard<std::mutex> lock(mutex);
  11855. if (!initialized) {
  11856. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  11857. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  11858. char desc[256];
  11859. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  11860. ctx->device = i;
  11861. ctx->name = GGML_VK_NAME + std::to_string(i);
  11862. ctx->description = desc;
  11863. ctx->is_integrated_gpu = ggml_backend_vk_get_device_type(i) == vk::PhysicalDeviceType::eIntegratedGpu;
  11864. ctx->pci_bus_id = ggml_backend_vk_get_device_pci_id(i);
  11865. devices.push_back(new ggml_backend_device {
  11866. /* .iface = */ ggml_backend_vk_device_i,
  11867. /* .reg = */ reg,
  11868. /* .context = */ ctx,
  11869. });
  11870. }
  11871. initialized = true;
  11872. }
  11873. }
  11874. GGML_ASSERT(device < devices.size());
  11875. return devices[device];
  11876. }
  11877. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  11878. /* .get_name = */ ggml_backend_vk_reg_get_name,
  11879. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  11880. /* .get_device = */ ggml_backend_vk_reg_get_device,
  11881. /* .get_proc_address = */ NULL,
  11882. };
  11883. ggml_backend_reg_t ggml_backend_vk_reg() {
  11884. static ggml_backend_reg reg = {
  11885. /* .api_version = */ GGML_BACKEND_API_VERSION,
  11886. /* .iface = */ ggml_backend_vk_reg_i,
  11887. /* .context = */ nullptr,
  11888. };
  11889. try {
  11890. ggml_vk_instance_init();
  11891. return &reg;
  11892. } catch (const vk::SystemError& e) {
  11893. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what());
  11894. return nullptr;
  11895. } catch (const std::exception &e) {
  11896. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: " << e.what());
  11897. return nullptr;
  11898. } catch (...) {
  11899. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: unknown exception during Vulkan init");
  11900. return nullptr;
  11901. }
  11902. }
  11903. // Extension availability
  11904. static bool ggml_vk_instance_validation_ext_available() {
  11905. #ifdef GGML_VULKAN_VALIDATE
  11906. // Check if validation layer provides the extension
  11907. const std::string layer_name = "VK_LAYER_KHRONOS_validation";
  11908. for (const auto& layer : vk::enumerateInstanceLayerProperties()) {
  11909. if (layer_name == layer.layerName.data()) {
  11910. for (const auto& ext : vk::enumerateInstanceExtensionProperties(layer_name)) {
  11911. if (strcmp("VK_EXT_validation_features", ext.extensionName.data()) == 0) {
  11912. return true;
  11913. }
  11914. }
  11915. }
  11916. }
  11917. std::cerr << "ggml_vulkan: WARNING: Validation layer or layer extension VK_EXT_validation_features not found." << std::endl;
  11918. #endif
  11919. return false;
  11920. }
  11921. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  11922. #ifdef __APPLE__
  11923. // Check for portability enumeration extension for MoltenVK support
  11924. for (const auto& properties : instance_extensions) {
  11925. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  11926. return true;
  11927. }
  11928. }
  11929. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  11930. #endif
  11931. return false;
  11932. UNUSED(instance_extensions);
  11933. }
  11934. // Extension availability
  11935. static bool ggml_vk_instance_debug_utils_ext_available(
  11936. const std::vector<vk::ExtensionProperties> & instance_extensions) {
  11937. // Check for portability enumeration extension for MoltenVK support
  11938. for (const auto & properties : instance_extensions) {
  11939. if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) {
  11940. return true;
  11941. }
  11942. }
  11943. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl;
  11944. return false;
  11945. UNUSED(instance_extensions);
  11946. }
  11947. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev) {
  11948. VkPhysicalDeviceFeatures2 device_features2;
  11949. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  11950. VkPhysicalDeviceVulkan11Features vk11_features;
  11951. vk11_features.pNext = nullptr;
  11952. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  11953. device_features2.pNext = &vk11_features;
  11954. vkGetPhysicalDeviceFeatures2(vkdev, &device_features2);
  11955. return vk11_features.storageBuffer16BitAccess;
  11956. }
  11957. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) {
  11958. switch (props.vendorID) {
  11959. case VK_VENDOR_ID_INTEL:
  11960. // Only allowing Xe2 GPU at the moment since Xe2 GPU can gain significant performance boost,
  11961. // while some older hardware (ex. Arc A770) has performance regressions
  11962. return arch == vk_device_architecture::INTEL_XE2;
  11963. case VK_VENDOR_ID_AMD:
  11964. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  11965. // Workaround for AMD proprietary driver reporting support on all GPUs
  11966. return arch == vk_device_architecture::AMD_RDNA3;
  11967. }
  11968. return true;
  11969. default:
  11970. return true;
  11971. }
  11972. }
  11973. // checks
  11974. #ifdef GGML_VULKAN_CHECK_RESULTS
  11975. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  11976. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  11977. return;
  11978. }
  11979. for (int j = 0; j < level; j++) {
  11980. std::cerr << " ";
  11981. }
  11982. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  11983. done.push_back(tensor);
  11984. for (int i = 0; i < GGML_MAX_SRC; i++) {
  11985. if (tensor->src[i] != nullptr) {
  11986. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  11987. }
  11988. }
  11989. }
  11990. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  11991. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  11992. return;
  11993. }
  11994. i0 = std::max(i0, 5);
  11995. i1 = std::max(i1, 5);
  11996. i2 = std::max(i2, 0);
  11997. i3 = std::max(i3, 0);
  11998. fprintf(stderr, " ");
  11999. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12000. fprintf(stderr, "%7d ", idx1);
  12001. }
  12002. fprintf(stderr, "\n");
  12003. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  12004. fprintf(stderr, "%7d: ", idx0);
  12005. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12006. 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]) {
  12007. float val;
  12008. if (tensor->type == GGML_TYPE_F32) {
  12009. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12010. } else if (tensor->type == GGML_TYPE_F16) {
  12011. 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]));
  12012. } else if (tensor->type == GGML_TYPE_I32) {
  12013. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12014. } else {
  12015. GGML_ABORT("fatal error");
  12016. }
  12017. fprintf(stderr, "% 7.2f ", val);
  12018. } else {
  12019. fprintf(stderr, " ");
  12020. }
  12021. }
  12022. fprintf(stderr, "\n");
  12023. }
  12024. }
  12025. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  12026. void * tensor_data = tensor->data;
  12027. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  12028. if (is_gpu) {
  12029. const size_t tensor_size = ggml_nbytes(tensor);
  12030. tensor_data = malloc(tensor_size);
  12031. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12032. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  12033. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  12034. }
  12035. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  12036. 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;
  12037. if (tensor->src[0] != nullptr) {
  12038. 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;
  12039. }
  12040. if (tensor->src[1] != nullptr) {
  12041. 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;
  12042. }
  12043. std::cerr << std::endl << "Result:" << std::endl;
  12044. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  12045. std::cerr << std::endl;
  12046. std::vector<const ggml_tensor *> done;
  12047. ggml_vk_print_graph_origin(tensor, done);
  12048. if (is_gpu) {
  12049. free(tensor_data);
  12050. }
  12051. }
  12052. void * comp_result;
  12053. size_t comp_size;
  12054. size_t comp_nb[GGML_MAX_DIMS];
  12055. size_t check_counter = 0;
  12056. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12057. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  12058. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12059. return;
  12060. }
  12061. check_counter++;
  12062. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12063. return;
  12064. }
  12065. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  12066. struct ggml_init_params iparams = {
  12067. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  12068. /*.mem_buffer =*/ NULL,
  12069. /*.no_alloc =*/ false,
  12070. };
  12071. struct ggml_context * ggml_ctx = ggml_init(iparams);
  12072. std::array<struct ggml_tensor *, GGML_MAX_SRC> src_clone = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  12073. const char * srci_name[GGML_MAX_SRC] = {"src0", "src1", "src2", "src3", "src4", "src5", "src6", "src7", "src8", "src9"};
  12074. std::map<ggml_tensor *, ggml_tensor *> cloned_tensors;
  12075. std::vector<void *> cloned_mallocs;
  12076. struct ggml_tensor * tensor_clone = nullptr;
  12077. for (int f = 0; f < ctx->num_additional_fused_ops + 1; ++f) {
  12078. tensor = cgraph->nodes[tensor_idx + f];
  12079. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12080. ggml_tensor * srci = tensor->src[i];
  12081. if (srci == nullptr) {
  12082. continue;
  12083. }
  12084. // If a src tensor has been cloned, use that one
  12085. auto it = cloned_tensors.find(srci);
  12086. if (it != cloned_tensors.end()) {
  12087. src_clone[i] = it->second;
  12088. continue;
  12089. }
  12090. ggml_tensor * srci_clone = ggml_dup_tensor(ggml_ctx, srci);
  12091. size_t srci_size = ggml_nbytes(srci);
  12092. src_clone[i] = srci_clone;
  12093. void *src_buffer = malloc(srci_size);
  12094. cloned_mallocs.push_back(src_buffer);
  12095. srci_clone->data = src_buffer;
  12096. if (ggml_backend_buffer_is_host(srci->buffer)) {
  12097. memcpy(srci_clone->data, srci->data, srci_size);
  12098. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12099. } else if (ggml_backend_buffer_is_vk(srci->buffer)) {
  12100. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)srci->buffer->context;
  12101. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12102. uint64_t offset = vk_tensor_offset(srci) + srci->view_offs;
  12103. if (!ggml_is_contiguous(srci) && ggml_vk_dim01_contiguous(srci)) {
  12104. for (int i3 = 0; i3 < srci->ne[3]; i3++) {
  12105. for (int i2 = 0; i2 < srci->ne[2]; i2++) {
  12106. const int idx = i3*srci->ne[2] + i2;
  12107. 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]);
  12108. }
  12109. }
  12110. srci_clone->nb[0] = srci->nb[0];
  12111. srci_clone->nb[1] = srci->nb[1];
  12112. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  12113. srci_clone->nb[i] = srci_clone->nb[i - 1]*srci_clone->ne[i - 1];
  12114. }
  12115. } else {
  12116. if (offset + srci_size >= buffer_gpu->size) {
  12117. srci_size = buffer_gpu->size - offset;
  12118. }
  12119. ggml_vk_buffer_read(buffer_gpu, offset, srci_clone->data, srci_size);
  12120. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12121. }
  12122. } else {
  12123. GGML_ABORT("fatal error");
  12124. }
  12125. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12126. ggml_vk_print_tensor(srci, srci_name[i]);
  12127. }
  12128. }
  12129. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  12130. const float * params = (const float *)tensor->op_params;
  12131. 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]);
  12132. if (src_clone[4]) {
  12133. ggml_flash_attn_ext_add_sinks(tensor_clone, src_clone[4]);
  12134. }
  12135. } else if (tensor->op == GGML_OP_MUL_MAT) {
  12136. tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
  12137. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  12138. tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12139. } else if (tensor->op == GGML_OP_SUB) {
  12140. tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
  12141. } else if (tensor->op == GGML_OP_MUL) {
  12142. tensor_clone = ggml_mul(ggml_ctx, src_clone[0], src_clone[1]);
  12143. } else if (tensor->op == GGML_OP_DIV) {
  12144. tensor_clone = ggml_div(ggml_ctx, src_clone[0], src_clone[1]);
  12145. } else if (tensor->op == GGML_OP_CONCAT) {
  12146. tensor_clone = ggml_concat(ggml_ctx, src_clone[0], src_clone[1], *(int *)tensor->op_params);
  12147. } else if (tensor->op == GGML_OP_UPSCALE) {
  12148. 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]);
  12149. } else if (tensor->op == GGML_OP_SCALE) {
  12150. const float * params = (const float *)tensor->op_params;
  12151. tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]);
  12152. } else if (tensor->op == GGML_OP_SQR) {
  12153. tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]);
  12154. } else if (tensor->op == GGML_OP_SQRT) {
  12155. tensor_clone = ggml_sqrt(ggml_ctx, src_clone[0]);
  12156. } else if (tensor->op == GGML_OP_SIN) {
  12157. tensor_clone = ggml_sin(ggml_ctx, src_clone[0]);
  12158. } else if (tensor->op == GGML_OP_COS) {
  12159. tensor_clone = ggml_cos(ggml_ctx, src_clone[0]);
  12160. } else if (tensor->op == GGML_OP_CLAMP) {
  12161. const float * params = (const float *)tensor->op_params;
  12162. tensor_clone = ggml_clamp(ggml_ctx, src_clone[0], params[0], params[1]);
  12163. } else if (tensor->op == GGML_OP_PAD) {
  12164. 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],
  12165. tensor->op_params[4], tensor->op_params[5], tensor->op_params[6], tensor->op_params[7]);
  12166. } else if (tensor->op == GGML_OP_REPEAT) {
  12167. tensor_clone = ggml_repeat(ggml_ctx, src_clone[0], tensor);
  12168. } else if (tensor->op == GGML_OP_REPEAT_BACK) {
  12169. tensor_clone = ggml_repeat_back(ggml_ctx, src_clone[0], tensor);
  12170. } else if (tensor->op == GGML_OP_ADD) {
  12171. tensor_clone = ggml_add(ggml_ctx, src_clone[0], src_clone[1]);
  12172. } else if (tensor->op == GGML_OP_ACC) {
  12173. 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]);
  12174. } else if (tensor->op == GGML_OP_NORM) {
  12175. tensor_clone = ggml_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12176. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  12177. const float * float_params = (const float *)tensor->op_params;
  12178. tensor_clone = ggml_group_norm(ggml_ctx, src_clone[0], tensor->op_params[0], float_params[1]);
  12179. } else if (tensor->op == GGML_OP_RMS_NORM) {
  12180. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12181. } else if (tensor->op == GGML_OP_RMS_NORM_BACK) {
  12182. const float eps = ((float *) tensor->op_params)[0];
  12183. tensor_clone = ggml_rms_norm_back(ggml_ctx, src_clone[0], src_clone[1], eps);
  12184. } else if (tensor->op == GGML_OP_SILU_BACK) {
  12185. tensor_clone = ggml_silu_back(ggml_ctx, src_clone[0], src_clone[1]);
  12186. } else if (tensor->op == GGML_OP_L2_NORM) {
  12187. const float eps = ((float *) tensor->op_params)[0];
  12188. tensor_clone = ggml_l2_norm(ggml_ctx, src_clone[0], eps);
  12189. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  12190. if (tensor->src[1] != nullptr) {
  12191. const float * params = (const float *)tensor->op_params;
  12192. tensor_clone = ggml_soft_max_ext(ggml_ctx, src_clone[0], src_clone[1], params[0], params[1]);
  12193. } else {
  12194. tensor_clone = ggml_soft_max(ggml_ctx, src_clone[0]);
  12195. }
  12196. } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) {
  12197. 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]);
  12198. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  12199. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]);
  12200. } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) {
  12201. const int n_dims = ((int32_t *) tensor->op_params)[1];
  12202. const int mode = ((int32_t *) tensor->op_params)[2];
  12203. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  12204. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  12205. const float freq_base = ((float *) tensor->op_params)[5];
  12206. const float freq_scale = ((float *) tensor->op_params)[6];
  12207. const float ext_factor = ((float *) tensor->op_params)[7];
  12208. const float attn_factor = ((float *) tensor->op_params)[8];
  12209. const float beta_fast = ((float *) tensor->op_params)[9];
  12210. const float beta_slow = ((float *) tensor->op_params)[10];
  12211. if (mode & GGML_ROPE_TYPE_MROPE) {
  12212. int32_t *sections = ((int32_t *) tensor->op_params) + 11;
  12213. if (tensor->op == GGML_OP_ROPE) {
  12214. 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);
  12215. } else {
  12216. 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);
  12217. }
  12218. } else {
  12219. if (tensor->op == GGML_OP_ROPE) {
  12220. 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);
  12221. } else {
  12222. 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);
  12223. }
  12224. }
  12225. } else if (tensor->op == GGML_OP_UNARY) {
  12226. switch (ggml_get_unary_op(tensor)) {
  12227. case GGML_UNARY_OP_EXP:
  12228. tensor_clone = ggml_exp(ggml_ctx, src_clone[0]);
  12229. break;
  12230. case GGML_UNARY_OP_SILU:
  12231. tensor_clone = ggml_silu(ggml_ctx, src_clone[0]);
  12232. break;
  12233. case GGML_UNARY_OP_GELU:
  12234. tensor_clone = ggml_gelu(ggml_ctx, src_clone[0]);
  12235. break;
  12236. case GGML_UNARY_OP_GELU_ERF:
  12237. tensor_clone = ggml_gelu_erf(ggml_ctx, src_clone[0]);
  12238. break;
  12239. case GGML_UNARY_OP_GELU_QUICK:
  12240. tensor_clone = ggml_gelu_quick(ggml_ctx, src_clone[0]);
  12241. break;
  12242. case GGML_UNARY_OP_RELU:
  12243. tensor_clone = ggml_relu(ggml_ctx, src_clone[0]);
  12244. break;
  12245. case GGML_UNARY_OP_TANH:
  12246. tensor_clone = ggml_tanh(ggml_ctx, src_clone[0]);
  12247. break;
  12248. case GGML_UNARY_OP_SIGMOID:
  12249. tensor_clone = ggml_sigmoid(ggml_ctx, src_clone[0]);
  12250. break;
  12251. case GGML_UNARY_OP_HARDSIGMOID:
  12252. tensor_clone = ggml_hardsigmoid(ggml_ctx, src_clone[0]);
  12253. break;
  12254. case GGML_UNARY_OP_HARDSWISH:
  12255. tensor_clone = ggml_hardswish(ggml_ctx, src_clone[0]);
  12256. break;
  12257. default:
  12258. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12259. GGML_ABORT("fatal error");
  12260. }
  12261. } else if (tensor->op == GGML_OP_GLU) {
  12262. if (src_clone[1] == nullptr) {
  12263. tensor_clone = ggml_glu(ggml_ctx, src_clone[0], (ggml_glu_op) tensor->op_params[0], tensor->op_params[1]);
  12264. } else {
  12265. tensor_clone = ggml_glu_split(ggml_ctx, src_clone[0], src_clone[1], (ggml_glu_op) tensor->op_params[0]);
  12266. }
  12267. ggml_set_op_params_i32(tensor_clone, 2, ggml_get_op_params_i32(tensor, 2));
  12268. ggml_set_op_params_i32(tensor_clone, 3, ggml_get_op_params_i32(tensor, 3));
  12269. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  12270. if (tensor->src[1] == nullptr) {
  12271. tensor_clone = ggml_dup(ggml_ctx, src_clone[0]);
  12272. tensor_clone->type = tensor->type;
  12273. } else {
  12274. tensor_clone = ggml_cpy(ggml_ctx, src_clone[0], src_clone[1]);
  12275. }
  12276. } else if (tensor->op == GGML_OP_CONT) {
  12277. tensor_clone = ggml_cont_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12278. } else if (tensor->op == GGML_OP_RESHAPE) {
  12279. tensor_clone = ggml_reshape_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12280. } else if (tensor->op == GGML_OP_VIEW) {
  12281. 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]);
  12282. } else if (tensor->op == GGML_OP_PERMUTE) {
  12283. int32_t * params = (int32_t *)tensor->op_params;
  12284. tensor_clone = ggml_permute(ggml_ctx, src_clone[0], params[0], params[1], params[2], params[3]);
  12285. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  12286. tensor_clone = ggml_transpose(ggml_ctx, src_clone[0]);
  12287. } else if (tensor->op == GGML_OP_GET_ROWS) {
  12288. tensor_clone = ggml_get_rows(ggml_ctx, src_clone[0], src_clone[1]);
  12289. } else if (tensor->op == GGML_OP_ARGSORT) {
  12290. tensor_clone = ggml_argsort(ggml_ctx, src_clone[0], (ggml_sort_order) *(int *)tensor->op_params);
  12291. } else if (tensor->op == GGML_OP_SUM) {
  12292. tensor_clone = ggml_sum(ggml_ctx, src_clone[0]);
  12293. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  12294. tensor_clone = ggml_sum_rows(ggml_ctx, src_clone[0]);
  12295. } else if (tensor->op == GGML_OP_MEAN) {
  12296. tensor_clone = ggml_mean(ggml_ctx, src_clone[0]);
  12297. } else if (tensor->op == GGML_OP_ARGMAX) {
  12298. tensor_clone = ggml_argmax(ggml_ctx, src_clone[0]);
  12299. } else if (tensor->op == GGML_OP_COUNT_EQUAL) {
  12300. tensor_clone = ggml_count_equal(ggml_ctx, src_clone[0], src_clone[1]);
  12301. } else if (tensor->op == GGML_OP_IM2COL) {
  12302. const int32_t s0 = tensor->op_params[0];
  12303. const int32_t s1 = tensor->op_params[1];
  12304. const int32_t p0 = tensor->op_params[2];
  12305. const int32_t p1 = tensor->op_params[3];
  12306. const int32_t d0 = tensor->op_params[4];
  12307. const int32_t d1 = tensor->op_params[5];
  12308. const bool is_2D = tensor->op_params[6] == 1;
  12309. tensor_clone = ggml_im2col(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  12310. } else if (tensor->op == GGML_OP_IM2COL_3D) {
  12311. const int32_t s0 = tensor->op_params[0];
  12312. const int32_t s1 = tensor->op_params[1];
  12313. const int32_t s2 = tensor->op_params[2];
  12314. const int32_t p0 = tensor->op_params[3];
  12315. const int32_t p1 = tensor->op_params[4];
  12316. const int32_t p2 = tensor->op_params[5];
  12317. const int32_t d0 = tensor->op_params[6];
  12318. const int32_t d1 = tensor->op_params[7];
  12319. const int32_t d2 = tensor->op_params[8];
  12320. const int32_t IC = tensor->op_params[9];
  12321. 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);
  12322. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  12323. const int32_t dim = tensor->op_params[0];
  12324. const int32_t max_period = tensor->op_params[1];
  12325. tensor_clone = ggml_timestep_embedding(ggml_ctx, src_clone[0], dim, max_period);
  12326. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_1D){
  12327. const int32_t s0 = tensor->op_params[0];
  12328. const int32_t p0 = tensor->op_params[1];
  12329. const int32_t d0 = tensor->op_params[2];
  12330. tensor_clone = ggml_conv_transpose_1d(ggml_ctx, src_clone[0], src_clone[1], s0, p0, d0);
  12331. } else if (tensor->op == GGML_OP_POOL_2D) {
  12332. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  12333. const int32_t k0 = tensor->op_params[1];
  12334. const int32_t k1 = tensor->op_params[2];
  12335. const int32_t s0 = tensor->op_params[3];
  12336. const int32_t s1 = tensor->op_params[4];
  12337. const int32_t p0 = tensor->op_params[5];
  12338. const int32_t p1 = tensor->op_params[6];
  12339. tensor_clone = ggml_pool_2d(ggml_ctx, src_clone[0], op, k0, k1, s0, s1, p0, p1);
  12340. } else if (tensor->op == GGML_OP_CONV_2D) {
  12341. const int32_t s0 = tensor->op_params[0];
  12342. const int32_t s1 = tensor->op_params[1];
  12343. const int32_t p0 = tensor->op_params[2];
  12344. const int32_t p1 = tensor->op_params[3];
  12345. const int32_t d0 = tensor->op_params[4];
  12346. const int32_t d1 = tensor->op_params[5];
  12347. tensor_clone = ggml_conv_2d(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  12348. } else if (tensor->op == GGML_OP_CONV_2D_DW) {
  12349. const int32_t s0 = tensor->op_params[0];
  12350. const int32_t s1 = tensor->op_params[1];
  12351. const int32_t p0 = tensor->op_params[2];
  12352. const int32_t p1 = tensor->op_params[3];
  12353. const int32_t d0 = tensor->op_params[4];
  12354. const int32_t d1 = tensor->op_params[5];
  12355. tensor_clone = ggml_conv_2d_dw_direct(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  12356. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_2D) {
  12357. const int32_t s = tensor->op_params[0];
  12358. tensor_clone = ggml_conv_transpose_2d_p0(ggml_ctx, src_clone[0], src_clone[1], s);
  12359. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  12360. const float * op_params = (const float *)tensor->op_params;
  12361. tensor_clone = ggml_leaky_relu(ggml_ctx, src_clone[0], op_params[0], false);
  12362. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  12363. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, src_clone[0], src_clone[1],
  12364. src_clone[2], src_clone[3], src_clone[4], src_clone[5]);
  12365. } else if (tensor->op == GGML_OP_RWKV_WKV7) {
  12366. tensor_clone = ggml_rwkv_wkv7(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3],
  12367. src_clone[4], src_clone[5], src_clone[6]);
  12368. } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
  12369. src_clone[0]->flags = tensor->src[0]->flags;
  12370. tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
  12371. src_clone[2], src_clone[3], src_clone[4]);
  12372. } else if (tensor->op == GGML_OP_OPT_STEP_SGD) {
  12373. src_clone[0]->flags = tensor->src[0]->flags;
  12374. tensor_clone = ggml_opt_step_sgd(ggml_ctx, src_clone[0], src_clone[1],
  12375. src_clone[2]);
  12376. } else if (tensor->op == GGML_OP_ADD_ID) {
  12377. tensor_clone = ggml_add_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12378. } else if (tensor->op == GGML_OP_SSM_SCAN) {
  12379. tensor_clone = ggml_ssm_scan(ggml_ctx, src_clone[0], src_clone[1], src_clone[2],
  12380. src_clone[3], src_clone[4], src_clone[5], src_clone[6]);
  12381. } else if (tensor->op == GGML_OP_SSM_CONV) {
  12382. tensor_clone = ggml_ssm_conv(ggml_ctx, src_clone[0], src_clone[1]);
  12383. } else if (tensor->op == GGML_OP_ROLL) {
  12384. const int32_t s0 = tensor->op_params[0];
  12385. const int32_t s1 = tensor->op_params[1];
  12386. const int32_t s2 = tensor->op_params[2];
  12387. const int32_t s3 = tensor->op_params[3];
  12388. tensor_clone = ggml_roll(ggml_ctx, src_clone[0], s0, s1, s2, s3);
  12389. }
  12390. else {
  12391. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12392. GGML_ABORT("fatal error");
  12393. }
  12394. cloned_tensors[tensor] = tensor_clone;
  12395. }
  12396. ggml_cgraph * cgraph_cpu = ggml_new_graph(ggml_ctx);
  12397. ggml_build_forward_expand(cgraph_cpu, tensor_clone);
  12398. ggml_graph_compute_with_ctx(ggml_ctx, cgraph_cpu, 8);
  12399. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12400. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  12401. }
  12402. comp_size = ggml_nbytes(tensor_clone);
  12403. comp_result = malloc(comp_size);
  12404. memcpy(comp_result, tensor_clone->data, comp_size);
  12405. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12406. for (auto m : cloned_mallocs) {
  12407. free(m);
  12408. }
  12409. ggml_free(ggml_ctx);
  12410. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  12411. }
  12412. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12413. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  12414. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12415. return;
  12416. }
  12417. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12418. return;
  12419. }
  12420. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  12421. ggml_tensor * src0 = tensor->src[0];
  12422. ggml_tensor * src1 = tensor->src[1];
  12423. ggml_tensor * src2 = tensor->src[2];
  12424. ggml_tensor * src3 = tensor->src[3];
  12425. void * tensor_data = tensor->data;
  12426. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  12427. size_t tensor_size = ggml_nbytes(tensor);
  12428. tensor_data = malloc(tensor_size);
  12429. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12430. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12431. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  12432. if (offset + tensor_size >= buffer_gpu->size) {
  12433. tensor_size = buffer_gpu->size - offset;
  12434. }
  12435. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  12436. }
  12437. float first_error_result = -1.0f;
  12438. float first_error_correct = -1.0f;
  12439. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  12440. double avg_err = 0.0;
  12441. size_t counter = 0;
  12442. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  12443. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  12444. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  12445. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  12446. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  12447. float correct = 0.0f;
  12448. float result = 0.0f;
  12449. if (buffer_size_fit) {
  12450. if (tensor->type == GGML_TYPE_F32) {
  12451. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12452. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12453. } else if (tensor->type == GGML_TYPE_F16) {
  12454. 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]));
  12455. 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]));
  12456. } else if (tensor->type == GGML_TYPE_BF16) {
  12457. 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]));
  12458. 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]));
  12459. } else if (tensor->type == GGML_TYPE_I32) {
  12460. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12461. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12462. } else if (tensor->type == GGML_TYPE_I64) {
  12463. correct = *(int64_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12464. result = *(int64_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12465. } else {
  12466. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  12467. }
  12468. } else {
  12469. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  12470. GGML_ABORT("fatal error");
  12471. }
  12472. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  12473. 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;
  12474. 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;
  12475. if (src0 != nullptr) {
  12476. 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;
  12477. }
  12478. if (src1 != nullptr) {
  12479. 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;
  12480. }
  12481. if (src2 != nullptr) {
  12482. 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;
  12483. }
  12484. if (src3 != nullptr) {
  12485. 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;
  12486. }
  12487. 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;
  12488. std::cerr << std::endl << "Result:" << std::endl;
  12489. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  12490. std::cerr << std::endl << "Correct:" << std::endl;
  12491. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  12492. std::cerr << std::endl;
  12493. std::vector<const ggml_tensor *> done;
  12494. ggml_vk_print_graph_origin(tensor, done);
  12495. GGML_ABORT("fatal error");
  12496. }
  12497. const double denom = std::fabs(correct) > 1.0f ? (std::fabs(correct) > 1e-8 ? std::fabs(correct) : 1e-8) : 1.0f;
  12498. if (first_error[0] == -1 && std::fabs(correct - result) / denom > 0.5) {
  12499. first_error[0] = i0;
  12500. first_error[1] = i1;
  12501. first_error[2] = i2;
  12502. first_error[3] = i3;
  12503. first_error_result = result;
  12504. first_error_correct = correct;
  12505. }
  12506. // Special case, value is infinite, avoid NaN result in avg_err
  12507. // NaN also appears in results, if both are nan error is 0
  12508. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  12509. avg_err += std::fabs(correct - result) / denom;
  12510. }
  12511. counter++;
  12512. }
  12513. }
  12514. }
  12515. }
  12516. avg_err /= counter;
  12517. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12518. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  12519. 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;
  12520. if (src0 != nullptr) {
  12521. 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;
  12522. }
  12523. if (src1 != nullptr) {
  12524. 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;
  12525. }
  12526. if (src2 != nullptr) {
  12527. 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;
  12528. }
  12529. if (src3 != nullptr) {
  12530. 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;
  12531. }
  12532. 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;
  12533. std::cerr << std::endl << "Result:" << std::endl;
  12534. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  12535. std::cerr << std::endl << "Correct:" << std::endl;
  12536. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  12537. std::cerr << std::endl;
  12538. std::vector<const ggml_tensor *> done;
  12539. ggml_vk_print_graph_origin(tensor, done);
  12540. }
  12541. if (avg_err > 0.5 || std::isnan(avg_err)) {
  12542. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  12543. 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;
  12544. if (src0 != nullptr) {
  12545. 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;
  12546. }
  12547. if (src1 != nullptr) {
  12548. 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;
  12549. }
  12550. if (src2 != nullptr) {
  12551. 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;
  12552. }
  12553. if (src3 != nullptr) {
  12554. 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;
  12555. }
  12556. 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;
  12557. std::cerr << std::endl << "Result:" << std::endl;
  12558. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  12559. std::cerr << std::endl << "Correct:" << std::endl;
  12560. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  12561. std::cerr << std::endl;
  12562. std::vector<const ggml_tensor *> done;
  12563. ggml_vk_print_graph_origin(tensor, done);
  12564. GGML_ABORT("fatal error");
  12565. } else {
  12566. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  12567. }
  12568. free(comp_result);
  12569. comp_result = nullptr;
  12570. comp_size = 0;
  12571. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  12572. free(tensor_data);
  12573. }
  12574. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  12575. }
  12576. #endif
  12577. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)