ggml-vulkan.cpp 726 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648
  1. #include "ggml-vulkan.h"
  2. #include <vulkan/vulkan_core.h>
  3. #if defined(GGML_VULKAN_RUN_TESTS) || defined(GGML_VULKAN_CHECK_RESULTS)
  4. #include <chrono>
  5. #include "ggml-cpu.h"
  6. #endif
  7. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  8. #define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
  9. // We use VULKAN_HPP_DEFAULT_DISPATCHER, but not VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
  10. // to avoid conflicts with applications or other libraries who might use it.
  11. #if VK_HEADER_VERSION >= 301
  12. namespace vk::detail { class DispatchLoaderDynamic; }
  13. using vk::detail::DispatchLoaderDynamic;
  14. #else
  15. namespace vk { class DispatchLoaderDynamic; }
  16. using vk::DispatchLoaderDynamic;
  17. #endif
  18. DispatchLoaderDynamic & ggml_vk_default_dispatcher();
  19. #define VULKAN_HPP_DEFAULT_DISPATCHER ggml_vk_default_dispatcher()
  20. #include <vulkan/vulkan.hpp>
  21. #include <algorithm>
  22. #include <cmath>
  23. #include <iomanip>
  24. #include <iostream>
  25. #include <tuple>
  26. #include <vector>
  27. #include <sstream>
  28. #include <utility>
  29. #include <memory>
  30. #include <limits>
  31. #include <map>
  32. #include <set>
  33. #include <unordered_map>
  34. #include <memory>
  35. #include <mutex>
  36. #include <future>
  37. #include <thread>
  38. #if defined(_MSC_VER)
  39. # define NOMINMAX 1
  40. # include <windows.h>
  41. # define YIELD() YieldProcessor()
  42. #elif defined(__clang__) || defined(__GNUC__)
  43. # if defined(__x86_64__) ||defined(__i386__)
  44. # include <immintrin.h>
  45. # define YIELD() _mm_pause()
  46. # elif defined(__arm__) || defined(__aarch64__)
  47. # if defined(__clang__)
  48. # include <arm_acle.h>
  49. # define YIELD() __yield()
  50. # else
  51. # define YIELD() asm volatile("yield")
  52. # endif
  53. # endif
  54. #endif
  55. #if !defined(YIELD)
  56. #define YIELD()
  57. #endif
  58. #include "ggml-impl.h"
  59. #include "ggml-backend-impl.h"
  60. #include "ggml-vulkan-shaders.hpp"
  61. // remove this once it's more widely available in the SDK
  62. #if !defined(VK_KHR_shader_bfloat16)
  63. #define VK_KHR_shader_bfloat16 1
  64. #define VK_KHR_SHADER_BFLOAT16_SPEC_VERSION 1
  65. #define VK_KHR_SHADER_BFLOAT16_EXTENSION_NAME "VK_KHR_shader_bfloat16"
  66. #define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR ((VkStructureType)1000141000)
  67. #define VK_COMPONENT_TYPE_BFLOAT16_KHR ((VkComponentTypeKHR)1000141000)
  68. typedef struct VkPhysicalDeviceShaderBfloat16FeaturesKHR {
  69. VkStructureType sType;
  70. void* pNext;
  71. VkBool32 shaderBFloat16Type;
  72. VkBool32 shaderBFloat16DotProduct;
  73. VkBool32 shaderBFloat16CooperativeMatrix;
  74. } VkPhysicalDeviceShaderBfloat16FeaturesKHR;
  75. #endif
  76. #define ROUNDUP_POW2(M, N) (((M) + (N) - 1) & ~((N) - 1))
  77. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  78. static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; }
  79. #define VK_VENDOR_ID_AMD 0x1002
  80. #define VK_VENDOR_ID_APPLE 0x106b
  81. #define VK_VENDOR_ID_INTEL 0x8086
  82. #define VK_VENDOR_ID_NVIDIA 0x10de
  83. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 256
  84. #define GGML_VK_MAX_NODES 8192
  85. #define VK_CHECK(err, msg) \
  86. do { \
  87. vk::Result err_ = (err); \
  88. if (err_ != vk::Result::eSuccess) { \
  89. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  90. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  91. exit(1); \
  92. } \
  93. } while (0)
  94. #ifdef GGML_VULKAN_DEBUG
  95. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  96. #else
  97. #define VK_LOG_DEBUG(msg) ((void) 0)
  98. #endif // GGML_VULKAN_DEBUG
  99. struct ggml_backend_vk_context;
  100. #define MAX_PARAMETER_COUNT 12
  101. // Max number of adds that can be fused without exceeding MAX_PARAMETER_COUNT.
  102. #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3)
  103. struct vk_pipeline_struct {
  104. std::string name;
  105. vk::ShaderModule shader_module;
  106. vk::PipelineLayout layout;
  107. vk::Pipeline pipeline;
  108. uint32_t push_constant_size;
  109. uint32_t parameter_count;
  110. std::array<uint32_t, 3> wg_denoms;
  111. uint32_t align;
  112. // true if fields have been set by ggml_vk_create_pipeline
  113. bool initialized {};
  114. // set to true to request the pipeline is compiled
  115. std::atomic<bool> needed {};
  116. // set to true when the shader has been compiled
  117. std::atomic<bool> compiled {};
  118. // number of registers used, extracted from pipeline executable properties
  119. uint32_t register_count {};
  120. };
  121. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  122. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  123. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  124. struct vk_matmul_pipeline_struct {
  125. vk_pipeline l, m, s;
  126. vk_pipeline a_l, a_m, a_s;
  127. // Returns true when all unaligned pipelines are null.
  128. // We only check for unaligned variants since one of the unaligned pipelines must exist
  129. // while aligned pipelines are optional
  130. bool is_empty() const {
  131. return l == nullptr && m == nullptr && s == nullptr;
  132. }
  133. };
  134. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  135. struct vk_matmul_pipeline2 {
  136. vk_matmul_pipeline2() {
  137. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  138. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  139. }
  140. vk_matmul_pipeline f32acc;
  141. vk_matmul_pipeline f16acc;
  142. };
  143. struct vk_device_struct;
  144. typedef std::shared_ptr<vk_device_struct> vk_device;
  145. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  146. struct vk_buffer_struct;
  147. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  148. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  149. struct ggml_backend_vk_buffer_type_context {
  150. std::string name;
  151. vk_device device;
  152. };
  153. struct vk_queue;
  154. // Stores command pool/buffers. There's an instance of this
  155. // for each (context,queue) pair and for each (device,queue) pair.
  156. struct vk_command_pool {
  157. void init(vk_device& device, vk_queue *q_);
  158. void destroy(vk::Device& device);
  159. vk::CommandPool pool;
  160. uint32_t cmd_buffer_idx;
  161. std::vector<vk::CommandBuffer> cmd_buffers;
  162. vk_queue *q;
  163. };
  164. // Prevent simultaneous submissions to the same queue.
  165. // This could be per vk_queue if we stopped having two vk_queue structures
  166. // sharing the same vk::Queue.
  167. static std::mutex queue_mutex;
  168. struct vk_queue {
  169. uint32_t queue_family_index;
  170. vk::Queue queue;
  171. vk_command_pool cmd_pool;
  172. vk::PipelineStageFlags stage_flags;
  173. bool transfer_only;
  174. // copy everything except the cmd_pool
  175. void copyFrom(vk_queue &other) {
  176. queue_family_index = other.queue_family_index;
  177. queue = other.queue;
  178. stage_flags = other.stage_flags;
  179. transfer_only = other.transfer_only;
  180. }
  181. };
  182. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  183. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  184. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  185. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  186. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  187. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  188. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  189. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  190. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  191. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  192. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  193. /* .is_host = */ NULL,
  194. };
  195. #ifdef GGML_VULKAN_MEMORY_DEBUG
  196. class vk_memory_logger;
  197. #endif
  198. class vk_perf_logger;
  199. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  200. static void ggml_vk_synchronize(ggml_backend_vk_context * ctx);
  201. static constexpr uint32_t mul_mat_vec_max_cols = 8;
  202. static constexpr uint32_t p021_max_gqa_ratio = 8;
  203. enum vk_device_architecture {
  204. OTHER,
  205. AMD_GCN,
  206. AMD_RDNA1,
  207. AMD_RDNA2,
  208. AMD_RDNA3,
  209. INTEL_XE2,
  210. NVIDIA_PRE_TURING,
  211. };
  212. static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) {
  213. vk::PhysicalDeviceProperties props = device.getProperties();
  214. if (props.vendorID == VK_VENDOR_ID_AMD) {
  215. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  216. bool amd_shader_core_properties = false;
  217. bool integer_dot_product = false;
  218. bool subgroup_size_control = false;
  219. for (const auto& properties : ext_props) {
  220. if (strcmp("VK_AMD_shader_core_properties", properties.extensionName) == 0) {
  221. amd_shader_core_properties = true;
  222. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0) {
  223. integer_dot_product = true;
  224. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  225. subgroup_size_control = true;
  226. }
  227. }
  228. if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) {
  229. return vk_device_architecture::OTHER;
  230. }
  231. vk::PhysicalDeviceProperties2 props2;
  232. vk::PhysicalDeviceShaderCorePropertiesAMD shader_core_props_amd;
  233. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR integer_dot_props;
  234. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  235. props2.pNext = &shader_core_props_amd;
  236. shader_core_props_amd.pNext = &integer_dot_props;
  237. integer_dot_props.pNext = &subgroup_size_control_props;
  238. device.getProperties2(&props2);
  239. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 64) {
  240. return vk_device_architecture::AMD_GCN;
  241. }
  242. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 32) {
  243. // RDNA
  244. if (shader_core_props_amd.wavefrontsPerSimd == 20) {
  245. return vk_device_architecture::AMD_RDNA1;
  246. }
  247. if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
  248. return vk_device_architecture::AMD_RDNA3;
  249. }
  250. return vk_device_architecture::AMD_RDNA2;
  251. }
  252. } else if (props.vendorID == VK_VENDOR_ID_INTEL) {
  253. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  254. bool subgroup_size_control = false;
  255. for (const auto& properties : ext_props) {
  256. if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  257. subgroup_size_control = true;
  258. }
  259. }
  260. if (!subgroup_size_control) {
  261. return vk_device_architecture::OTHER;
  262. }
  263. vk::PhysicalDeviceProperties2 props2;
  264. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  265. props2.pNext = &subgroup_size_control_props;
  266. device.getProperties2(&props2);
  267. if (subgroup_size_control_props.minSubgroupSize == 16) {
  268. // Xe2 architecture uses SIMD16 while previous Xe and Gen architecture uses SIMD8.
  269. // Minimum subgroup size matches the SIMD width so we distinguish architecture by checking this value.
  270. // https://www.intel.com/content/www/us/en/content-details/824434/2024-intel-tech-tour-xe2-and-lunar-lake-s-gpu.html
  271. // https://www.intel.com/content/www/us/en/docs/oneapi/optimization-guide-gpu/2025-0/intel-xe-gpu-architecture.html
  272. return vk_device_architecture::INTEL_XE2;
  273. }
  274. } else if (props.vendorID == VK_VENDOR_ID_NVIDIA) {
  275. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  276. bool cooperative_matrix = false;
  277. // Detect "pre-turing" based on lack of coopmat support.
  278. for (const auto& properties : ext_props) {
  279. if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0) {
  280. cooperative_matrix = true;
  281. break;
  282. }
  283. }
  284. if (!cooperative_matrix) {
  285. return vk_device_architecture::NVIDIA_PRE_TURING;
  286. }
  287. }
  288. return vk_device_architecture::OTHER;
  289. }
  290. enum vk_conv_shapes {
  291. CONV_SHAPE_128x128,
  292. CONV_SHAPE_64x32,
  293. CONV_SHAPE_32x256,
  294. CONV_SHAPE_COUNT,
  295. };
  296. uint32_t conv_shapes_wg_denoms[][3] = {
  297. { 128, 128, 1 },
  298. { 64, 32, 1 },
  299. { 32, 256, 1 },
  300. };
  301. enum dmmv_wg_sizes {
  302. DMMV_WG_SIZE_SUBGROUP,
  303. DMMV_WG_SIZE_LARGE,
  304. DMMV_WG_SIZE_COUNT,
  305. };
  306. enum FaCodePath {
  307. FA_SCALAR,
  308. FA_COOPMAT1,
  309. FA_COOPMAT2,
  310. };
  311. struct vk_fa_pipeline_state {
  312. vk_fa_pipeline_state(uint32_t HSK, uint32_t HSV, bool small_rows, FaCodePath path, bool aligned, bool f32acc)
  313. : HSK(HSK), HSV(HSV), small_rows(small_rows), path(path), aligned(aligned), f32acc(f32acc) {}
  314. uint32_t HSK, HSV;
  315. bool small_rows;
  316. FaCodePath path;
  317. bool aligned;
  318. bool f32acc;
  319. bool operator<(const vk_fa_pipeline_state &b) const {
  320. return std::tie(HSK, HSV, small_rows, path, aligned, f32acc) <
  321. std::tie(b.HSK, b.HSV, b.small_rows, b.path, b.aligned, b.f32acc);
  322. }
  323. };
  324. struct vk_conv2d_pipeline_state {
  325. 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)
  326. : s0(s0), s1(s1), p0(p0), p1(p1), d0(d0), d1(d1), KW(KW), KH(KH) {}
  327. uint32_t s0, s1, p0, p1, d0, d1, KW, KH;
  328. bool operator<(const vk_conv2d_pipeline_state &b) const {
  329. return std::tie(s0, s1, p0, p1, d0, d1, KW, KH) <
  330. std::tie(b.s0, b.s1, b.p0, b.p1, b.d0, b.d1, b.KW, b.KH);
  331. }
  332. };
  333. enum shader_reduction_mode {
  334. SHADER_REDUCTION_MODE_SHMEM,
  335. SHADER_REDUCTION_MODE_HYBRID,
  336. SHADER_REDUCTION_MODE_SUBGROUP,
  337. SHADER_REDUCTION_MODE_COUNT,
  338. };
  339. static constexpr uint32_t num_argsort_pipelines = 11;
  340. static constexpr uint32_t max_argsort_cols = 1 << (num_argsort_pipelines-1);
  341. static constexpr uint32_t num_topk_moe_pipelines = 10;
  342. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax_norm{ GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  343. GGML_OP_VIEW, GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  344. GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV,
  345. GGML_OP_RESHAPE };
  346. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax { GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  347. GGML_OP_VIEW, GGML_OP_GET_ROWS };
  348. static constexpr std::initializer_list<ggml_op> topk_moe_late_softmax { GGML_OP_ARGSORT, GGML_OP_VIEW,
  349. GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  350. GGML_OP_SOFT_MAX, GGML_OP_RESHAPE };
  351. //node #978 ( SOFT_MAX): ffn_moe_probs-15 ( 0K) [Vulka ] use=2: ffn_moe_logits-15 ( 0K) [Vulka ]
  352. //node #979 ( RESHAPE): ffn_moe_probs-15 (re ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  353. //node #980 ( ARGSORT): ffn_moe_argsort-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  354. //node #981 ( VIEW): ffn_moe_topk-15 ( 0K) [Vulka ] use=4: ffn_moe_argsort-15 ( 0K) [Vulka ]
  355. //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 ]
  356. //node #983 ( RESHAPE): ffn_moe_weights-15 ( ( 0K) [Vulka ] use=2: ffn_moe_weights-15 ( 0K) [Vulka ]
  357. //node #984 ( SUM_ROWS): ffn_moe_weights_sum- ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ]
  358. //node #985 ( CLAMP): ffn_moe_weights_sum_ ( 0K) [Vulka ] use=1: ffn_moe_weights_sum- ( 0K) [Vulka ]
  359. //node #986 ( DIV): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ] ffn_moe_weights_sum_ ( 0K) [Vulka ]
  360. //node #987 ( RESHAPE): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights_norm ( 0K) [Vulka ]
  361. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_norm_edges {
  362. { 1, 0, 0 }, // reshape->src[0] == softmax
  363. { 2, 0, 0 }, // argsort->src[0] == softmax
  364. { 3, 0, 2 }, // view->src[0] == argsort
  365. { 4, 0, 1 }, // get_rows->src[0] == reshape
  366. { 4, 1, 3 }, // get_rows->src[1] == view
  367. { 5, 0, 4 }, // reshape->src[0] == get_rows
  368. { 6, 0, 5 }, // sum_rows->src[0] == reshape
  369. { 7, 0, 6 }, // clamp->src[0] == sum_rows
  370. { 8, 0, 5 }, // div->src[0] == reshape
  371. { 8, 1, 7 }, // div->src[1] == clamp
  372. { 9, 0, 8 }, // reshape->src[0] == div
  373. };
  374. // same as early_softmax_norm but ending after the get_rows
  375. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_edges {
  376. { 1, 0, 0 }, // reshape->src[0] == softmax
  377. { 2, 0, 0 }, // argsort->src[0] == softmax
  378. { 3, 0, 2 }, // view->src[0] == argsort
  379. { 4, 0, 1 }, // get_rows->src[0] == reshape
  380. { 4, 1, 3 }, // get_rows->src[1] == view
  381. };
  382. //node #652 ( ARGSORT): ffn_moe_argsort-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 ( 0K) [Vulka ]
  383. //node #653 ( VIEW): ffn_moe_topk-11 ( 0K) [Vulka ] use=7: ffn_moe_argsort-11 ( 0K) [Vulka ]
  384. //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 ]
  385. //node #655 ( RESHAPE): ffn_moe_weights-11 ( ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( 0K) [Vulka ]
  386. //node #656 ( SOFT_MAX): node_656 ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( ( 0K) [Vulka ]
  387. //node #657 ( RESHAPE): ffn_moe_weights_soft ( 0K) [Vulka ] use=1: node_656 ( 0K) [Vulka ]
  388. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_late_softmax_edges {
  389. { 1, 0, 0 }, // view->src[0] == argsort
  390. { 2, 1, 1 }, // get_rows->src[1] == view
  391. { 3, 0, 2 }, // reshape->src[0] == get_rows
  392. { 4, 0, 3 }, // soft_max->src[0] == reshape
  393. { 5, 0, 4 }, // reshape->src[0] == soft_max
  394. };
  395. enum topk_moe_mode {
  396. TOPK_MOE_EARLY_SOFTMAX,
  397. TOPK_MOE_EARLY_SOFTMAX_NORM,
  398. TOPK_MOE_LATE_SOFTMAX,
  399. TOPK_MOE_COUNT,
  400. };
  401. static topk_moe_mode ggml_vk_num_additional_ops_to_topk_moe_mode(uint32_t num) {
  402. topk_moe_mode mode = num == topk_moe_early_softmax_norm.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX_NORM :
  403. num == topk_moe_early_softmax.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX :
  404. TOPK_MOE_LATE_SOFTMAX;
  405. return mode;
  406. }
  407. static constexpr std::initializer_list<std::array<int, 3>> rope_view_set_rows_edges {
  408. { 1, 0, 0 }, // view->src[0] == rope
  409. { 2, 0, 1 }, // set_rows->src[0] == view
  410. };
  411. static constexpr std::initializer_list<std::array<int, 3>> rms_norm_mul_rope_view_set_rows_edges {
  412. { 1, 0, 0 }, // mul->src[0] == rms
  413. { 2, 0, 1 }, // rope->src[0] == mul
  414. { 3, 0, 2 }, // view->src[0] == rope
  415. { 4, 0, 3 }, // set_rows->src[0] == view
  416. };
  417. struct vk_device_struct {
  418. std::recursive_mutex mutex;
  419. vk::PhysicalDevice physical_device;
  420. vk::PhysicalDeviceProperties properties;
  421. std::string name;
  422. uint64_t max_memory_allocation_size;
  423. uint64_t max_buffer_size;
  424. uint64_t suballocation_block_size;
  425. bool fp16;
  426. bool bf16;
  427. bool pipeline_robustness;
  428. vk::Device device;
  429. uint32_t vendor_id;
  430. vk::DriverId driver_id;
  431. vk_device_architecture architecture;
  432. vk_queue compute_queue;
  433. vk_queue transfer_queue;
  434. bool single_queue;
  435. uint32_t subgroup_size;
  436. uint32_t shader_core_count;
  437. bool uma;
  438. bool prefer_host_memory;
  439. bool float_controls_rte_fp16;
  440. bool subgroup_arithmetic;
  441. bool subgroup_shuffle;
  442. bool subgroup_ballot;
  443. bool subgroup_clustered;
  444. bool subgroup_vote;
  445. bool multi_add;
  446. bool shader_int64;
  447. bool buffer_device_address;
  448. bool add_rms_fusion;
  449. uint32_t partials_binding_alignment;
  450. bool integer_dot_product;
  451. // 0: default, 1: force mmvq, -1: disable mmvq
  452. int32_t mmvq_mode;
  453. bool subgroup_size_control;
  454. uint32_t subgroup_min_size;
  455. uint32_t subgroup_max_size;
  456. bool subgroup_require_full_support;
  457. bool coopmat_support;
  458. bool coopmat_acc_f32_support {};
  459. bool coopmat_acc_f16_support {};
  460. bool coopmat_bf16_support {};
  461. bool coopmat_support_16x16x16_f16acc {};
  462. bool coopmat_support_16x16x16_f32acc {};
  463. bool coopmat1_fa_support {};
  464. uint32_t coopmat_m;
  465. uint32_t coopmat_n;
  466. uint32_t coopmat_k;
  467. bool coopmat_int_support;
  468. uint32_t coopmat_int_m;
  469. uint32_t coopmat_int_n;
  470. uint32_t coopmat_int_k;
  471. bool coopmat2;
  472. bool pipeline_executable_properties_support {};
  473. size_t idx;
  474. bool mul_mat_l[GGML_TYPE_COUNT];
  475. bool mul_mat_m[GGML_TYPE_COUNT];
  476. bool mul_mat_s[GGML_TYPE_COUNT];
  477. bool mul_mat_id_l[GGML_TYPE_COUNT];
  478. bool mul_mat_id_m[GGML_TYPE_COUNT];
  479. bool mul_mat_id_s[GGML_TYPE_COUNT];
  480. vk::DescriptorSetLayout dsl;
  481. vk_matmul_pipeline pipeline_matmul_f32 {};
  482. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  483. vk_matmul_pipeline pipeline_matmul_bf16 {};
  484. vk_matmul_pipeline2 pipeline_matmul_f16;
  485. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  486. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  487. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  488. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_COUNT];
  489. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  490. vk_matmul_pipeline pipeline_matmul_id_bf16 {};
  491. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  492. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  493. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  494. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_COUNT];
  495. vk_pipeline pipeline_matmul_split_k_reduce;
  496. vk_pipeline pipeline_quantize_q8_1_x4;
  497. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  498. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  499. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  500. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_COUNT];
  501. vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  502. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio];
  503. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  504. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  505. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  506. vk_pipeline pipeline_acc_f32;
  507. // [src0 0=fp32,1=fp16][src1 0=fp32,1=fp16][dst 0=fp32,1=fp16]
  508. vk_pipeline pipeline_add[2][2][2];
  509. vk_pipeline pipeline_add_norepeat[2][2][2];
  510. vk_pipeline pipeline_sub[2][2][2];
  511. vk_pipeline pipeline_sub_norepeat[2][2][2];
  512. vk_pipeline pipeline_mul[2][2][2];
  513. vk_pipeline pipeline_mul_norepeat[2][2][2];
  514. vk_pipeline pipeline_div[2][2][2];
  515. vk_pipeline pipeline_div_norepeat[2][2][2];
  516. vk_pipeline pipeline_add_rms[2][2][2];
  517. vk_pipeline pipeline_add_rms_norepeat[2][2][2];
  518. // indexed by num_additional_fused_ops == num_adds - 1
  519. vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS];
  520. vk_pipeline pipeline_multi_add_rms[MAX_FUSED_ADDS];
  521. vk_pipeline pipeline_add_id_f32;
  522. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  523. vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32, pipeline_upscale_bicubic_f32;
  524. vk_pipeline pipeline_scale_f32;
  525. vk_pipeline pipeline_sqr_f32;
  526. vk_pipeline pipeline_sqrt_f32;
  527. vk_pipeline pipeline_sin_f32;
  528. vk_pipeline pipeline_cos_f32;
  529. vk_pipeline pipeline_log[2];
  530. vk_pipeline pipeline_clamp_f32;
  531. vk_pipeline pipeline_pad_f32;
  532. vk_pipeline pipeline_roll_f32;
  533. vk_pipeline pipeline_repeat_f32, pipeline_repeat_back_f32;
  534. 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;
  535. 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;
  536. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  537. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  538. vk_pipeline pipeline_set_rows_i32[GGML_TYPE_COUNT];
  539. vk_pipeline pipeline_set_rows_i64[GGML_TYPE_COUNT];
  540. vk_pipeline pipeline_norm_f32;
  541. vk_pipeline pipeline_group_norm_f32;
  542. vk_pipeline pipeline_rms_norm_f32;
  543. vk_pipeline pipeline_rms_norm_mul_f32;
  544. vk_pipeline pipeline_rms_norm_partials_f32;
  545. vk_pipeline pipeline_rms_norm_mul_partials_f32;
  546. vk_pipeline pipeline_rms_norm_mul_rope_f32_f32;
  547. vk_pipeline pipeline_rms_norm_mul_rope_f32_f16;
  548. vk_pipeline pipeline_rms_norm_back_f32;
  549. vk_pipeline pipeline_l2_norm_f32;
  550. // [src/dst 0=fp32,1=fp16]
  551. vk_pipeline pipeline_exp[2];
  552. vk_pipeline pipeline_gelu[2];
  553. vk_pipeline pipeline_gelu_erf[2];
  554. vk_pipeline pipeline_gelu_quick[2];
  555. vk_pipeline pipeline_silu[2];
  556. vk_pipeline pipeline_relu[2];
  557. vk_pipeline pipeline_neg[2];
  558. vk_pipeline pipeline_tanh[2];
  559. vk_pipeline pipeline_sigmoid[2];
  560. vk_pipeline pipeline_hardsigmoid[2];
  561. vk_pipeline pipeline_hardswish[2];
  562. vk_pipeline pipeline_abs[2];
  563. vk_pipeline pipeline_geglu[2];
  564. vk_pipeline pipeline_reglu[2];
  565. vk_pipeline pipeline_swiglu[2];
  566. vk_pipeline pipeline_swiglu_oai[2];
  567. vk_pipeline pipeline_geglu_erf[2];
  568. vk_pipeline pipeline_geglu_quick[2];
  569. vk_pipeline pipeline_leaky_relu_f32;
  570. vk_pipeline pipeline_silu_back_f32;
  571. vk_pipeline pipeline_diag_mask_inf_f32;
  572. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  573. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  574. vk_pipeline pipeline_soft_max_back_f32;
  575. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16, pipeline_rope_norm_f32_f16;
  576. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16, pipeline_rope_neox_f32_f16;
  577. vk_pipeline pipeline_rope_multi_f32, pipeline_rope_multi_f16;
  578. vk_pipeline pipeline_rope_vision_f32, pipeline_rope_vision_f16;
  579. vk_pipeline pipeline_argsort_f32[num_argsort_pipelines];
  580. vk_pipeline pipeline_sum_rows_f32;
  581. vk_pipeline pipeline_argmax_f32;
  582. vk_pipeline pipeline_count_equal_i32;
  583. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  584. vk_pipeline pipeline_im2col_3d_f32, pipeline_im2col_3d_f32_f16;
  585. vk_pipeline pipeline_timestep_embedding_f32;
  586. vk_pipeline pipeline_conv_transpose_1d_f32;
  587. vk_pipeline pipeline_pool2d_f32;
  588. vk_pipeline pipeline_rwkv_wkv6_f32;
  589. vk_pipeline pipeline_rwkv_wkv7_f32;
  590. vk_pipeline pipeline_ssm_scan_f32_d128;
  591. vk_pipeline pipeline_ssm_scan_f32_d256;
  592. vk_pipeline pipeline_ssm_conv_f32;
  593. vk_pipeline pipeline_opt_step_adamw_f32;
  594. vk_pipeline pipeline_opt_step_sgd_f32;
  595. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f32[CONV_SHAPE_COUNT];
  596. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f16_f32[CONV_SHAPE_COUNT];
  597. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f32[CONV_SHAPE_COUNT];
  598. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f16_f32[CONV_SHAPE_COUNT];
  599. vk_pipeline pipeline_conv2d_dw_whcn_f32, pipeline_conv2d_dw_whcn_f16_f32;
  600. vk_pipeline pipeline_conv2d_dw_cwhn_f32, pipeline_conv2d_dw_cwhn_f16_f32;
  601. std::map<vk_fa_pipeline_state, vk_pipeline> pipeline_flash_attn_f32_f16[GGML_TYPE_COUNT];
  602. vk_pipeline pipeline_flash_attn_split_k_reduce;
  603. vk_pipeline pipeline_topk_moe[num_topk_moe_pipelines][TOPK_MOE_COUNT];
  604. std::vector<vk_pipeline_ref> all_pipelines;
  605. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  606. vk::Fence fence;
  607. vk_buffer sync_staging;
  608. ggml_backend_buffer_type buffer_type;
  609. bool disable_fusion;
  610. bool disable_host_visible_vidmem;
  611. bool allow_sysmem_fallback;
  612. bool disable_graph_optimize;
  613. #ifdef GGML_VULKAN_MEMORY_DEBUG
  614. std::unique_ptr<vk_memory_logger> memory_logger;
  615. #endif
  616. // for GGML_VK_PERF_LOGGER
  617. std::unique_ptr<vk_perf_logger> perf_logger;
  618. vk::QueryPool query_pool;
  619. int32_t num_queries;
  620. ~vk_device_struct() {
  621. VK_LOG_DEBUG("destroy device " << name);
  622. device.destroyFence(fence);
  623. ggml_vk_destroy_buffer(sync_staging);
  624. compute_queue.cmd_pool.destroy(device);
  625. transfer_queue.cmd_pool.destroy(device);
  626. for (auto& pipeline : all_pipelines) {
  627. if (pipeline.expired()) {
  628. continue;
  629. }
  630. vk_pipeline pl = pipeline.lock();
  631. ggml_vk_destroy_pipeline(device, pl);
  632. }
  633. all_pipelines.clear();
  634. device.destroyDescriptorSetLayout(dsl);
  635. device.destroy();
  636. }
  637. };
  638. void vk_command_pool::init(vk_device& device, vk_queue *q_) {
  639. cmd_buffer_idx = 0;
  640. q = q_;
  641. vk::CommandPoolCreateInfo command_pool_create_info(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), q->queue_family_index);
  642. pool = device->device.createCommandPool(command_pool_create_info);
  643. }
  644. void vk_command_pool::destroy(vk::Device& device) {
  645. device.destroyCommandPool(pool);
  646. pool = nullptr;
  647. cmd_buffers.clear();
  648. }
  649. struct vk_buffer_struct {
  650. vk::Buffer buffer = VK_NULL_HANDLE;
  651. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  652. vk::MemoryPropertyFlags memory_property_flags;
  653. void * ptr;
  654. size_t size = 0;
  655. vk::DeviceAddress bda_addr {};
  656. vk_device device;
  657. ~vk_buffer_struct() {
  658. if (size == 0) {
  659. return;
  660. }
  661. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  662. device->device.freeMemory(device_memory);
  663. device->device.destroyBuffer(buffer);
  664. }
  665. };
  666. struct vk_subbuffer {
  667. vk_buffer buffer;
  668. uint64_t offset;
  669. uint64_t size;
  670. operator vk::DescriptorBufferInfo() const {
  671. return { buffer->buffer, offset, size };
  672. }
  673. };
  674. struct vk_semaphore {
  675. vk::Semaphore s;
  676. uint64_t value;
  677. };
  678. struct vk_submission {
  679. vk::CommandBuffer buffer;
  680. std::vector<vk_semaphore> wait_semaphores;
  681. std::vector<vk_semaphore> signal_semaphores;
  682. };
  683. typedef std::vector<vk_submission> vk_sequence;
  684. struct vk_mat_mat_push_constants {
  685. uint32_t M; uint32_t N; uint32_t K;
  686. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  687. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  688. uint32_t k_split;
  689. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  690. uint32_t padded_N;
  691. };
  692. #define MAT_VEC_FUSION_FLAGS_BIAS0 0x1
  693. #define MAT_VEC_FUSION_FLAGS_BIAS1 0x2
  694. #define MAT_VEC_FUSION_FLAGS_SCALE0 0x4
  695. #define MAT_VEC_FUSION_FLAGS_SCALE1 0x8
  696. struct vk_mat_vec_push_constants {
  697. uint32_t ncols;
  698. uint32_t stride_a;
  699. uint32_t stride_b;
  700. uint32_t stride_d;
  701. uint32_t batch_stride_a;
  702. uint32_t batch_stride_b;
  703. uint32_t batch_stride_d;
  704. uint32_t fusion_flags;
  705. uint32_t ne02;
  706. uint32_t ne12;
  707. uint32_t broadcast2;
  708. uint32_t broadcast3;
  709. };
  710. struct vk_mat_vec_p021_push_constants {
  711. uint32_t ncols_x;
  712. uint32_t nrows_x;
  713. uint32_t nchannels_x;
  714. uint32_t nchannels_y;
  715. uint32_t b_offset;
  716. uint32_t d_offset;
  717. uint32_t fusion_flags;
  718. };
  719. struct vk_mat_vec_nc_push_constants {
  720. uint32_t ncols_x;
  721. uint32_t nrows_x;
  722. uint32_t row_stride_x;
  723. uint32_t channel_stride_x;
  724. uint32_t channel_stride_y;
  725. uint32_t channel_x_divisor;
  726. uint32_t ne12;
  727. uint32_t b_offset;
  728. uint32_t d_offset;
  729. uint32_t nb03;
  730. uint32_t nb13;
  731. uint32_t nb23;
  732. uint32_t fusion_flags;
  733. };
  734. struct vk_mat_mat_id_push_constants {
  735. uint32_t M; uint32_t N; uint32_t K;
  736. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  737. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  738. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  739. uint32_t padded_N;
  740. };
  741. struct vk_mat_vec_id_push_constants {
  742. uint32_t ncols;
  743. uint32_t stride_a;
  744. uint32_t stride_b;
  745. uint32_t stride_d;
  746. uint32_t batch_stride_a;
  747. uint32_t batch_stride_b;
  748. uint32_t batch_stride_d;
  749. uint32_t fusion_flags;
  750. uint32_t nei0;
  751. uint32_t ne11;
  752. };
  753. struct vk_flash_attn_push_constants {
  754. uint32_t N;
  755. uint32_t KV;
  756. uint32_t ne1;
  757. uint32_t ne2;
  758. uint32_t ne3;
  759. uint32_t neq2;
  760. uint32_t neq3;
  761. uint32_t nek2;
  762. uint32_t nek3;
  763. uint32_t nev2;
  764. uint32_t nev3;
  765. uint32_t nem1;
  766. uint32_t nem2;
  767. uint32_t nem3;
  768. uint32_t nb01;
  769. uint32_t nb02;
  770. uint32_t nb03;
  771. uint32_t nb11;
  772. uint32_t nb12;
  773. uint32_t nb13;
  774. uint32_t nb21;
  775. uint32_t nb22;
  776. uint32_t nb23;
  777. float scale;
  778. float max_bias;
  779. float logit_softcap;
  780. uint32_t mask_n_head_log2;
  781. float m0;
  782. float m1;
  783. uint32_t gqa_ratio;
  784. uint32_t split_kv;
  785. uint32_t k_num;
  786. };
  787. static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128");
  788. struct vk_op_push_constants {
  789. uint32_t KX;
  790. uint32_t KY;
  791. float param1;
  792. float param2;
  793. };
  794. struct vk_op_glu_push_constants {
  795. uint32_t N;
  796. uint32_t ne00;
  797. uint32_t ne20;
  798. uint32_t mode; // 0: default, 1: swapped, 2: split
  799. float alpha; // for swiglu_oai
  800. float limit;
  801. };
  802. struct vk_op_unary_push_constants {
  803. uint32_t ne;
  804. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  805. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  806. uint32_t misalign_offsets;
  807. float param1; float param2;
  808. uint32_t ne0_012mp; uint32_t ne0_012L;
  809. uint32_t ne0_01mp; uint32_t ne0_01L;
  810. uint32_t ne0_0mp; uint32_t ne0_0L;
  811. uint32_t ne1_012mp; uint32_t ne1_012L;
  812. uint32_t ne1_01mp; uint32_t ne1_01L;
  813. uint32_t ne1_0mp; uint32_t ne1_0L;
  814. };
  815. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  816. static vk_op_unary_push_constants vk_op_unary_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst, int64_t ne = 0) {
  817. GGML_ASSERT(ne != 0 || (ggml_nelements(src0) == ggml_nelements(dst)));
  818. ne = ne != 0 ? ne : ggml_nelements(dst);
  819. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  820. vk_op_unary_push_constants p{};
  821. p.ne = (uint32_t)ne;
  822. size_t src0_tsize = ggml_type_size(src0->type);
  823. p.ne00 = (uint32_t)src0->ne[0];
  824. p.ne01 = (uint32_t)src0->ne[1];
  825. p.ne02 = (uint32_t)src0->ne[2];
  826. p.ne03 = (uint32_t)src0->ne[3];
  827. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  828. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  829. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  830. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  831. size_t dst_tsize = ggml_type_size(dst->type);
  832. p.ne10 = (uint32_t)dst->ne[0];
  833. p.ne11 = (uint32_t)dst->ne[1];
  834. p.ne12 = (uint32_t)dst->ne[2];
  835. p.ne13 = (uint32_t)dst->ne[3];
  836. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  837. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  838. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  839. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  840. return p; // offsets are initialized later in ggml_vk_op
  841. }
  842. struct vk_op_pad_push_constants {
  843. uint32_t ne;
  844. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  845. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  846. uint32_t misalign_offsets;
  847. uint32_t lp0; uint32_t rp0;
  848. uint32_t lp1; uint32_t rp1;
  849. uint32_t lp2; uint32_t rp2;
  850. uint32_t lp3; uint32_t rp3;
  851. };
  852. static vk_op_pad_push_constants vk_op_pad_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst) {
  853. int64_t ne = ggml_nelements(dst);
  854. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  855. vk_op_pad_push_constants p{};
  856. p.ne = (uint32_t)ne;
  857. size_t src0_tsize = ggml_type_size(src0->type);
  858. p.ne00 = (uint32_t)src0->ne[0];
  859. p.ne01 = (uint32_t)src0->ne[1];
  860. p.ne02 = (uint32_t)src0->ne[2];
  861. p.ne03 = (uint32_t)src0->ne[3];
  862. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  863. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  864. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  865. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  866. size_t dst_tsize = ggml_type_size(dst->type);
  867. p.ne10 = (uint32_t)dst->ne[0];
  868. p.ne11 = (uint32_t)dst->ne[1];
  869. p.ne12 = (uint32_t)dst->ne[2];
  870. p.ne13 = (uint32_t)dst->ne[3];
  871. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  872. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  873. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  874. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  875. p.lp0 = dst->op_params[0];
  876. p.rp0 = dst->op_params[1];
  877. p.lp1 = dst->op_params[2];
  878. p.rp1 = dst->op_params[3];
  879. p.lp2 = dst->op_params[4];
  880. p.rp2 = dst->op_params[5];
  881. p.lp3 = dst->op_params[6];
  882. p.rp3 = dst->op_params[7];
  883. return p; // fastdiv values and offsets are initialized later in ggml_vk_op
  884. }
  885. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  886. // Precompute mp (m' in the paper) and L such that division
  887. // can be computed using a multiply (high 32b of 64b result)
  888. // and a shift:
  889. //
  890. // n/d = (mulhi(n, mp) + n) >> L;
  891. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  892. {
  893. // compute L = ceil(log2(d));
  894. L = 0;
  895. while (L < 32 && (uint32_t{1} << L) < d) {
  896. L++;
  897. }
  898. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  899. }
  900. template <typename T> void init_pushconst_fastdiv(T &p) {
  901. GGML_UNUSED(p);
  902. static_assert(!std::is_const<T>::value, "unexpected type");
  903. }
  904. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  905. // Compute magic values to divide by these six numbers.
  906. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  907. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  908. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  909. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  910. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  911. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  912. }
  913. struct vk_op_binary_push_constants {
  914. uint32_t ne;
  915. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  916. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  917. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  918. uint32_t misalign_offsets;
  919. float param1; float param2; int32_t param3;
  920. };
  921. struct vk_op_multi_add_push_constants {
  922. // shape for dst
  923. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23;
  924. // strides for srcs+dst
  925. uint32_t nb[MAX_PARAMETER_COUNT][4];
  926. uint32_t rms_partials;
  927. };
  928. // update multi_add.comp if this changes
  929. static_assert(MAX_PARAMETER_COUNT == 12);
  930. static_assert(sizeof(vk_op_multi_add_push_constants) <= 256);
  931. struct vk_op_topk_moe_push_constants {
  932. uint32_t n_rows;
  933. uint32_t n_expert_used;
  934. float clamp_min;
  935. float clamp_max;
  936. };
  937. struct vk_op_add_id_push_constants {
  938. uint32_t ne0;
  939. uint32_t ne1;
  940. uint32_t s01;
  941. uint32_t s02;
  942. uint32_t s11;
  943. uint32_t s21;
  944. };
  945. struct vk_op_diag_mask_push_constants {
  946. uint32_t ncols;
  947. uint32_t rows_per_channel;
  948. int32_t n_past;
  949. };
  950. struct vk_op_rope_push_constants {
  951. uint32_t rope_mode;
  952. uint32_t ncols;
  953. uint32_t n_dims;
  954. float freq_scale;
  955. uint32_t p_delta_rows;
  956. float freq_base;
  957. float ext_factor;
  958. float attn_factor;
  959. float corr_dims[2];
  960. float theta_scale;
  961. uint32_t has_ff;
  962. uint32_t ne02;
  963. uint32_t s1;
  964. uint32_t s2;
  965. int32_t sections[4];
  966. uint32_t is_imrope;
  967. uint32_t is_back;
  968. uint32_t set_rows_stride;
  969. };
  970. // For fused rms_norm+mul+rope(+view+set_rows)
  971. struct vk_op_rms_norm_mul_rope_push_constants {
  972. vk_op_binary_push_constants bin;
  973. vk_op_rope_push_constants rope;
  974. };
  975. struct vk_op_soft_max_push_constants {
  976. uint32_t KX;
  977. uint32_t KY;
  978. uint32_t ne00;
  979. uint32_t ne01;
  980. uint32_t ne02;
  981. uint32_t ne12;
  982. uint32_t ne13;
  983. uint32_t nb11;
  984. uint32_t nb12;
  985. uint32_t nb13;
  986. float scale;
  987. float max_bias;
  988. float m0;
  989. float m1;
  990. uint32_t n_head_log2;
  991. uint32_t nrows_x;
  992. uint32_t has_sinks;
  993. };
  994. struct vk_op_argsort_push_constants {
  995. uint32_t ncols;
  996. uint32_t nrows;
  997. int32_t order;
  998. };
  999. struct vk_op_im2col_push_constants {
  1000. uint64_t dst_addr;
  1001. uint32_t batch_offset; uint32_t offset_delta;
  1002. uint32_t IC;
  1003. uint32_t IW; uint32_t IH;
  1004. uint32_t OW; uint32_t OH;
  1005. uint32_t KW; uint32_t KH;
  1006. uint32_t pelements;
  1007. uint32_t CHW;
  1008. int32_t s0; int32_t s1;
  1009. int32_t p0; int32_t p1;
  1010. int32_t d0; int32_t d1;
  1011. };
  1012. struct vk_op_im2col_3d_push_constants {
  1013. uint64_t dst_addr;
  1014. uint32_t nb10;
  1015. uint32_t nb11;
  1016. uint32_t nb12;
  1017. uint32_t nb13;
  1018. uint32_t s0;
  1019. uint32_t s1;
  1020. uint32_t s2;
  1021. uint32_t p0;
  1022. uint32_t p1;
  1023. uint32_t p2;
  1024. uint32_t d0;
  1025. uint32_t d1;
  1026. uint32_t d2;
  1027. uint32_t IW;
  1028. uint32_t IH;
  1029. uint32_t ID;
  1030. uint32_t IC;
  1031. uint32_t KW;
  1032. uint32_t OH;
  1033. uint32_t KD_KH_KW;
  1034. uint32_t KH_KW;
  1035. uint32_t IC_KD_KH_KW;
  1036. uint32_t N_OD_OH;
  1037. uint32_t OD_OH;
  1038. uint32_t OD_OH_OW_IC_KD_KH_KW;
  1039. uint32_t OH_OW_IC_KD_KH_KW;
  1040. uint32_t OW_IC_KD_KH_KW;
  1041. uint32_t misalign_offsets;
  1042. };
  1043. struct vk_op_timestep_embedding_push_constants {
  1044. uint32_t nb1;
  1045. uint32_t dim;
  1046. uint32_t max_period;
  1047. };
  1048. struct vk_op_conv_transpose_1d_push_constants {
  1049. uint32_t Cout;
  1050. uint32_t Cin;
  1051. uint32_t K;
  1052. uint32_t L;
  1053. uint32_t KL;
  1054. uint32_t nb01;
  1055. uint32_t nb02;
  1056. uint32_t nb11;
  1057. uint32_t nb1;
  1058. int32_t s0;
  1059. };
  1060. struct vk_op_pool2d_push_constants {
  1061. uint32_t IW; uint32_t IH;
  1062. uint32_t OW; uint32_t OH;
  1063. uint32_t OC;
  1064. uint32_t pelements;
  1065. uint32_t op;
  1066. int32_t k0; int32_t k1;
  1067. int32_t s0; int32_t s1;
  1068. int32_t p0; int32_t p1;
  1069. };
  1070. struct vk_op_rwkv_wkv6_push_constants {
  1071. uint32_t B;
  1072. uint32_t T;
  1073. uint32_t C;
  1074. uint32_t H;
  1075. };
  1076. struct vk_op_rwkv_wkv7_push_constants {
  1077. uint32_t B;
  1078. uint32_t T;
  1079. uint32_t C;
  1080. uint32_t H;
  1081. };
  1082. struct vk_op_ssm_scan_push_constants {
  1083. uint32_t nb02, nb03, nb12, nb13;
  1084. uint32_t nb21, nb22, nb31;
  1085. uint32_t nb42, nb43, nb52, nb53;
  1086. uint32_t s_off;
  1087. uint32_t n_head, d_head, n_group, n_tok;
  1088. };
  1089. struct vk_op_ssm_conv_push_constants {
  1090. uint32_t nb01, nb02;
  1091. uint32_t nb11;
  1092. uint32_t dst_nb0, dst_nb1, dst_nb2;
  1093. uint32_t nc, ncs, nr, n_t, n_s;
  1094. };
  1095. struct vk_op_conv2d_push_constants {
  1096. uint32_t Cout;
  1097. uint32_t Cin;
  1098. uint32_t N;
  1099. uint32_t KW;
  1100. uint32_t KH;
  1101. uint32_t W;
  1102. uint32_t H;
  1103. uint32_t OW;
  1104. uint32_t OH;
  1105. uint32_t s0;
  1106. uint32_t s1;
  1107. uint32_t p0;
  1108. uint32_t p1;
  1109. uint32_t d0;
  1110. uint32_t d1;
  1111. uint32_t nb01;
  1112. uint32_t nb02;
  1113. uint32_t nb03;
  1114. uint32_t nb11;
  1115. uint32_t nb12;
  1116. uint32_t nb13;
  1117. uint32_t nb1;
  1118. uint32_t nb2;
  1119. uint32_t nb3;
  1120. // init_fastdiv_values constants for dividing by OW, OW*OH
  1121. uint32_t OWmp; uint32_t OWL;
  1122. uint32_t OWOHmp; uint32_t OWOHL;
  1123. };
  1124. template <> void init_pushconst_fastdiv(vk_op_conv2d_push_constants &p) {
  1125. // Compute magic values to divide by OW, OW*OH
  1126. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1127. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1128. }
  1129. struct vk_op_conv_transpose_2d_push_constants {
  1130. uint32_t Cout;
  1131. uint32_t Cin;
  1132. uint32_t N;
  1133. uint32_t KW;
  1134. uint32_t KH;
  1135. uint32_t W;
  1136. uint32_t H;
  1137. uint32_t OW;
  1138. uint32_t OH;
  1139. uint32_t s0;
  1140. uint32_t s1;
  1141. uint32_t p0;
  1142. uint32_t p1;
  1143. uint32_t d0;
  1144. uint32_t d1;
  1145. uint32_t nb01;
  1146. uint32_t nb02;
  1147. uint32_t nb03;
  1148. uint32_t nb11;
  1149. uint32_t nb12;
  1150. uint32_t nb13;
  1151. uint32_t nb1;
  1152. uint32_t nb2;
  1153. uint32_t nb3;
  1154. // init_fastdiv_values constants for dividing by OW, OW*OH
  1155. uint32_t OWmp; uint32_t OWL;
  1156. uint32_t OWOHmp; uint32_t OWOHL;
  1157. };
  1158. template <> void init_pushconst_fastdiv(vk_op_conv_transpose_2d_push_constants &p) {
  1159. // Compute magic values to divide by OW, OW*OH
  1160. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1161. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1162. }
  1163. struct vk_op_conv2d_dw_push_constants {
  1164. uint32_t ne;
  1165. uint32_t batches;
  1166. uint32_t channels;
  1167. uint32_t dst_w;
  1168. uint32_t dst_h;
  1169. uint32_t src_w;
  1170. uint32_t src_h;
  1171. uint32_t knl_w;
  1172. uint32_t knl_h;
  1173. int32_t stride_x;
  1174. int32_t stride_y;
  1175. int32_t pad_x;
  1176. int32_t pad_y;
  1177. int32_t dilation_x;
  1178. int32_t dilation_y;
  1179. };
  1180. struct vk_op_upscale_push_constants {
  1181. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  1182. uint32_t ne00; uint32_t ne01;
  1183. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1184. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  1185. float sf0; float sf1; float sf2; float sf3;
  1186. float pixel_offset;
  1187. };
  1188. struct vk_op_sum_rows_push_constants
  1189. {
  1190. uint32_t n_cols;
  1191. uint32_t ne01, ne02;
  1192. uint32_t nb01, nb02, nb03;
  1193. uint32_t nb11, nb12, nb13;
  1194. float weight;
  1195. uint32_t misalign_offsets;
  1196. uint32_t ne0_12mp, ne0_12L;
  1197. uint32_t ne0_1mp, ne0_1L;
  1198. };
  1199. 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) {
  1200. uint32_t type_size = (uint32_t)ggml_type_size(src->type);
  1201. vk_op_sum_rows_push_constants p = {};
  1202. p.n_cols = (uint32_t)n_cols;
  1203. p.ne01 = (uint32_t)src->ne[1];
  1204. p.ne02 = (uint32_t)src->ne[2];
  1205. p.nb01 = (uint32_t)src->nb[1] / type_size;
  1206. p.nb02 = (uint32_t)src->nb[2] / type_size;
  1207. p.nb03 = (uint32_t)src->nb[3] / type_size;
  1208. p.nb11 = (uint32_t)dst->nb[1] / type_size;
  1209. p.nb12 = (uint32_t)dst->nb[2] / type_size;
  1210. p.nb13 = (uint32_t)dst->nb[3] / type_size;
  1211. p.weight = 1.0f;
  1212. return p;
  1213. }
  1214. template <> void init_pushconst_fastdiv(vk_op_sum_rows_push_constants &p) {
  1215. init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L);
  1216. init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L);
  1217. }
  1218. // Allow pre-recording command buffers
  1219. struct vk_staging_memcpy {
  1220. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  1221. void * dst;
  1222. const void * src;
  1223. size_t n;
  1224. };
  1225. struct vk_staging_memset {
  1226. vk_staging_memset(void * _dst, uint32_t _val, size_t _n) : dst(_dst), val(_val), n(_n) {}
  1227. void * dst;
  1228. uint32_t val;
  1229. size_t n;
  1230. };
  1231. struct vk_context_struct {
  1232. vk_submission * s;
  1233. std::vector<vk_sequence> seqs;
  1234. int exit_tensor_idx;
  1235. std::vector<vk_staging_memcpy> in_memcpys;
  1236. std::vector<vk_staging_memcpy> out_memcpys;
  1237. std::vector<vk_staging_memset> memsets;
  1238. vk_command_pool * p {};
  1239. };
  1240. typedef std::shared_ptr<vk_context_struct> vk_context;
  1241. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  1242. struct ggml_vk_garbage_collector {
  1243. std::vector<vk_semaphore> tl_semaphores;
  1244. std::vector<vk_semaphore> semaphores;
  1245. std::vector<vk::Event> events;
  1246. std::vector<vk_context> contexts;
  1247. };
  1248. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx);
  1249. static void ggml_vk_load_shaders(vk_device& device);
  1250. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx);
  1251. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  1252. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  1253. static std::string format_size(size_t size) {
  1254. const size_t kib = 1024;
  1255. const size_t mib = kib * 1024;
  1256. const size_t gib = mib * 1024;
  1257. std::ostringstream oss;
  1258. oss << std::fixed << std::setprecision(2);
  1259. if (size >= gib) {
  1260. oss << static_cast<double>(size) / gib << " GiB";
  1261. } else if (size >= mib) {
  1262. oss << static_cast<double>(size) / mib << " MiB";
  1263. } else if (size >= kib) {
  1264. oss << static_cast<double>(size) / kib << " KiB";
  1265. } else {
  1266. oss << size << " B";
  1267. }
  1268. return oss.str();
  1269. }
  1270. class vk_memory_logger {
  1271. public:
  1272. vk_memory_logger(): total_device(0), total_host(0) {}
  1273. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  1274. void log_deallocation(vk_buffer_ref buf_ref);
  1275. private:
  1276. std::map<vk::Buffer, size_t> allocations; // Track allocations
  1277. size_t total_device;
  1278. size_t total_host;
  1279. };
  1280. #else
  1281. #define VK_LOG_MEMORY(msg) ((void) 0)
  1282. #endif // GGML_VULKAN_MEMORY_DEBUG
  1283. class vk_perf_logger {
  1284. public:
  1285. void print_timings() {
  1286. if (timings.empty()) {
  1287. return;
  1288. }
  1289. uint64_t total_all_op_times = 0;
  1290. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  1291. for (const auto & t : timings) {
  1292. uint64_t total_op_times = 0;
  1293. for (const auto & time : t.second) {
  1294. total_op_times += time;
  1295. }
  1296. std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0)
  1297. << " us";
  1298. // If we have as many flops entries as timing entries for the op, then compute and log the flops/S.
  1299. auto it = flops.find(t.first);
  1300. if (it != flops.end() && (it->second).size() == t.second.size()) {
  1301. uint64_t total_op_flops = 0;
  1302. for (const auto & elem : it->second) {
  1303. total_op_flops += elem;
  1304. }
  1305. std::cerr << " ("
  1306. << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) /
  1307. (double(total_op_times) / (1000.0 * 1000.0 * 1000.0))
  1308. << " GFLOPS/s)";
  1309. }
  1310. total_all_op_times += total_op_times;
  1311. std::cerr << std::endl;
  1312. }
  1313. if (timings.size() > 0) {
  1314. std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl;
  1315. }
  1316. timings.clear();
  1317. flops.clear();
  1318. }
  1319. void log_timing(const ggml_tensor * node, uint64_t time) {
  1320. if (node->op == GGML_OP_UNARY) {
  1321. timings[ggml_unary_op_name(ggml_get_unary_op(node))].push_back(time);
  1322. return;
  1323. }
  1324. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  1325. const uint64_t m = node->src[0]->ne[1];
  1326. const uint64_t n = node->ne[1];
  1327. const uint64_t k = node->src[1]->ne[0];
  1328. const uint64_t batch = node->src[1]->ne[2] * node->src[1]->ne[3];
  1329. std::string name = ggml_op_name(node->op);
  1330. if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) ||
  1331. (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) {
  1332. name += "_VEC";
  1333. }
  1334. name += " ";
  1335. name += ggml_type_name(node->src[0]->type);
  1336. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  1337. if (batch > 1) {
  1338. name += " batch=" + std::to_string(batch);
  1339. }
  1340. timings[name].push_back(time);
  1341. flops[name].push_back(m * n * (k + (k - 1)) * batch);
  1342. return;
  1343. }
  1344. if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) {
  1345. std::string name = ggml_op_name(node->op);
  1346. ggml_tensor * knl = node->src[0];
  1347. uint64_t OW = node->ne[0];
  1348. uint64_t OH = node->ne[1];
  1349. uint64_t N = node->ne[3];
  1350. uint64_t Cout = node->ne[2];
  1351. uint64_t KW = knl->ne[0];
  1352. uint64_t KH = knl->ne[1];
  1353. uint64_t Cin = node->src[1]->ne[2];
  1354. // KxCRS @ CRSxNPQ = KxNPQ -> M=K, K=CRS, N=NPQ
  1355. uint64_t size_M = Cout;
  1356. uint64_t size_K = Cin * KW * KH;
  1357. uint64_t size_N = N * OW * OH;
  1358. uint64_t n_flops = size_M * size_N * (size_K + (size_K - 1));
  1359. name += " M=Cout=" + std::to_string(size_M) + ", K=Cin*KW*KH=" + std::to_string(size_K) +
  1360. ", N=N*OW*OH=" + std::to_string(size_N);
  1361. flops[name].push_back(n_flops);
  1362. timings[name].push_back(time);
  1363. return;
  1364. }
  1365. if (node->op == GGML_OP_RMS_NORM) {
  1366. std::string name = ggml_op_name(node->op);
  1367. 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]) + ")";
  1368. timings[name].push_back(time);
  1369. return;
  1370. }
  1371. timings[ggml_op_name(node->op)].push_back(time);
  1372. }
  1373. private:
  1374. std::map<std::string, std::vector<uint64_t>> timings;
  1375. std::map<std::string, std::vector<uint64_t>> flops;
  1376. };
  1377. struct ggml_backend_vk_context {
  1378. std::string name;
  1379. vk_device device;
  1380. size_t semaphore_idx, event_idx;
  1381. ggml_vk_garbage_collector gc;
  1382. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset;
  1383. vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials, sync_staging;
  1384. vk::Fence fence, almost_ready_fence;
  1385. bool submit_pending {};
  1386. bool almost_ready_fence_pending {};
  1387. // Set before op_add and unset after op_rms_norm to indicate that the add should
  1388. // write partial sums to accumulate the square of the vector components
  1389. bool do_add_rms_partials_offset_calculation;
  1390. bool do_add_rms_partials;
  1391. uint64_t last_total_mul_mat_bytes {};
  1392. // Cache most recent tensor that was converted into prealloc_y, and what pipeline it used to convert.
  1393. vk_pipeline_struct * prealloc_y_last_pipeline_used {};
  1394. const ggml_tensor * prealloc_y_last_tensor_used {};
  1395. // Track which nodes have been used since the last sync, and whether they were written to
  1396. std::vector<const ggml_tensor *> unsynced_nodes_written;
  1397. std::vector<const ggml_tensor *> unsynced_nodes_read;
  1398. // Track which prealloc buffers have pending reads that need to be synchronized.
  1399. // These are checked before writing to the buffer (and call ggml_vk_sync_buffers if set),
  1400. // and set to true after the buffer contents are consumed.
  1401. bool prealloc_x_need_sync, prealloc_y_need_sync, prealloc_split_k_need_sync;
  1402. vk_context_ref compute_ctx;
  1403. vk_context_ref transfer_ctx;
  1404. std::vector<vk_context_ref> tensor_ctxs;
  1405. std::vector<vk::DescriptorPool> descriptor_pools;
  1406. std::vector<vk::DescriptorSet> descriptor_sets;
  1407. uint32_t descriptor_set_idx {};
  1408. uint32_t pipeline_descriptor_set_requirements {};
  1409. vk_command_pool compute_cmd_pool;
  1410. vk_command_pool transfer_cmd_pool;
  1411. // number of additional consecutive nodes that are being fused with the
  1412. // node currently being processed
  1413. int num_additional_fused_ops {};
  1414. // Bitmask of which fused ops need to write an intermediate value to memory.
  1415. // Bit 'i' means nodes[start_of_fusion + i] writes to memory.
  1416. // If there's no fusion, bit 0 is still set.
  1417. int fused_ops_write_mask {};
  1418. };
  1419. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  1420. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  1421. if (tensor->view_src) {
  1422. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  1423. }
  1424. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  1425. }
  1426. static uint32_t get_misalign_bytes(const ggml_backend_vk_context * ctx, const ggml_tensor * t)
  1427. {
  1428. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  1429. }
  1430. 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) {
  1431. GGML_UNUSED(p);
  1432. GGML_UNUSED(src0);
  1433. GGML_UNUSED(src1);
  1434. GGML_UNUSED(src2);
  1435. GGML_UNUSED(src3);
  1436. GGML_UNUSED(dst);
  1437. static_assert(!std::is_const<T>::value, "unexpected type");
  1438. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  1439. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  1440. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  1441. GGML_ASSERT(!src3 || get_misalign_bytes(ctx, src3) == 0);
  1442. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  1443. }
  1444. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_mat_vec_p021_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  1445. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1446. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1447. p.b_offset = b_offset;
  1448. p.d_offset = d_offset;
  1449. GGML_UNUSED(src0);
  1450. GGML_UNUSED(src2);
  1451. GGML_UNUSED(src3);
  1452. }
  1453. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_mat_vec_nc_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  1454. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1455. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1456. p.b_offset = b_offset;
  1457. p.d_offset = d_offset;
  1458. GGML_UNUSED(src0);
  1459. GGML_UNUSED(src2);
  1460. GGML_UNUSED(src3);
  1461. }
  1462. struct ggml_backend_vk_buffer_context {
  1463. vk_device_ref device;
  1464. vk_buffer dev_buffer;
  1465. std::string name;
  1466. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  1467. device(device),
  1468. dev_buffer(dev_buffer),
  1469. name(name) {
  1470. }
  1471. ~ggml_backend_vk_buffer_context() {
  1472. ggml_vk_destroy_buffer(dev_buffer);
  1473. }
  1474. };
  1475. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1476. static std::mutex log_mutex;
  1477. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  1478. std::lock_guard<std::mutex> guard(log_mutex);
  1479. vk_buffer buf = buf_ref.lock();
  1480. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1481. const std::string type = device ? "device" : "host";
  1482. allocations[buf->buffer] = size;
  1483. total_device += device ? size : 0;
  1484. total_host += device ? 0 : size;
  1485. 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));
  1486. }
  1487. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  1488. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  1489. return;
  1490. }
  1491. std::lock_guard<std::mutex> guard(log_mutex);
  1492. vk_buffer buf = buf_ref.lock();
  1493. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1494. std::string type = device ? "device" : "host";
  1495. auto it = allocations.find(buf->buffer);
  1496. total_device -= device ? it->second : 0;
  1497. total_host -= device ? 0 : it->second;
  1498. if (it != allocations.end()) {
  1499. 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));
  1500. allocations.erase(it);
  1501. } else {
  1502. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  1503. }
  1504. }
  1505. #endif // GGML_VULKAN_MEMORY_DEBUG
  1506. struct vk_instance_t {
  1507. vk::Instance instance;
  1508. bool debug_utils_support = false; // VK_EXT_debug_utils enabled
  1509. PFN_vkSetDebugUtilsObjectNameEXT pfn_vkSetDebugUtilsObjectNameEXT = {};
  1510. PFN_vkQueueBeginDebugUtilsLabelEXT pfn_vkQueueBeginDebugUtilsLabelEXT = {};
  1511. PFN_vkQueueEndDebugUtilsLabelEXT pfn_vkQueueEndDebugUtilsLabelEXT = {};
  1512. PFN_vkCmdBeginDebugUtilsLabelEXT pfn_vkCmdBeginDebugUtilsLabelEXT = {};
  1513. PFN_vkCmdEndDebugUtilsLabelEXT pfn_vkCmdEndDebugUtilsLabelEXT = {};
  1514. PFN_vkCmdInsertDebugUtilsLabelEXT pfn_vkCmdInsertDebugUtilsLabelEXT = {};
  1515. std::vector<size_t> device_indices;
  1516. std::vector<bool> device_supports_membudget;
  1517. vk_device devices[GGML_VK_MAX_DEVICES];
  1518. };
  1519. static bool vk_instance_initialized = false;
  1520. static vk_instance_t vk_instance;
  1521. static bool vk_perf_logger_enabled = false;
  1522. #ifdef GGML_VULKAN_CHECK_RESULTS
  1523. static size_t vk_skip_checks;
  1524. static size_t vk_output_tensor;
  1525. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  1526. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1527. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1528. #endif
  1529. 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);
  1530. static void ggml_backend_vk_free(ggml_backend_t backend);
  1531. static VkDeviceSize ggml_vk_get_max_buffer_range(const ggml_backend_vk_context * ctx, const vk_buffer &buf, const VkDeviceSize offset) {
  1532. const VkDeviceSize range = std::min(VkDeviceSize{buf->size - offset},
  1533. VkDeviceSize{ctx->device->properties.limits.maxStorageBufferRange});
  1534. return range;
  1535. }
  1536. // Wait for ctx->fence to be signaled.
  1537. static void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) {
  1538. // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep
  1539. // during this wait.
  1540. if (ctx->almost_ready_fence_pending) {
  1541. VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence");
  1542. ctx->device->device.resetFences({ ctx->almost_ready_fence });
  1543. ctx->almost_ready_fence_pending = false;
  1544. }
  1545. // Spin (w/pause) waiting for the graph to finish executing.
  1546. vk::Result result;
  1547. while ((result = ctx->device->device.getFenceStatus(ctx->fence)) != vk::Result::eSuccess) {
  1548. if (result != vk::Result::eNotReady) {
  1549. fprintf(stderr, "ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__);
  1550. exit(1);
  1551. }
  1552. for (uint32_t i = 0; i < 100; ++i) {
  1553. YIELD();
  1554. YIELD();
  1555. YIELD();
  1556. YIELD();
  1557. YIELD();
  1558. YIELD();
  1559. YIELD();
  1560. YIELD();
  1561. YIELD();
  1562. YIELD();
  1563. }
  1564. }
  1565. ctx->device->device.resetFences({ ctx->fence });
  1566. }
  1567. // variables to track number of compiles in progress
  1568. static uint32_t compile_count = 0;
  1569. static std::mutex compile_count_mutex;
  1570. static std::condition_variable compile_count_cond;
  1571. 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,
  1572. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  1573. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  1574. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  1575. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  1576. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  1577. GGML_ASSERT(parameter_count > 0);
  1578. GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT);
  1579. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  1580. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  1581. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  1582. vk::PushConstantRange pcr(
  1583. vk::ShaderStageFlagBits::eCompute,
  1584. 0,
  1585. pipeline->push_constant_size
  1586. );
  1587. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr);
  1588. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  1589. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  1590. for (size_t i = 0; i < specialization_constants.size(); i++) {
  1591. specialization_entries[i].constantID = i;
  1592. specialization_entries[i].offset = i * sizeof(uint32_t);
  1593. specialization_entries[i].size = sizeof(uint32_t);
  1594. }
  1595. vk::SpecializationInfo specialization_info(
  1596. specialization_entries.size(),
  1597. specialization_entries.data(),
  1598. specialization_constants.size() * sizeof(uint32_t),
  1599. specialization_constants.data()
  1600. );
  1601. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  1602. if (device->subgroup_require_full_support && require_full_subgroups) {
  1603. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  1604. }
  1605. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  1606. pipeline_shader_stage_create_flags,
  1607. vk::ShaderStageFlagBits::eCompute,
  1608. pipeline->shader_module,
  1609. entrypoint.c_str(),
  1610. &specialization_info);
  1611. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  1612. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  1613. if (device->subgroup_size_control && required_subgroup_size > 0) {
  1614. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  1615. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  1616. }
  1617. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  1618. device->pipeline_executable_properties_support ?
  1619. vk::PipelineCreateFlagBits::eCaptureStatisticsKHR :
  1620. vk::PipelineCreateFlags{},
  1621. pipeline_shader_create_info,
  1622. pipeline->layout);
  1623. vk::PipelineRobustnessCreateInfoEXT rci;
  1624. if (device->pipeline_robustness && disable_robustness) {
  1625. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1626. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1627. compute_pipeline_create_info.setPNext(&rci);
  1628. }
  1629. try {
  1630. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  1631. } catch (const vk::SystemError& e) {
  1632. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  1633. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1634. throw e;
  1635. }
  1636. pipeline->compiled = true;
  1637. if (vk_instance.debug_utils_support) {
  1638. vk::DebugUtilsObjectNameInfoEXT duoni;
  1639. duoni.objectType = vk::ObjectType::ePipeline;
  1640. duoni.pObjectName = pipeline->name.c_str();
  1641. duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast<VkPipeline>(pipeline->pipeline));
  1642. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast<VkDebugUtilsObjectNameInfoEXT &>(duoni));
  1643. }
  1644. if (device->pipeline_executable_properties_support) {
  1645. vk::PipelineExecutableInfoKHR executableInfo;
  1646. executableInfo.pipeline = pipeline->pipeline;
  1647. auto statistics = device->device.getPipelineExecutableStatisticsKHR(executableInfo);
  1648. for (auto & s : statistics) {
  1649. // "Register Count" is reported by NVIDIA drivers.
  1650. if (strcmp(s.name, "Register Count") == 0) {
  1651. VK_LOG_DEBUG(pipeline->name << " " << s.name << ": " << s.value.u64 << " registers");
  1652. pipeline->register_count = (uint32_t)s.value.u64;
  1653. }
  1654. }
  1655. }
  1656. device->all_pipelines.push_back(pipeline);
  1657. {
  1658. std::lock_guard<std::mutex> guard(compile_count_mutex);
  1659. assert(compile_count > 0);
  1660. compile_count--;
  1661. }
  1662. compile_count_cond.notify_all();
  1663. }
  1664. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  1665. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  1666. device.destroyPipelineLayout(pipeline->layout);
  1667. device.destroyShaderModule(pipeline->shader_module);
  1668. device.destroyPipeline(pipeline->pipeline);
  1669. }
  1670. static void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) {
  1671. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  1672. ctx->pipeline_descriptor_set_requirements += n;
  1673. if (!pipeline->compiled) {
  1674. pipeline->needed = true;
  1675. ggml_vk_load_shaders(ctx->device);
  1676. }
  1677. ggml_pipeline_allocate_descriptor_sets(ctx);
  1678. }
  1679. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
  1680. if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) {
  1681. // Enough descriptors are available
  1682. return;
  1683. }
  1684. vk_device& device = ctx->device;
  1685. // Grow by 50% to avoid frequent allocations
  1686. uint32_t needed = std::max(3 * ctx->descriptor_sets.size() / 2, size_t{ctx->pipeline_descriptor_set_requirements});
  1687. uint32_t to_alloc = needed - ctx->descriptor_sets.size();
  1688. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1689. uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1690. while (to_alloc > 0) {
  1691. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  1692. to_alloc -= alloc_count;
  1693. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1694. if (pool_idx >= ctx->descriptor_pools.size()) {
  1695. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  1696. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  1697. ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  1698. }
  1699. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  1700. for (uint32_t i = 0; i < alloc_count; i++) {
  1701. layouts[i] = device->dsl;
  1702. }
  1703. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
  1704. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  1705. ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
  1706. pool_idx++;
  1707. }
  1708. }
  1709. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) {
  1710. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  1711. if (p.cmd_buffers.size() > p.cmd_buffer_idx) {
  1712. // Reuse command buffer
  1713. return p.cmd_buffers[p.cmd_buffer_idx++];
  1714. }
  1715. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  1716. p.pool,
  1717. vk::CommandBufferLevel::ePrimary,
  1718. 1);
  1719. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  1720. auto buf = cmd_buffers.front();
  1721. p.cmd_buffers.push_back(buf);
  1722. p.cmd_buffer_idx++;
  1723. return buf;
  1724. }
  1725. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  1726. if (ctx->seqs.empty()) {
  1727. if (fence) {
  1728. std::lock_guard<std::mutex> guard(queue_mutex);
  1729. ctx->p->q->queue.submit({}, fence);
  1730. }
  1731. return;
  1732. }
  1733. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  1734. std::vector<std::vector<uint64_t>> tl_wait_vals;
  1735. std::vector<std::vector<uint64_t>> tl_signal_vals;
  1736. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  1737. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  1738. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  1739. std::vector<vk::SubmitInfo> submit_infos;
  1740. int idx = -1;
  1741. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  1742. size_t reserve = 0;
  1743. for (const auto& sequence : ctx->seqs) {
  1744. reserve += sequence.size();
  1745. }
  1746. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  1747. tl_wait_semaphores.reserve(reserve);
  1748. tl_wait_vals.reserve(reserve);
  1749. tl_signal_semaphores.reserve(reserve);
  1750. tl_signal_vals.reserve(reserve);
  1751. tl_submit_infos.reserve(reserve);
  1752. submit_infos.reserve(reserve);
  1753. stage_flags.reserve(reserve);
  1754. for (const auto& sequence : ctx->seqs) {
  1755. for (const auto& submission : sequence) {
  1756. stage_flags.push_back({});
  1757. idx++;
  1758. tl_wait_vals.push_back({});
  1759. tl_wait_semaphores.push_back({});
  1760. tl_signal_vals.push_back({});
  1761. tl_signal_semaphores.push_back({});
  1762. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  1763. stage_flags[idx].push_back(ctx->p->q->stage_flags);
  1764. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  1765. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  1766. }
  1767. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  1768. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  1769. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  1770. }
  1771. tl_submit_infos.push_back({
  1772. (uint32_t) submission.wait_semaphores.size(),
  1773. tl_wait_vals[idx].data(),
  1774. (uint32_t) submission.signal_semaphores.size(),
  1775. tl_signal_vals[idx].data(),
  1776. });
  1777. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  1778. tl_submit_infos[idx].pNext = nullptr;
  1779. vk::SubmitInfo si{
  1780. (uint32_t) submission.wait_semaphores.size(),
  1781. tl_wait_semaphores[idx].data(),
  1782. stage_flags[idx].data(),
  1783. 1,
  1784. &submission.buffer,
  1785. (uint32_t) submission.signal_semaphores.size(),
  1786. tl_signal_semaphores[idx].data(),
  1787. };
  1788. si.setPNext(&tl_submit_infos[idx]);
  1789. submit_infos.push_back(si);
  1790. }
  1791. }
  1792. std::lock_guard<std::mutex> guard(queue_mutex);
  1793. ctx->p->q->queue.submit(submit_infos, fence);
  1794. ctx->seqs.clear();
  1795. }
  1796. 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) {
  1797. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  1798. const uint32_t qfsize = queue_family_props.size();
  1799. // Try with avoid preferences first
  1800. for (uint32_t i = 0; i < qfsize; i++) {
  1801. 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)) {
  1802. return i;
  1803. }
  1804. }
  1805. // Fall back to only required
  1806. for (size_t i = 0; i < qfsize; i++) {
  1807. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  1808. return i;
  1809. }
  1810. }
  1811. // Fall back to reusing compute queue
  1812. for (size_t i = 0; i < qfsize; i++) {
  1813. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  1814. return i;
  1815. }
  1816. }
  1817. // Fall back to ignoring min_num_queries
  1818. for (size_t i = 0; i < qfsize; i++) {
  1819. if (queue_family_props[i].queueFlags & required) {
  1820. return i;
  1821. }
  1822. }
  1823. // 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.
  1824. // 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.
  1825. if (compute_index >= 0) {
  1826. return compute_index;
  1827. }
  1828. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  1829. for(auto &q_family : queue_family_props) {
  1830. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  1831. }
  1832. abort();
  1833. }
  1834. 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) {
  1835. VK_LOG_DEBUG("ggml_vk_create_queue()");
  1836. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1837. q.queue_family_index = queue_family_index;
  1838. q.transfer_only = transfer_only;
  1839. q.cmd_pool.init(device, &q);
  1840. q.queue = device->device.getQueue(queue_family_index, queue_index);
  1841. q.stage_flags = stage_flags;
  1842. }
  1843. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) {
  1844. vk_context result = std::make_shared<vk_context_struct>();
  1845. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  1846. ctx->gc.contexts.emplace_back(result);
  1847. result->p = &p;
  1848. return result;
  1849. }
  1850. static vk_context ggml_vk_create_temporary_context(vk_command_pool& p) {
  1851. vk_context result = std::make_shared<vk_context_struct>();
  1852. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  1853. result->p = &p;
  1854. return result;
  1855. }
  1856. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  1857. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1858. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  1859. vk::SemaphoreCreateInfo ci{};
  1860. ci.setPNext(&tci);
  1861. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1862. ctx->gc.semaphores.push_back({ semaphore, 0 });
  1863. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  1864. }
  1865. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  1866. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1867. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  1868. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  1869. vk::SemaphoreCreateInfo ci{};
  1870. ci.setPNext(&tci);
  1871. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1872. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  1873. }
  1874. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  1875. }
  1876. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  1877. if (ctx->event_idx >= ctx->gc.events.size()) {
  1878. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  1879. }
  1880. return ctx->gc.events[ctx->event_idx++];
  1881. }
  1882. static void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) {
  1883. VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()");
  1884. // Requires command buffers to be done
  1885. device->device.resetCommandPool(p.pool);
  1886. p.cmd_buffer_idx = 0;
  1887. }
  1888. static void ggml_vk_queue_command_pools_cleanup(vk_device& device) {
  1889. VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()");
  1890. // Arbitrary frequency to cleanup/reuse command buffers
  1891. static constexpr uint32_t cleanup_frequency = 10;
  1892. if (device->compute_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1893. ggml_vk_command_pool_cleanup(device, device->compute_queue.cmd_pool);
  1894. }
  1895. if (device->transfer_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1896. ggml_vk_command_pool_cleanup(device, device->transfer_queue.cmd_pool);
  1897. }
  1898. }
  1899. static std::vector<uint32_t> ggml_vk_find_memory_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  1900. std::vector<uint32_t> indices;
  1901. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  1902. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  1903. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  1904. (flags & memory_type.propertyFlags) == flags &&
  1905. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  1906. indices.push_back(i);
  1907. }
  1908. }
  1909. return indices;
  1910. }
  1911. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, const std::initializer_list<vk::MemoryPropertyFlags> & req_flags_list) {
  1912. 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]) << ")");
  1913. if (size > device->max_buffer_size) {
  1914. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device buffer size limit");
  1915. }
  1916. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  1917. if (size == 0) {
  1918. buf->size = 0;
  1919. return buf;
  1920. }
  1921. vk::BufferUsageFlags usage_flags = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst;
  1922. vk::MemoryAllocateFlags mem_flags {};
  1923. if (device->buffer_device_address) {
  1924. usage_flags |= vk::BufferUsageFlagBits::eShaderDeviceAddress;
  1925. mem_flags |= vk::MemoryAllocateFlagBits::eDeviceAddress;
  1926. }
  1927. vk::BufferCreateInfo buffer_create_info{
  1928. vk::BufferCreateFlags(),
  1929. size,
  1930. usage_flags,
  1931. vk::SharingMode::eExclusive,
  1932. 0,
  1933. nullptr,
  1934. };
  1935. buf->buffer = device->device.createBuffer(buffer_create_info);
  1936. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  1937. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  1938. const vk::MemoryAllocateFlagsInfo mem_flags_info { mem_flags };
  1939. for (auto it = req_flags_list.begin(); it != req_flags_list.end(); it++) {
  1940. const auto & req_flags = *it;
  1941. const std::vector<uint32_t> memory_type_indices = ggml_vk_find_memory_properties(&mem_props, &mem_req, req_flags);
  1942. if (memory_type_indices.empty()) {
  1943. continue;
  1944. }
  1945. buf->memory_property_flags = req_flags;
  1946. bool done = false;
  1947. for (auto mtype_it = memory_type_indices.begin(); mtype_it != memory_type_indices.end(); mtype_it++) {
  1948. try {
  1949. buf->device_memory = device->device.allocateMemory({ mem_req.size, *mtype_it, &mem_flags_info });
  1950. done = true;
  1951. break;
  1952. } catch (const vk::SystemError& e) {
  1953. // loop and retry
  1954. // during last attempt throw the exception
  1955. if (it + 1 == req_flags_list.end() && mtype_it + 1 == memory_type_indices.end()) {
  1956. device->device.destroyBuffer(buf->buffer);
  1957. throw e;
  1958. }
  1959. }
  1960. }
  1961. if (done) {
  1962. break;
  1963. }
  1964. }
  1965. if (!buf->device_memory) {
  1966. device->device.destroyBuffer(buf->buffer);
  1967. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  1968. }
  1969. buf->ptr = nullptr;
  1970. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1971. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  1972. }
  1973. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  1974. buf->device = device;
  1975. buf->size = size;
  1976. if (device->buffer_device_address) {
  1977. const vk::BufferDeviceAddressInfo addressInfo(buf->buffer);
  1978. buf->bda_addr = device->device.getBufferAddress(addressInfo);
  1979. }
  1980. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1981. device->memory_logger->log_allocation(buf, size);
  1982. #endif
  1983. return buf;
  1984. }
  1985. 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)) {
  1986. try {
  1987. return ggml_vk_create_buffer(device, size, {req_flags, fallback_flags});
  1988. } catch (const vk::SystemError& e) {
  1989. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  1990. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1991. throw e;
  1992. }
  1993. }
  1994. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  1995. vk_buffer buf;
  1996. try {
  1997. if (device->prefer_host_memory) {
  1998. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1999. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2000. } else if (device->uma) {
  2001. // Fall back to host memory type
  2002. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2003. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2004. } else if (device->disable_host_visible_vidmem) {
  2005. if (device->allow_sysmem_fallback) {
  2006. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2007. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2008. } else {
  2009. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  2010. }
  2011. } else {
  2012. // use rebar if available, otherwise fallback to device only visible memory
  2013. if (device->allow_sysmem_fallback) {
  2014. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2015. vk::MemoryPropertyFlagBits::eDeviceLocal,
  2016. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2017. } else {
  2018. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2019. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2020. }
  2021. }
  2022. } catch (const vk::SystemError& e) {
  2023. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  2024. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  2025. throw e;
  2026. }
  2027. return buf;
  2028. }
  2029. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  2030. if (buf == nullptr) {
  2031. return;
  2032. }
  2033. #ifdef GGML_VULKAN_MEMORY_DEBUG
  2034. if (buf->device != nullptr) {
  2035. buf->device->memory_logger->log_deallocation(buf);
  2036. }
  2037. #endif
  2038. buf.reset();
  2039. }
  2040. static vk_subbuffer ggml_vk_subbuffer(const ggml_backend_vk_context* ctx, const vk_buffer& buf, size_t offset = 0) {
  2041. return { buf, offset, ggml_vk_get_max_buffer_range(ctx, buf, offset) };
  2042. }
  2043. static void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) {
  2044. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  2045. const bool transfer_queue = subctx->p->q->transfer_only;
  2046. if (ctx) {
  2047. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  2048. }
  2049. subctx->s->buffer.pipelineBarrier(
  2050. subctx->p->q->stage_flags,
  2051. subctx->p->q->stage_flags,
  2052. {},
  2053. { {
  2054. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  2055. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  2056. } },
  2057. {},
  2058. {}
  2059. );
  2060. }
  2061. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  2062. VK_LOG_DEBUG("ggml_vk_wait_events()");
  2063. if (events.empty()) {
  2064. return;
  2065. }
  2066. ctx->s->buffer.waitEvents(
  2067. events,
  2068. ctx->p->q->stage_flags,
  2069. ctx->p->q->stage_flags,
  2070. {},
  2071. {},
  2072. {}
  2073. );
  2074. }
  2075. // number of rows/cols for flash attention shader
  2076. static constexpr uint32_t flash_attention_num_small_rows = 32;
  2077. static constexpr uint32_t scalar_flash_attention_num_small_rows = 1;
  2078. static uint32_t get_fa_scalar_num_large_rows(uint32_t hsv) {
  2079. if (hsv >= 192) {
  2080. return 2;
  2081. } else {
  2082. return 8;
  2083. }
  2084. }
  2085. // The FA coopmat1 shader assumes 16x16x16 matrix multiply support.
  2086. // 128 threads split into four subgroups, each subgroup does 1/4
  2087. // of the Bc dimension.
  2088. static constexpr uint32_t coopmat1_flash_attention_num_large_rows = 16;
  2089. static constexpr uint32_t scalar_flash_attention_Bc = 64;
  2090. static constexpr uint32_t scalar_flash_attention_workgroup_size = 128;
  2091. static uint32_t get_fa_num_small_rows(FaCodePath path) {
  2092. if (path == FA_COOPMAT2) {
  2093. return flash_attention_num_small_rows;
  2094. } else {
  2095. return scalar_flash_attention_num_small_rows;
  2096. }
  2097. }
  2098. 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) {
  2099. GGML_UNUSED(clamp);
  2100. GGML_UNUSED(hsv);
  2101. if (path == FA_SCALAR) {
  2102. if (small_rows) {
  2103. return {scalar_flash_attention_num_small_rows, 64};
  2104. } else {
  2105. if ((hsv | hsk) & 8) {
  2106. // HSV/HSK not being a multiple of 16 makes D_split smaller, which makes cols_per_iter
  2107. // larger, and Bc needs to be >= cols_per_thread. 64 is large enough, 32 is not.
  2108. return {get_fa_scalar_num_large_rows(hsv), 64};
  2109. } else {
  2110. return {get_fa_scalar_num_large_rows(hsv), 32};
  2111. }
  2112. }
  2113. }
  2114. if (path == FA_COOPMAT1) {
  2115. if (small_rows) {
  2116. return {scalar_flash_attention_num_small_rows, scalar_flash_attention_Bc};
  2117. } else {
  2118. return {coopmat1_flash_attention_num_large_rows, scalar_flash_attention_Bc};
  2119. }
  2120. }
  2121. // small rows, large cols
  2122. if (small_rows) {
  2123. return {get_fa_num_small_rows(FA_COOPMAT2), 32};
  2124. }
  2125. // small cols to reduce register count
  2126. if (ggml_is_quantized(type) || hsk >= 256 || hsv >= 256) {
  2127. if (hsk >= 512 || hsv >= 512) {
  2128. return {32, 32};
  2129. } else {
  2130. return {64, 32};
  2131. }
  2132. }
  2133. return {64, 64};
  2134. }
  2135. static uint32_t fa_align(FaCodePath path, uint32_t hsk, uint32_t hsv, ggml_type type, bool small_rows) {
  2136. return fa_rows_cols(path, hsk, hsv, 0, type, small_rows)[1];
  2137. }
  2138. 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) {
  2139. uint32_t lut_size = 0;
  2140. switch (src0_type) {
  2141. case GGML_TYPE_IQ1_S:
  2142. case GGML_TYPE_IQ1_M:
  2143. lut_size = 2*2048;
  2144. break;
  2145. case GGML_TYPE_IQ2_XXS:
  2146. lut_size = 8*256;
  2147. break;
  2148. case GGML_TYPE_IQ2_XS:
  2149. lut_size = 8*512;
  2150. break;
  2151. case GGML_TYPE_IQ2_S:
  2152. lut_size = 8*1024;
  2153. break;
  2154. case GGML_TYPE_IQ3_XXS:
  2155. lut_size = 4*256;
  2156. break;
  2157. case GGML_TYPE_IQ3_S:
  2158. lut_size = 4*512;
  2159. break;
  2160. case GGML_TYPE_IQ4_NL:
  2161. case GGML_TYPE_IQ4_XS:
  2162. case GGML_TYPE_MXFP4:
  2163. lut_size = 4*16;
  2164. break;
  2165. default:
  2166. break;
  2167. }
  2168. // Needs to be kept up to date on shader changes
  2169. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  2170. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  2171. const uint32_t warps = warptile[0] / warptile[10];
  2172. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  2173. const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0;
  2174. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  2175. const uint32_t ballots_sh = mul_mat_id ? (warps * 4 * sizeof(uint32_t)) : 0;
  2176. const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size + ballots_sh;
  2177. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  2178. VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), "
  2179. "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported);
  2180. return supported;
  2181. }
  2182. struct GpuPipelineConfig {
  2183. // GPU architecture identifier.
  2184. // Example: vk_device_architecture::AMD_GCN
  2185. vk_device_architecture arch;
  2186. // Mapping of pipeline names to their specific subgroup sizes.
  2187. // Example: {"soft_max_f32", 64}
  2188. std::unordered_map<std::string, uint32_t> pipelines;
  2189. // Default subgroup size for this GPU.
  2190. // Defaults to 0 if not explicitly provided.
  2191. uint32_t default_subgroup_size = 0;
  2192. };
  2193. // Pipeline configuration for RDNA1 GPUs.
  2194. static const std::unordered_map<std::string, uint32_t> rdna1_pipelines = {
  2195. {"soft_max", 64}, {"im2col", 64},
  2196. {"argmax", 64}, {"mul_mat_vec", 64},
  2197. {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32}
  2198. };
  2199. // Pipeline configuration for RDNA2 GPUs.
  2200. static const std::unordered_map<std::string, uint32_t> rdna2_pipelines = {
  2201. {"soft_max", 64}, {"im2col", 64},
  2202. };
  2203. static constexpr uint32_t RDNA_DEFAULT_SUBGROUP_SIZE = 32;
  2204. // Define configurations for different GPUs.
  2205. static std::vector<GpuPipelineConfig> gpu_pipeline_configs = {
  2206. {
  2207. vk_device_architecture::AMD_RDNA1,
  2208. {
  2209. rdna1_pipelines,
  2210. },
  2211. RDNA_DEFAULT_SUBGROUP_SIZE
  2212. },
  2213. {
  2214. vk_device_architecture::AMD_RDNA2,
  2215. {
  2216. rdna2_pipelines,
  2217. },
  2218. RDNA_DEFAULT_SUBGROUP_SIZE
  2219. },
  2220. };
  2221. static uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) {
  2222. for (const auto &config : gpu_pipeline_configs) {
  2223. if (config.arch == arch) {
  2224. auto pipIt = config.pipelines.find(pipeline_name);
  2225. if (pipIt != config.pipelines.end()) {
  2226. return pipIt->second;
  2227. }
  2228. std::vector<std::pair<std::string, uint32_t>> sorted_pipelines(config.pipelines.begin(), config.pipelines.end());
  2229. std::sort(sorted_pipelines.begin(), sorted_pipelines.end(),
  2230. [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
  2231. for (const auto &entry : sorted_pipelines) {
  2232. if (pipeline_name.find(entry.first) != std::string::npos) {
  2233. return entry.second;
  2234. }
  2235. }
  2236. return config.default_subgroup_size;
  2237. }
  2238. }
  2239. return 0; // If no matching configuration is found
  2240. }
  2241. static void ggml_vk_load_shaders(vk_device& device) {
  2242. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  2243. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  2244. // some shaders have a minimum subgroup size
  2245. const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u);
  2246. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  2247. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  2248. 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;
  2249. const uint32_t mul_mat_subgroup_size_8 = std::max(mul_mat_subgroup_size, 8u);
  2250. const uint32_t mul_mat_subgroup_size_16 = std::max(mul_mat_subgroup_size, 16u);
  2251. const uint32_t mul_mat_subgroup_size_32 = std::max(mul_mat_subgroup_size, 32u);
  2252. const bool subgroup_min_size_16 = (!device->subgroup_size_control && device->subgroup_size >= 16) ||
  2253. (device->subgroup_size_control && device->subgroup_max_size >= 16);
  2254. // mulmat
  2255. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  2256. l_warptile_id, m_warptile_id, s_warptile_id,
  2257. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  2258. l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int,
  2259. l_warptile_mmq_int_k, m_warptile_mmq_int_k, s_warptile_mmq_int_k,
  2260. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  2261. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid,
  2262. l_warptile_mmqid_int, m_warptile_mmqid_int, s_warptile_mmqid_int,
  2263. l_warptile_mmqid_int_k, m_warptile_mmqid_int_k, s_warptile_mmqid_int_k;
  2264. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  2265. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  2266. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  2267. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  2268. uint32_t l_align, m_align, s_align;
  2269. if (device->coopmat2) {
  2270. // spec constants and tile sizes for non-quant matmul/matmul_id
  2271. l_warptile = { 256, 128, 256, 64, 1 };
  2272. m_warptile = { 256, 128, 128, 64, 0 };
  2273. s_warptile = { 128, 64, 64, 64, 0 };
  2274. l_wg_denoms = {128, 256, 1 };
  2275. m_wg_denoms = {128, 128, 1 };
  2276. s_wg_denoms = { 64, 64, 1 };
  2277. // spec constants and tile sizes for quant matmul (non-Qi_K)
  2278. l_warptile_mmq = { 256, 128, 256, 64, 1 };
  2279. m_warptile_mmq = { 256, 128, 128, 64, 1 };
  2280. s_warptile_mmq = { 256, 32, 64, 128, 0 };
  2281. l_mmq_wg_denoms = { 128, 256, 1 };
  2282. m_mmq_wg_denoms = { 128, 128, 1 };
  2283. s_mmq_wg_denoms = { 32, 64, 1 };
  2284. // spec constants and tile sizes for quant matmul (Qi_K)
  2285. l_warptile_mmq_k = { 256, 128, 256, 64, 1 };
  2286. m_warptile_mmq_k = { 256, 128, 128, 64, 1 };
  2287. s_warptile_mmq_k = { 256, 32, 64, 128, 0 };
  2288. l_mmq_wg_denoms_k = { 128, 256, 1 };
  2289. m_mmq_wg_denoms_k = { 128, 128, 1 };
  2290. s_mmq_wg_denoms_k = { 32, 64, 1 };
  2291. // spec constants and tile sizes for quant matmul_id
  2292. l_warptile_mmqid = { 256, 128, 128, 16, 1, device->subgroup_size };
  2293. m_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2294. s_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2295. l_mmqid_wg_denoms = { 128, 128, 1 };
  2296. m_mmqid_wg_denoms = { 128, 64, 1 };
  2297. s_mmqid_wg_denoms = { 128, 64, 1 };
  2298. l_align = 128;
  2299. m_align = 64;
  2300. s_align = 32;
  2301. } else {
  2302. // Matrix cores require different warp group sizes
  2303. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  2304. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  2305. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  2306. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  2307. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  2308. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  2309. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  2310. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  2311. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  2312. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2313. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2314. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2315. l_warptile_mmq = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2316. m_warptile_mmq = { 128, 64, 64, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2317. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2318. // Integer MMQ has a smaller shared memory profile, but heavier register use
  2319. l_warptile_mmq_int = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2320. m_warptile_mmq_int = { 128, 64, 64, 32, subgroup_size_8, 32, 2, 2, 2, 1, subgroup_size_8 };
  2321. s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, subgroup_size_8 };
  2322. // K-quants use even more registers, mitigate by setting WMITER to 1
  2323. l_warptile_mmq_int_k = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 1, 4, 4, 1, subgroup_size_8 };
  2324. m_warptile_mmq_int_k = { 128, 64, 64, 32, subgroup_size_8, 32, 1, 2, 2, 1, subgroup_size_8 };
  2325. s_warptile_mmq_int_k = { subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, subgroup_size_8 };
  2326. 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 };
  2327. 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 };
  2328. 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 };
  2329. 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 };
  2330. 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 };
  2331. 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 };
  2332. l_warptile_mmqid_int = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, 4, 4, 1, mul_mat_subgroup_size_8 };
  2333. m_warptile_mmqid_int = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, 2, 2, 1, mul_mat_subgroup_size_8 };
  2334. s_warptile_mmqid_int = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, mul_mat_subgroup_size_8 };
  2335. 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 };
  2336. m_warptile_mmqid_int_k = { 128, 64, 64, 32, mul_mat_subgroup_size_16, 32, 1, 2, 2, 1, mul_mat_subgroup_size_16 };
  2337. s_warptile_mmqid_int_k = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, mul_mat_subgroup_size_16 };
  2338. // chip specific tuning
  2339. if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) {
  2340. m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2341. m_warptile_mmqid = m_warptile_mmqid_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2342. }
  2343. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  2344. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  2345. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  2346. l_align = 128;
  2347. m_align = 64;
  2348. s_align = 32;
  2349. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  2350. ggml_type t = (ggml_type)i;
  2351. // Disable medium and large matrix multiplication if not enough shared memory is available
  2352. // Check mmq warptiles as the largest configuration
  2353. // Throw an error if not enough for any matrix multiplication is available
  2354. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) {
  2355. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  2356. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  2357. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) {
  2358. device->mul_mat_m[i] = false;
  2359. device->mul_mat_l[i] = false;
  2360. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) {
  2361. device->mul_mat_l[i] = false;
  2362. }
  2363. // Disable mul_mat_id if not enough shared memory is available
  2364. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmqid, true, t)) {
  2365. device->mul_mat_id_s[i] = false;
  2366. device->mul_mat_id_m[i] = false;
  2367. device->mul_mat_id_l[i] = false;
  2368. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmqid, true, t)) {
  2369. device->mul_mat_id_m[i] = false;
  2370. device->mul_mat_id_l[i] = false;
  2371. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmqid, true, t)) {
  2372. device->mul_mat_id_l[i] = false;
  2373. }
  2374. }
  2375. }
  2376. if (!device->pipeline_matmul_f32) {
  2377. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2378. }
  2379. if (!device->pipeline_matmul_f32_f16) {
  2380. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  2381. }
  2382. if (!device->pipeline_matmul_id_f32) {
  2383. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2384. }
  2385. if (!device->pipeline_matmul_bf16) {
  2386. device->pipeline_matmul_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2387. }
  2388. if (!device->pipeline_matmul_id_bf16) {
  2389. device->pipeline_matmul_id_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2390. }
  2391. std::vector<std::future<void>> compiles;
  2392. 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,
  2393. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2394. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2395. if (!require_full_subgroups && required_subgroup_size == 0) {
  2396. required_subgroup_size = get_subgroup_size(name, device->architecture);
  2397. }
  2398. if (!pipeline) {
  2399. pipeline = std::make_shared<vk_pipeline_struct>();
  2400. }
  2401. if (!pipeline->initialized) {
  2402. pipeline->name = name;
  2403. pipeline->parameter_count = parameter_count;
  2404. pipeline->push_constant_size = push_constant_size;
  2405. pipeline->wg_denoms = wg_denoms;
  2406. pipeline->align = align;
  2407. pipeline->initialized = true;
  2408. }
  2409. if (!pipeline->needed || pipeline->compiled) {
  2410. return;
  2411. }
  2412. // TODO: We're no longer benefitting from the async compiles (shaders are
  2413. // compiled individually, as needed) and this complexity can be removed.
  2414. {
  2415. // wait until fewer than N compiles are in progress
  2416. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  2417. std::unique_lock<std::mutex> guard(compile_count_mutex);
  2418. while (compile_count >= N) {
  2419. compile_count_cond.wait(guard);
  2420. }
  2421. compile_count++;
  2422. }
  2423. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  2424. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  2425. };
  2426. 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,
  2427. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2428. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2429. return ggml_vk_create_pipeline(device, pipeline, name.c_str(), spv_size, spv_data, entrypoint,
  2430. parameter_count, push_constant_size, wg_denoms, specialization_constants,
  2431. align, disable_robustness, require_full_subgroups, required_subgroup_size);
  2432. };
  2433. 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> {
  2434. return {fa_rows_cols(path, hsk, hsv, clamp, type, small_rows)[0], 1, 1};
  2435. };
  2436. 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> {
  2437. // For large number of rows, 128 invocations seems to work best.
  2438. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  2439. // can't use 256 for D==80.
  2440. // For scalar, use 128 (arbitrary)
  2441. // The same D_split value is used for both HSK and HSV, so just base it on the union of the LSBs.
  2442. const uint32_t D = (hsk|hsv);
  2443. uint32_t wg_size = (path == FA_SCALAR || path == FA_COOPMAT1)
  2444. ? scalar_flash_attention_workgroup_size
  2445. : ((small_rows && (D % 32) == 0) ? 256 : 128);
  2446. auto rows_cols = fa_rows_cols(path, hsk, hsv, clamp, type, small_rows);
  2447. // D_split can't be larger than a subgroup because we use subgroupShuffle to reduce it.
  2448. // D_split can't be larger than the LSB of D divided by 4 due to vectorization in the shader.
  2449. const uint32_t D_lsb = D ^ (D & (D-1));
  2450. uint32_t D_split = std::min(std::min(device->subgroup_size, 8u), D_lsb / 4);
  2451. return {wg_size, rows_cols[0], rows_cols[1], hsk, hsv, clamp, D_split};
  2452. };
  2453. #define CREATE_FA(TYPE, NAMELC, FAPATH, SUFFIX) \
  2454. for (auto &fa : device->pipeline_flash_attn_f32_f16[TYPE]) { \
  2455. uint32_t HSK = fa.first.HSK; \
  2456. uint32_t HSV = fa.first.HSV; \
  2457. bool small_rows = fa.first.small_rows; \
  2458. FaCodePath path = fa.first.path; \
  2459. bool aligned = fa.first.aligned; \
  2460. bool f32acc = fa.first.f32acc; \
  2461. if (path == FAPATH) { \
  2462. if (aligned) { \
  2463. if (f32acc) { \
  2464. 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)); \
  2465. } else { \
  2466. 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)); \
  2467. } \
  2468. } else { \
  2469. if (f32acc) { \
  2470. 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)); \
  2471. } else { \
  2472. 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)); \
  2473. } \
  2474. } \
  2475. } \
  2476. }
  2477. CREATE_FA(GGML_TYPE_F32, f32, FA_SCALAR, )
  2478. CREATE_FA(GGML_TYPE_F16, f16, FA_SCALAR, )
  2479. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_SCALAR, )
  2480. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_SCALAR, )
  2481. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2482. if (device->coopmat1_fa_support) {
  2483. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT1, _cm1)
  2484. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT1, _cm1)
  2485. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT1, _cm1)
  2486. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT1, _cm1)
  2487. }
  2488. #endif
  2489. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2490. if (device->coopmat2) {
  2491. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT2, _cm2)
  2492. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT2, _cm2)
  2493. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT2, _cm2)
  2494. CREATE_FA(GGML_TYPE_Q4_1, q4_1, FA_COOPMAT2, _cm2)
  2495. CREATE_FA(GGML_TYPE_Q5_0, q5_0, FA_COOPMAT2, _cm2)
  2496. CREATE_FA(GGML_TYPE_Q5_1, q5_1, FA_COOPMAT2, _cm2)
  2497. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT2, _cm2)
  2498. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl, FA_COOPMAT2, _cm2)
  2499. }
  2500. #endif
  2501. #undef CREATE_FA
  2502. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2503. if (device->coopmat2) {
  2504. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2505. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2506. 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); \
  2507. 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); \
  2508. 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); \
  2509. 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); \
  2510. 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); \
  2511. 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); \
  2512. // Create 2 variants, {f16,f32} accumulator
  2513. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2514. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2515. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2516. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2517. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2518. if (device->coopmat_bf16_support) {
  2519. CREATE_MM(pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2520. }
  2521. #endif
  2522. 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)
  2523. 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)
  2524. 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)
  2525. 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)
  2526. 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)
  2527. 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)
  2528. 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)
  2529. 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)
  2530. 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)
  2531. 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)
  2532. 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)
  2533. 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)
  2534. 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)
  2535. 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)
  2536. 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)
  2537. 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)
  2538. 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)
  2539. 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)
  2540. 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)
  2541. 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)
  2542. GGML_ASSERT(device->subgroup_ballot);
  2543. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2544. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2545. if (device->coopmat_bf16_support) {
  2546. CREATE_MM(pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2547. }
  2548. #endif
  2549. 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)
  2550. 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)
  2551. 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)
  2552. 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)
  2553. 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)
  2554. 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)
  2555. 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)
  2556. 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)
  2557. 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)
  2558. 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)
  2559. 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)
  2560. 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)
  2561. 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)
  2562. 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)
  2563. 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)
  2564. 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)
  2565. 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)
  2566. 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)
  2567. 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)
  2568. 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)
  2569. #undef CREATE_MM
  2570. #undef CREATE_MM2
  2571. } else
  2572. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2573. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2574. if (device->coopmat_support) {
  2575. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2576. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2577. if (device->mul_mat ## ID ## _l[TYPE]) \
  2578. 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); \
  2579. if (device->mul_mat ## ID ## _m[TYPE]) \
  2580. 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); \
  2581. if (device->mul_mat ## ID ## _s[TYPE]) \
  2582. 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); \
  2583. if (device->mul_mat ## ID ## _l[TYPE]) \
  2584. 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); \
  2585. if (device->mul_mat ## ID ## _m[TYPE]) \
  2586. 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); \
  2587. if (device->mul_mat ## ID ## _s[TYPE]) \
  2588. 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); \
  2589. // Create 2 variants, {f16,f32} accumulator
  2590. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2591. if (device->coopmat_acc_f16_support) { \
  2592. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2593. } \
  2594. if (device->coopmat_acc_f32_support) { \
  2595. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2596. } \
  2597. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2598. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2599. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2600. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2601. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2602. if (device->coopmat_bf16_support) {
  2603. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, )
  2604. }
  2605. #endif
  2606. if (device->coopmat_acc_f16_support) {
  2607. 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, );
  2608. 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, );
  2609. 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, );
  2610. 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, );
  2611. 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, );
  2612. 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, );
  2613. 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, );
  2614. 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, );
  2615. 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, );
  2616. 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, );
  2617. 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, );
  2618. 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, );
  2619. 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, );
  2620. 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, );
  2621. 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, );
  2622. 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, );
  2623. 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, );
  2624. 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, );
  2625. 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, );
  2626. 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, );
  2627. } else {
  2628. 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, );
  2629. 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, );
  2630. 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, );
  2631. 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, );
  2632. 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, );
  2633. 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, );
  2634. 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, );
  2635. 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, );
  2636. 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, );
  2637. 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, );
  2638. 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, );
  2639. 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, );
  2640. 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, );
  2641. 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, );
  2642. 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, );
  2643. 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, );
  2644. 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, );
  2645. 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, );
  2646. 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, );
  2647. 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, );
  2648. }
  2649. GGML_ASSERT(device->subgroup_ballot);
  2650. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2651. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2652. 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);
  2653. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2654. if (device->coopmat_bf16_support) {
  2655. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2656. }
  2657. #endif
  2658. 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);
  2659. 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);
  2660. 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);
  2661. 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);
  2662. 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);
  2663. 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);
  2664. 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);
  2665. 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);
  2666. 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);
  2667. 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);
  2668. 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);
  2669. 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);
  2670. 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);
  2671. 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);
  2672. 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);
  2673. 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);
  2674. 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);
  2675. 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);
  2676. 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);
  2677. 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);
  2678. #undef CREATE_MM2
  2679. #undef CREATE_MM
  2680. } else
  2681. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2682. if (device->fp16) {
  2683. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2684. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2685. if (device->mul_mat ## ID ## _l[TYPE]) \
  2686. 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); \
  2687. if (device->mul_mat ## ID ## _m[TYPE]) \
  2688. 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); \
  2689. if (device->mul_mat ## ID ## _s[TYPE]) \
  2690. 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); \
  2691. if (device->mul_mat ## ID ## _l[TYPE]) \
  2692. 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); \
  2693. if (device->mul_mat ## ID ## _m[TYPE]) \
  2694. 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); \
  2695. if (device->mul_mat ## ID ## _s[TYPE]) \
  2696. 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); \
  2697. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2698. if (device->mul_mat ## ID ## _l[TYPE]) { \
  2699. 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); \
  2700. } \
  2701. if (device->mul_mat ## ID ## _m[TYPE]) { \
  2702. 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); \
  2703. } \
  2704. if (device->mul_mat ## ID ## _s[TYPE]) { \
  2705. 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); \
  2706. } \
  2707. // Create 2 variants, {f16,f32} accumulator
  2708. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2709. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2710. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2711. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2712. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2713. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2714. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2715. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2716. 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);
  2717. 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);
  2718. 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);
  2719. 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);
  2720. 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);
  2721. 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);
  2722. 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);
  2723. 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);
  2724. 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);
  2725. 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);
  2726. 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);
  2727. 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);
  2728. 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);
  2729. 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);
  2730. 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);
  2731. 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);
  2732. 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);
  2733. 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);
  2734. 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);
  2735. 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);
  2736. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2737. if (device->integer_dot_product) {
  2738. 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);
  2739. 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);
  2740. 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);
  2741. 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);
  2742. 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);
  2743. 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);
  2744. 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);
  2745. 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);
  2746. 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);
  2747. 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);
  2748. 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);
  2749. }
  2750. #endif
  2751. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2752. 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);
  2753. 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);
  2754. 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);
  2755. 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);
  2756. 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);
  2757. 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);
  2758. 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);
  2759. 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);
  2760. 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);
  2761. 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);
  2762. 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);
  2763. 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);
  2764. 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);
  2765. 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);
  2766. 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);
  2767. 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);
  2768. 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);
  2769. 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);
  2770. 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);
  2771. 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);
  2772. 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);
  2773. 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);
  2774. 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);
  2775. 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);
  2776. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2777. if (device->integer_dot_product) {
  2778. 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);
  2779. 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);
  2780. 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);
  2781. 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);
  2782. 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);
  2783. 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);
  2784. 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);
  2785. 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);
  2786. 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);
  2787. 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);
  2788. 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);
  2789. }
  2790. #endif
  2791. } else {
  2792. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2793. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2794. 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);
  2795. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2796. 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);
  2797. 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);
  2798. 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);
  2799. 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);
  2800. 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);
  2801. 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);
  2802. 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);
  2803. 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);
  2804. 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);
  2805. 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);
  2806. 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);
  2807. 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);
  2808. 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);
  2809. 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);
  2810. 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);
  2811. 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);
  2812. 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);
  2813. 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);
  2814. 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);
  2815. 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);
  2816. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2817. if (device->integer_dot_product) {
  2818. 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);
  2819. 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);
  2820. 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);
  2821. 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);
  2822. 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);
  2823. 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);
  2824. 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);
  2825. 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);
  2826. 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);
  2827. 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);
  2828. 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);
  2829. }
  2830. #endif
  2831. }
  2832. #undef CREATE_MM2
  2833. #undef CREATE_MMQ
  2834. #undef CREATE_MM
  2835. } else {
  2836. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2837. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2838. if (device->mul_mat ## ID ## _l[TYPE]) \
  2839. 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); \
  2840. if (device->mul_mat ## ID ## _m[TYPE]) \
  2841. 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); \
  2842. if (device->mul_mat ## ID ## _s[TYPE]) \
  2843. 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); \
  2844. if (device->mul_mat ## ID ## _l[TYPE]) \
  2845. 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); \
  2846. if (device->mul_mat ## ID ## _m[TYPE]) \
  2847. 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); \
  2848. if (device->mul_mat ## ID ## _s[TYPE]) \
  2849. 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); \
  2850. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2851. if (device->mul_mat ## ID ## _l[TYPE]) \
  2852. 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); \
  2853. if (device->mul_mat ## ID ## _m[TYPE]) \
  2854. 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); \
  2855. if (device->mul_mat ## ID ## _s[TYPE]) \
  2856. 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); \
  2857. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2858. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2859. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2860. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2861. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2862. 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);
  2863. 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);
  2864. 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);
  2865. 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);
  2866. 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);
  2867. 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);
  2868. 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);
  2869. 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);
  2870. 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);
  2871. 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);
  2872. 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);
  2873. 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);
  2874. 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);
  2875. 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);
  2876. 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);
  2877. 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);
  2878. 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);
  2879. 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);
  2880. 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);
  2881. 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);
  2882. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2883. if (device->integer_dot_product) {
  2884. 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, );
  2885. 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, );
  2886. 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, );
  2887. 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, );
  2888. 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, );
  2889. 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, );
  2890. 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, );
  2891. 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, );
  2892. 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, );
  2893. 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, );
  2894. }
  2895. #endif
  2896. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2897. 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);
  2898. 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);
  2899. 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);
  2900. 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);
  2901. 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);
  2902. 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);
  2903. 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);
  2904. 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);
  2905. 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);
  2906. 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);
  2907. 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);
  2908. 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);
  2909. 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);
  2910. 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);
  2911. 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);
  2912. 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);
  2913. 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);
  2914. 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);
  2915. 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);
  2916. 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);
  2917. 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);
  2918. 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);
  2919. 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);
  2920. 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);
  2921. } else {
  2922. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2923. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2924. 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);
  2925. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2926. 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);
  2927. 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);
  2928. 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);
  2929. 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);
  2930. 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);
  2931. 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);
  2932. 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);
  2933. 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);
  2934. 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);
  2935. 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);
  2936. 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);
  2937. 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);
  2938. 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);
  2939. 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);
  2940. 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);
  2941. 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);
  2942. 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);
  2943. 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);
  2944. 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);
  2945. 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);
  2946. }
  2947. }
  2948. // reusing CREATE_MM from the fp32 path
  2949. if ((device->coopmat2 || device->coopmat_support)
  2950. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2951. && !device->coopmat_bf16_support
  2952. #endif
  2953. ) {
  2954. // use scalar tile sizes
  2955. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2956. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, 4, 2, 1, subgroup_size_8 };
  2957. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, 2, 2, 1, subgroup_size_8 };
  2958. l_wg_denoms = {128, 128, 1 };
  2959. m_wg_denoms = { 64, 64, 1 };
  2960. s_wg_denoms = { 32, 32, 1 };
  2961. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2962. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2963. }
  2964. #undef CREATE_MM
  2965. // mul mat vec
  2966. // the number of rows computed per shader depends on GPU model and quant
  2967. uint32_t rm_stdq = 1;
  2968. uint32_t rm_kq = 2;
  2969. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  2970. if (device->architecture == AMD_GCN) {
  2971. rm_stdq = 2;
  2972. rm_kq = 4;
  2973. }
  2974. } else if (device->vendor_id == VK_VENDOR_ID_INTEL)
  2975. rm_stdq = 2;
  2976. uint32_t rm_iq = 2 * rm_kq;
  2977. const bool use_subgroups = device->subgroup_arithmetic && device->architecture != vk_device_architecture::AMD_GCN;
  2978. // Ensure a subgroup size >= 16 is available
  2979. const bool use_subgroups16 = use_subgroups && subgroup_min_size_16;
  2980. 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;
  2981. const uint32_t subgroup_size16 = std::max(subgroup_size, 16u);
  2982. const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0;
  2983. const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0;
  2984. static constexpr uint32_t mul_mat_vec_num_bindings = 5;
  2985. static constexpr uint32_t mul_mat_vec_id_num_bindings = 6;
  2986. for (uint32_t w = 0; w < DMMV_WG_SIZE_COUNT; ++w) {
  2987. const uint32_t wg_size_subgroup = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size : (subgroup_size * 4);
  2988. const uint32_t wg_size_subgroup16 = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size16 : (subgroup_size16 * 4);
  2989. const shader_reduction_mode reduc = (use_subgroups && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  2990. (use_subgroups && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  2991. SHADER_REDUCTION_MODE_SHMEM;
  2992. const shader_reduction_mode reduc16 = (use_subgroups16 && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  2993. (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  2994. SHADER_REDUCTION_MODE_SHMEM;
  2995. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  2996. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f32_f32", arr_dmmv_f32_f32_f32_len[reduc], arr_dmmv_f32_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2997. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f32_f32", arr_dmmv_f16_f32_f32_len[reduc], arr_dmmv_f16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2998. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f32_f32", arr_dmmv_bf16_f32_f32_len[reduc], arr_dmmv_bf16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2999. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f32_f32", arr_dmmv_q4_0_f32_f32_len[reduc], arr_dmmv_q4_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3000. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f32_f32", arr_dmmv_q4_1_f32_f32_len[reduc], arr_dmmv_q4_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3001. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f32_f32", arr_dmmv_q5_0_f32_f32_len[reduc], arr_dmmv_q5_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3002. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f32_f32", arr_dmmv_q5_1_f32_f32_len[reduc], arr_dmmv_q5_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3003. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f32_f32", arr_dmmv_q8_0_f32_f32_len[reduc], arr_dmmv_q8_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3004. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f32_f32", arr_dmmv_q2_k_f32_f32_len[reduc16], arr_dmmv_q2_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3005. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f32_f32", arr_dmmv_q3_k_f32_f32_len[reduc16], arr_dmmv_q3_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3006. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f32_f32", arr_dmmv_q4_k_f32_f32_len[reduc16], arr_dmmv_q4_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3007. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f32_f32", arr_dmmv_q5_k_f32_f32_len[reduc16], arr_dmmv_q5_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3008. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f32_f32", arr_dmmv_q6_k_f32_f32_len[reduc16], arr_dmmv_q6_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3009. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f32_f32", arr_dmmv_iq1_s_f32_f32_len[reduc16], arr_dmmv_iq1_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3010. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f32_f32", arr_dmmv_iq1_m_f32_f32_len[reduc16], arr_dmmv_iq1_m_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3011. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f32_f32", arr_dmmv_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_iq2_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3012. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f32_f32", arr_dmmv_iq2_xs_f32_f32_len[reduc16], arr_dmmv_iq2_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3013. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f32_f32", arr_dmmv_iq2_s_f32_f32_len[reduc16], arr_dmmv_iq2_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3014. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f32_f32", arr_dmmv_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_iq3_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3015. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f32_f32", arr_dmmv_iq3_s_f32_f32_len[reduc16], arr_dmmv_iq3_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3016. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f32_f32", arr_dmmv_iq4_xs_f32_f32_len[reduc16], arr_dmmv_iq4_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3017. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f32_f32", arr_dmmv_iq4_nl_f32_f32_len[reduc16], arr_dmmv_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3018. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f32_f32", arr_dmmv_mxfp4_f32_f32_len[reduc16], arr_dmmv_mxfp4_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3019. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f16_f32", arr_dmmv_f32_f16_f32_len[reduc], arr_dmmv_f32_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3020. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f16_f32", arr_dmmv_f16_f16_f32_len[reduc], arr_dmmv_f16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3021. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f16_f32", arr_dmmv_bf16_f16_f32_len[reduc], arr_dmmv_bf16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3022. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f16_f32", arr_dmmv_q4_0_f16_f32_len[reduc], arr_dmmv_q4_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3023. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f16_f32", arr_dmmv_q4_1_f16_f32_len[reduc], arr_dmmv_q4_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3024. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f16_f32", arr_dmmv_q5_0_f16_f32_len[reduc], arr_dmmv_q5_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3025. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f16_f32", arr_dmmv_q5_1_f16_f32_len[reduc], arr_dmmv_q5_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3026. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f16_f32", arr_dmmv_q8_0_f16_f32_len[reduc], arr_dmmv_q8_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3027. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f16_f32", arr_dmmv_q2_k_f16_f32_len[reduc16], arr_dmmv_q2_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3028. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f16_f32", arr_dmmv_q3_k_f16_f32_len[reduc16], arr_dmmv_q3_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3029. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f16_f32", arr_dmmv_q4_k_f16_f32_len[reduc16], arr_dmmv_q4_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3030. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f16_f32", arr_dmmv_q5_k_f16_f32_len[reduc16], arr_dmmv_q5_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3031. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f16_f32", arr_dmmv_q6_k_f16_f32_len[reduc16], arr_dmmv_q6_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3032. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f16_f32", arr_dmmv_iq1_s_f16_f32_len[reduc16], arr_dmmv_iq1_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3033. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f16_f32", arr_dmmv_iq1_m_f16_f32_len[reduc16], arr_dmmv_iq1_m_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3034. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f16_f32", arr_dmmv_iq2_xxs_f16_f32_len[reduc16], arr_dmmv_iq2_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3035. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f16_f32", arr_dmmv_iq2_xs_f16_f32_len[reduc16], arr_dmmv_iq2_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3036. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f16_f32", arr_dmmv_iq2_s_f16_f32_len[reduc16], arr_dmmv_iq2_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3037. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f16_f32", arr_dmmv_iq3_xxs_f16_f32_len[reduc16], arr_dmmv_iq3_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3038. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f16_f32", arr_dmmv_iq3_s_f16_f32_len[reduc16], arr_dmmv_iq3_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3039. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f16_f32", arr_dmmv_iq4_xs_f16_f32_len[reduc16], arr_dmmv_iq4_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3040. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f16_f32", arr_dmmv_iq4_nl_f16_f32_len[reduc16], arr_dmmv_iq4_nl_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3041. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f16_f32", arr_dmmv_mxfp4_f16_f32_len[reduc16], arr_dmmv_mxfp4_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3042. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3043. if (device->integer_dot_product) {
  3044. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  3045. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  3046. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_q8_1_f32", arr_dmmv_q4_0_q8_1_f32_len[reduc], arr_dmmv_q4_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3047. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_q8_1_f32", arr_dmmv_q4_1_q8_1_f32_len[reduc], arr_dmmv_q4_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3048. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_q8_1_f32", arr_dmmv_q5_0_q8_1_f32_len[reduc], arr_dmmv_q5_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3049. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_q8_1_f32", arr_dmmv_q5_1_q8_1_f32_len[reduc], arr_dmmv_q5_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3050. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_q8_1_f32", arr_dmmv_q8_0_q8_1_f32_len[reduc], arr_dmmv_q8_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3051. }
  3052. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  3053. }
  3054. }
  3055. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  3056. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  3057. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  3058. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  3059. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  3060. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  3061. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  3062. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq, 1, 1}, {device->subgroup_size, 1*rm_stdq}, 1, true);
  3063. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  3064. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  3065. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  3066. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  3067. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  3068. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3069. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3070. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3071. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3072. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3073. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3074. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3075. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3076. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3077. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3078. // dequant shaders
  3079. 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);
  3080. 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);
  3081. 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);
  3082. 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);
  3083. 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);
  3084. 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);
  3085. 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);
  3086. 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);
  3087. 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);
  3088. 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);
  3089. 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);
  3090. 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);
  3091. 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);
  3092. 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);
  3093. 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);
  3094. 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);
  3095. 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);
  3096. 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);
  3097. 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);
  3098. 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);
  3099. 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);
  3100. // get_rows
  3101. 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);
  3102. 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);
  3103. 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);
  3104. 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);
  3105. 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);
  3106. 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);
  3107. 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);
  3108. 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);
  3109. 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);
  3110. 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);
  3111. 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);
  3112. 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);
  3113. 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);
  3114. 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);
  3115. 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);
  3116. 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);
  3117. 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);
  3118. 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);
  3119. 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);
  3120. 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);
  3121. 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);
  3122. 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);
  3123. 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);
  3124. 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);
  3125. 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);
  3126. 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);
  3127. 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);
  3128. 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);
  3129. 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);
  3130. 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);
  3131. 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);
  3132. 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);
  3133. 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);
  3134. 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);
  3135. 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);
  3136. 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);
  3137. 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);
  3138. 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);
  3139. 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);
  3140. 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);
  3141. 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);
  3142. 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);
  3143. 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);
  3144. 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);
  3145. 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);
  3146. 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);
  3147. 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);
  3148. 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);
  3149. if (device->subgroup_clustered && device->subgroup_require_full_support) {
  3150. 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);
  3151. } else {
  3152. 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);
  3153. }
  3154. for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) {
  3155. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3156. ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_subgroup_add_len, mul_mat_vec_p021_f16_f32_subgroup_add_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_p021_push_constants), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true, true);
  3157. } else {
  3158. ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_len, mul_mat_vec_p021_f16_f32_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_p021_push_constants), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true);
  3159. }
  3160. }
  3161. ggml_vk_create_pipeline(device, device->pipeline_mul_mat_vec_nc_f16_f32, "mul_mat_vec_nc_f16_f32", mul_mat_vec_nc_f16_f32_len, mul_mat_vec_nc_f16_f32_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_nc_push_constants), {1, 1, 1}, {}, 1);
  3162. 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);
  3163. 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);
  3164. 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);
  3165. 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);
  3166. 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);
  3167. 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);
  3168. if (device->float_controls_rte_fp16 &&
  3169. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= device->properties.limits.maxPushConstantsSize) {
  3170. 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);
  3171. 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);
  3172. }
  3173. 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);
  3174. 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);
  3175. 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);
  3176. 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);
  3177. 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);
  3178. 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);
  3179. 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);
  3180. 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);
  3181. 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);
  3182. 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);
  3183. 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);
  3184. 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);
  3185. 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);
  3186. 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);
  3187. 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);
  3188. 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);
  3189. if (device->float_controls_rte_fp16) {
  3190. 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);
  3191. 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);
  3192. 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);
  3193. 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);
  3194. 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);
  3195. 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);
  3196. } else {
  3197. 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);
  3198. 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);
  3199. 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);
  3200. 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);
  3201. 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);
  3202. 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);
  3203. }
  3204. #define SET_ROWS(itype, rte) \
  3205. 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); \
  3206. 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); \
  3207. 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); \
  3208. 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); \
  3209. 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); \
  3210. 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); \
  3211. 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); \
  3212. 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); \
  3213. 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);
  3214. if (device->float_controls_rte_fp16) {
  3215. SET_ROWS(_i32, _rte)
  3216. SET_ROWS(_i64, _rte)
  3217. } else {
  3218. SET_ROWS(_i32, )
  3219. SET_ROWS(_i64, )
  3220. }
  3221. #undef SET_ROWS
  3222. 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);
  3223. 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);
  3224. 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);
  3225. 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);
  3226. 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);
  3227. 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);
  3228. auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) {
  3229. std::string s;
  3230. s += std::string(src0_f16 ? "_f16" : "_f32");
  3231. s += std::string(src1_f16 ? "_f16" : "_f32");
  3232. s += std::string(dst_f16 ? "_f16" : "_f32");
  3233. return s;
  3234. };
  3235. bool rte = device->float_controls_rte_fp16;
  3236. #define CREATE_BINARY(name, namemod, spec, bindings) \
  3237. for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \
  3238. ggml_vk_create_pipeline2(device, device->pipeline_ ## name ## namemod[s0][s1][d], \
  3239. #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d][rte], name ## _data[s0][s1][d][rte], \
  3240. "main", (bindings), sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1);
  3241. CREATE_BINARY(add, , {0}, 4)
  3242. CREATE_BINARY(add, _norepeat, {1}, 4)
  3243. CREATE_BINARY(sub, , {0}, 3)
  3244. CREATE_BINARY(sub, _norepeat, {1}, 3)
  3245. CREATE_BINARY(mul, , {0}, 3)
  3246. CREATE_BINARY(mul, _norepeat, {1}, 3)
  3247. CREATE_BINARY(div, , {0}, 3)
  3248. CREATE_BINARY(div, _norepeat, {1}, 3)
  3249. CREATE_BINARY(add_rms, , {0}, 4)
  3250. CREATE_BINARY(add_rms, _norepeat, {1}, 4)
  3251. #undef CREATE_BINARY
  3252. if (device->multi_add) {
  3253. for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) {
  3254. 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);
  3255. 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);
  3256. }
  3257. }
  3258. 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);
  3259. 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);
  3260. 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);
  3261. 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);
  3262. 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);
  3263. 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);
  3264. 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);
  3265. ggml_vk_create_pipeline(device, device->pipeline_upscale_bicubic_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BICUBIC}, 1);
  3266. 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);
  3267. 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);
  3268. 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);
  3269. 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);
  3270. 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);
  3271. if (device->float_controls_rte_fp16) {
  3272. ggml_vk_create_pipeline(device, device->pipeline_log[0], "log_f32_rte", log_f32_rte_len, log_f32_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3273. ggml_vk_create_pipeline(device, device->pipeline_log[1], "log_f16_rte", log_f16_rte_len, log_f16_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3274. } else {
  3275. ggml_vk_create_pipeline(device, device->pipeline_log[0], "log_f32", log_f32_len, log_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3276. ggml_vk_create_pipeline(device, device->pipeline_log[1], "log_f16", log_f16_len, log_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3277. }
  3278. 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);
  3279. 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);
  3280. 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);
  3281. 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);
  3282. 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);
  3283. #define CREATE_UNARY(name) \
  3284. 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); \
  3285. 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);
  3286. CREATE_UNARY(gelu)
  3287. CREATE_UNARY(gelu_erf)
  3288. CREATE_UNARY(gelu_quick)
  3289. CREATE_UNARY(silu)
  3290. CREATE_UNARY(relu)
  3291. CREATE_UNARY(neg)
  3292. CREATE_UNARY(tanh)
  3293. CREATE_UNARY(sigmoid)
  3294. CREATE_UNARY(hardsigmoid)
  3295. CREATE_UNARY(hardswish)
  3296. CREATE_UNARY(abs)
  3297. #undef CREATE_UNARY
  3298. #define CREATE_UNARY_RTE(name) \
  3299. if (device->float_controls_rte_fp16) { \
  3300. 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); \
  3301. 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); \
  3302. } else { \
  3303. 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); \
  3304. 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); \
  3305. }
  3306. CREATE_UNARY_RTE(exp)
  3307. #undef CREATE_UNARY_RTE
  3308. #define CREATE_GLU(name) \
  3309. if (device->float_controls_rte_fp16) { \
  3310. 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); \
  3311. 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); \
  3312. } else { \
  3313. 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); \
  3314. 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); \
  3315. }
  3316. CREATE_GLU(geglu)
  3317. CREATE_GLU(reglu)
  3318. CREATE_GLU(swiglu)
  3319. CREATE_GLU(swiglu_oai)
  3320. CREATE_GLU(geglu_erf)
  3321. CREATE_GLU(geglu_quick)
  3322. #undef CREATE_GLU
  3323. 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);
  3324. 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);
  3325. 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);
  3326. 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);
  3327. 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);
  3328. 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);
  3329. 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);
  3330. 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);
  3331. 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);
  3332. 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);
  3333. 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);
  3334. 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);
  3335. if (device->float_controls_rte_fp16) {
  3336. 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);
  3337. 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);
  3338. 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);
  3339. 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);
  3340. 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);
  3341. 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);
  3342. } else {
  3343. 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);
  3344. 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);
  3345. 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);
  3346. 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);
  3347. 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);
  3348. 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);
  3349. }
  3350. for (uint32_t i = 0; i < num_argsort_pipelines; ++i) {
  3351. 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);
  3352. }
  3353. 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);
  3354. 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);
  3355. 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);
  3356. #define IM2COL(bda) \
  3357. 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); \
  3358. 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); \
  3359. if (device->float_controls_rte_fp16) { \
  3360. 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); \
  3361. 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); \
  3362. } else { \
  3363. 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); \
  3364. 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); \
  3365. }
  3366. if (device->shader_int64 && device->buffer_device_address) {
  3367. IM2COL(_bda)
  3368. } else {
  3369. IM2COL()
  3370. }
  3371. 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);
  3372. 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);
  3373. 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);
  3374. 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);
  3375. 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);
  3376. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3377. 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);
  3378. 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);
  3379. } else {
  3380. 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);
  3381. 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);
  3382. }
  3383. 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);
  3384. 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);
  3385. 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);
  3386. // conv2d, conv_transpose_2d
  3387. for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) {
  3388. uint32_t conv2d_WG_SIZE = 256;
  3389. uint32_t conv2d_BS_K = 128;
  3390. uint32_t conv2d_BS_CRS = 16;
  3391. uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices.
  3392. uint32_t conv2d_BS_NPQ = 128;
  3393. uint32_t conv2d_TS_K = 8;
  3394. uint32_t conv2d_SHMEM_PAD = 4;
  3395. bool conv2d_UNROLL = true;
  3396. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3397. if (device->coopmat2) {
  3398. conv2d_SHMEM_PAD = 8; // 8 float16_t
  3399. }
  3400. #endif
  3401. if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3402. conv2d_SHMEM_PAD = 0;
  3403. conv2d_UNROLL = false;
  3404. } else if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3405. conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4;
  3406. }
  3407. switch (s) {
  3408. default:
  3409. case CONV_SHAPE_128x128:
  3410. conv2d_BS_K = conv_shapes_wg_denoms[CONV_SHAPE_128x128][0];
  3411. conv2d_BS_NPQ = conv_shapes_wg_denoms[CONV_SHAPE_128x128][1];
  3412. conv2d_BS_CRS = 16;
  3413. if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != vk_device_architecture::AMD_GCN) {
  3414. conv2d_UNROLL = false;
  3415. }
  3416. break;
  3417. case CONV_SHAPE_64x32:
  3418. conv2d_BS_K = conv_shapes_wg_denoms[CONV_SHAPE_64x32][0];
  3419. conv2d_BS_NPQ = conv_shapes_wg_denoms[CONV_SHAPE_64x32][1];
  3420. conv2d_BS_CRS = 32;
  3421. conv2d_TS_K = 4;
  3422. break;
  3423. case CONV_SHAPE_32x256:
  3424. conv2d_BS_K = conv_shapes_wg_denoms[CONV_SHAPE_32x256][0];
  3425. conv2d_BS_NPQ = conv_shapes_wg_denoms[CONV_SHAPE_32x256][1];
  3426. conv2d_BS_CRS = 16;
  3427. break;
  3428. }
  3429. // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math.
  3430. bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA ||
  3431. device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  3432. bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD ||
  3433. device->architecture == vk_device_architecture::AMD_GCN;
  3434. if (device->subgroup_shuffle &&
  3435. device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316.
  3436. allow_collectives_nv &&
  3437. allow_collectives_amd) {
  3438. use_collectives = 1;
  3439. conv2d_BS_CRS = std::min(
  3440. device->subgroup_size,
  3441. conv2d_BS_CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used.
  3442. }
  3443. uint32_t conv2d_shmem_req =
  3444. (conv2d_BS_K * (conv2d_BS_CRS + conv2d_SHMEM_PAD) + conv2d_BS_CRS * (conv2d_BS_NPQ + conv2d_SHMEM_PAD)) * sizeof(float);
  3445. if (device->properties.limits.maxComputeSharedMemorySize < conv2d_shmem_req) {
  3446. conv2d_BS_CRS = 8;
  3447. if (use_collectives) {
  3448. conv2d_BS_CRS = std::min(device->subgroup_size, conv2d_BS_CRS);
  3449. }
  3450. }
  3451. std::array<uint32_t, 3> wg_denoms = { conv2d_BS_K, conv2d_BS_NPQ, 1 };
  3452. 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 };
  3453. #define CREATE_CONV(name, type_suffix, spv_suffix) \
  3454. for (auto &c : device->pipeline_##name##type_suffix[s]) { \
  3455. const vk_conv2d_pipeline_state &state = c.first; \
  3456. std::vector<uint32_t> spec_constants_cpy = spec_constants; \
  3457. spec_constants_cpy.push_back(state.s0); \
  3458. spec_constants_cpy.push_back(state.s1); \
  3459. spec_constants_cpy.push_back(state.p0); \
  3460. spec_constants_cpy.push_back(state.p1); \
  3461. spec_constants_cpy.push_back(state.d0); \
  3462. spec_constants_cpy.push_back(state.d1); \
  3463. spec_constants_cpy.push_back(state.KW); \
  3464. spec_constants_cpy.push_back(state.KH); \
  3465. ggml_vk_create_pipeline( \
  3466. device, c.second, #name #type_suffix, \
  3467. name##type_suffix##spv_suffix##_len, name##type_suffix##spv_suffix##_data, "main", 3, \
  3468. sizeof(vk_op_##name##_push_constants), wg_denoms, spec_constants_cpy, 1, true, use_collectives); \
  3469. }
  3470. #define CREATE_CONVS(spv_suffix) \
  3471. CREATE_CONV(conv2d, _f32, spv_suffix) \
  3472. CREATE_CONV(conv2d, _f16_f32, spv_suffix) \
  3473. if (device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_conv_transpose_2d_push_constants)) { \
  3474. CREATE_CONV(conv_transpose_2d, _f32, spv_suffix) \
  3475. CREATE_CONV(conv_transpose_2d, _f16_f32, spv_suffix) \
  3476. }
  3477. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3478. if (device->coopmat2) {
  3479. CREATE_CONVS(_cm2)
  3480. } else
  3481. #endif
  3482. if (conv2d_UNROLL) {
  3483. CREATE_CONVS(_unroll)
  3484. } else {
  3485. CREATE_CONVS( )
  3486. }
  3487. #undef CREATE_CONV
  3488. #undef CREATE_CONVS
  3489. }
  3490. 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);
  3491. 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);
  3492. 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);
  3493. 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);
  3494. for (uint32_t i = 0; i < num_topk_moe_pipelines; ++i) {
  3495. 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);
  3496. 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);
  3497. 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);
  3498. }
  3499. for (auto &c : compiles) {
  3500. c.wait();
  3501. }
  3502. }
  3503. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch);
  3504. static vk_device ggml_vk_get_device(size_t idx) {
  3505. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  3506. if (vk_instance.devices[idx] == nullptr) {
  3507. VK_LOG_DEBUG("Initializing new vk_device");
  3508. vk_device device = std::make_shared<vk_device_struct>();
  3509. vk_instance.devices[idx] = device;
  3510. #ifdef GGML_VULKAN_MEMORY_DEBUG
  3511. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  3512. #endif
  3513. if (vk_perf_logger_enabled) {
  3514. device->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  3515. }
  3516. size_t dev_num = vk_instance.device_indices[idx];
  3517. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  3518. if (dev_num >= physical_devices.size()) {
  3519. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3520. throw std::runtime_error("Device not found");
  3521. }
  3522. device->physical_device = physical_devices[dev_num];
  3523. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  3524. device->architecture = get_device_architecture(device->physical_device);
  3525. const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY");
  3526. device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr;
  3527. const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM");
  3528. device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr;
  3529. const char* GGML_VK_ALLOW_SYSMEM_FALLBACK = getenv("GGML_VK_ALLOW_SYSMEM_FALLBACK");
  3530. device->allow_sysmem_fallback = GGML_VK_ALLOW_SYSMEM_FALLBACK != nullptr;
  3531. const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE");
  3532. device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr;
  3533. bool fp16_storage = false;
  3534. bool fp16_compute = false;
  3535. bool maintenance4_support = false;
  3536. bool sm_builtins = false;
  3537. bool amd_shader_core_properties2 = false;
  3538. bool pipeline_robustness = false;
  3539. bool coopmat2_support = false;
  3540. bool pipeline_executable_properties_support = false;
  3541. device->coopmat_support = false;
  3542. device->integer_dot_product = false;
  3543. bool bfloat16_support = false;
  3544. for (const auto& properties : ext_props) {
  3545. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  3546. maintenance4_support = true;
  3547. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3548. fp16_storage = true;
  3549. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3550. fp16_compute = true;
  3551. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  3552. sm_builtins = true;
  3553. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  3554. amd_shader_core_properties2 = true;
  3555. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  3556. pipeline_robustness = true;
  3557. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  3558. device->subgroup_size_control = true;
  3559. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3560. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3561. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3562. device->coopmat_support = true;
  3563. device->coopmat_m = 0;
  3564. device->coopmat_n = 0;
  3565. device->coopmat_k = 0;
  3566. #endif
  3567. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3568. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3569. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3570. coopmat2_support = true;
  3571. #endif
  3572. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3573. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3574. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3575. device->integer_dot_product = true;
  3576. #endif
  3577. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3578. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3579. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3580. bfloat16_support = true;
  3581. #endif
  3582. } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) {
  3583. pipeline_executable_properties_support = true;
  3584. }
  3585. }
  3586. vk::PhysicalDeviceProperties2 props2;
  3587. vk::PhysicalDeviceMaintenance3Properties props3;
  3588. vk::PhysicalDeviceMaintenance4Properties props4;
  3589. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3590. vk::PhysicalDeviceDriverProperties driver_props;
  3591. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  3592. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  3593. vk::PhysicalDeviceVulkan11Properties vk11_props;
  3594. vk::PhysicalDeviceVulkan12Properties vk12_props;
  3595. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  3596. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3597. props2.pNext = &props3;
  3598. props3.pNext = &subgroup_props;
  3599. subgroup_props.pNext = &driver_props;
  3600. driver_props.pNext = &vk11_props;
  3601. vk11_props.pNext = &vk12_props;
  3602. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  3603. if (maintenance4_support) {
  3604. last_struct->pNext = (VkBaseOutStructure *)&props4;
  3605. last_struct = (VkBaseOutStructure *)&props4;
  3606. }
  3607. if (sm_builtins) {
  3608. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  3609. last_struct = (VkBaseOutStructure *)&sm_props;
  3610. }
  3611. if (amd_shader_core_properties2) {
  3612. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3613. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3614. }
  3615. if (device->subgroup_size_control) {
  3616. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  3617. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  3618. }
  3619. #if defined(VK_NV_cooperative_matrix2)
  3620. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  3621. if (coopmat2_support) {
  3622. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  3623. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  3624. }
  3625. #endif
  3626. if (device->integer_dot_product) {
  3627. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3628. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3629. }
  3630. device->physical_device.getProperties2(&props2);
  3631. device->properties = props2.properties;
  3632. device->vendor_id = device->properties.vendorID;
  3633. device->driver_id = driver_props.driverID;
  3634. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  3635. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  3636. device->max_memory_allocation_size = std::stoull(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  3637. } else if (maintenance4_support) {
  3638. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  3639. } else {
  3640. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  3641. }
  3642. const char* GGML_VK_FORCE_MAX_BUFFER_SIZE = getenv("GGML_VK_FORCE_MAX_BUFFER_SIZE");
  3643. if (GGML_VK_FORCE_MAX_BUFFER_SIZE != nullptr) {
  3644. device->max_buffer_size = std::stoull(GGML_VK_FORCE_MAX_BUFFER_SIZE);
  3645. } else if (maintenance4_support) {
  3646. device->max_buffer_size = props4.maxBufferSize;
  3647. } else {
  3648. device->max_buffer_size = device->max_memory_allocation_size;
  3649. }
  3650. const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE");
  3651. if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) {
  3652. device->suballocation_block_size = std::stoull(GGML_VK_SUBALLOCATION_BLOCK_SIZE);
  3653. } else {
  3654. // Limit batching of allocations to 1GB by default to avoid fragmentation issues
  3655. device->suballocation_block_size = 1024*1024*1024;
  3656. }
  3657. device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size);
  3658. device->subgroup_size = subgroup_props.subgroupSize;
  3659. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3660. if (sm_builtins) {
  3661. device->shader_core_count = sm_props.shaderSMCount;
  3662. } else if (amd_shader_core_properties2) {
  3663. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  3664. } else {
  3665. device->shader_core_count = 0;
  3666. }
  3667. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  3668. device->subgroup_arithmetic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3669. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic);
  3670. #ifdef __APPLE__
  3671. // Workaround for subgroup arithmetic failing on MoltenVK with AMD GPUs (issue 15846)
  3672. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3673. device->subgroup_arithmetic = false;
  3674. }
  3675. #endif
  3676. device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3677. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle);
  3678. device->subgroup_clustered = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3679. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eClustered);
  3680. device->subgroup_ballot = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3681. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBallot);
  3682. device->subgroup_vote = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3683. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eVote);
  3684. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  3685. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  3686. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) {
  3687. device->coopmat_support = false;
  3688. }
  3689. device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated;
  3690. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  3691. // Try to find a non-graphics compute queue and transfer-focused queues
  3692. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  3693. 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);
  3694. const float priorities[] = { 1.0f, 1.0f };
  3695. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  3696. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  3697. if (compute_queue_family_index != transfer_queue_family_index) {
  3698. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3699. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  3700. } else if(!device->single_queue) {
  3701. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  3702. } else {
  3703. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3704. }
  3705. vk::DeviceCreateInfo device_create_info;
  3706. std::vector<const char *> device_extensions;
  3707. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  3708. VkPhysicalDeviceFeatures2 device_features2;
  3709. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  3710. device_features2.pNext = nullptr;
  3711. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  3712. VkPhysicalDeviceVulkan11Features vk11_features;
  3713. vk11_features.pNext = nullptr;
  3714. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  3715. device_features2.pNext = &vk11_features;
  3716. VkPhysicalDeviceVulkan12Features vk12_features;
  3717. vk12_features.pNext = nullptr;
  3718. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  3719. vk11_features.pNext = &vk12_features;
  3720. last_struct = (VkBaseOutStructure *)&vk12_features;
  3721. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  3722. pl_robustness_features.pNext = nullptr;
  3723. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  3724. pl_robustness_features.pipelineRobustness = VK_FALSE;
  3725. if (pipeline_robustness) {
  3726. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  3727. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  3728. device_extensions.push_back("VK_EXT_pipeline_robustness");
  3729. }
  3730. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  3731. subgroup_size_control_features.pNext = nullptr;
  3732. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  3733. subgroup_size_control_features.computeFullSubgroups = false;
  3734. subgroup_size_control_features.subgroupSizeControl = false;
  3735. if (device->subgroup_size_control) {
  3736. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  3737. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  3738. }
  3739. #if defined(VK_KHR_cooperative_matrix)
  3740. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  3741. coopmat_features.pNext = nullptr;
  3742. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  3743. coopmat_features.cooperativeMatrix = VK_FALSE;
  3744. if (device->coopmat_support) {
  3745. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  3746. last_struct = (VkBaseOutStructure *)&coopmat_features;
  3747. }
  3748. #endif
  3749. #if defined(VK_NV_cooperative_matrix2)
  3750. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  3751. coopmat2_features.pNext = nullptr;
  3752. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  3753. if (coopmat2_support) {
  3754. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  3755. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  3756. device_extensions.push_back("VK_NV_cooperative_matrix2");
  3757. }
  3758. #endif
  3759. #if defined(VK_KHR_shader_bfloat16)
  3760. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  3761. bfloat16_features.pNext = nullptr;
  3762. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  3763. if (bfloat16_support) {
  3764. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  3765. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  3766. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3767. }
  3768. #endif
  3769. VkPhysicalDeviceMaintenance4Features maint4_features {};
  3770. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  3771. if (maintenance4_support) {
  3772. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  3773. last_struct = (VkBaseOutStructure *)&maint4_features;
  3774. device_extensions.push_back("VK_KHR_maintenance4");
  3775. }
  3776. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  3777. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  3778. if (device->integer_dot_product) {
  3779. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3780. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3781. device_extensions.push_back("VK_KHR_shader_integer_dot_product");
  3782. }
  3783. VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pep_features {};
  3784. pep_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR;
  3785. if (pipeline_executable_properties_support) {
  3786. last_struct->pNext = (VkBaseOutStructure *)&pep_features;
  3787. last_struct = (VkBaseOutStructure *)&pep_features;
  3788. device_extensions.push_back("VK_KHR_pipeline_executable_properties");
  3789. }
  3790. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  3791. device->pipeline_executable_properties_support = pipeline_executable_properties_support;
  3792. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  3793. #if defined(VK_KHR_shader_bfloat16)
  3794. device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  3795. #else
  3796. device->bf16 = false;
  3797. #endif
  3798. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  3799. device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 &&
  3800. device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) &&
  3801. getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr;
  3802. device->shader_int64 = device_features2.features.shaderInt64;
  3803. device->buffer_device_address = vk12_features.bufferDeviceAddress;
  3804. if (device->subgroup_size_control) {
  3805. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  3806. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  3807. device_extensions.push_back("VK_EXT_subgroup_size_control");
  3808. }
  3809. device->subgroup_size_control = device->subgroup_size_control &&
  3810. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  3811. subgroup_size_control_features.subgroupSizeControl;
  3812. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  3813. #if defined(VK_KHR_cooperative_matrix)
  3814. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  3815. // coopmat1 fa shader currently assumes 32 invocations per subgroup
  3816. device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support &&
  3817. device->subgroup_size_control && device->subgroup_min_size <= 32 &&
  3818. device->subgroup_max_size >= 32;
  3819. #endif
  3820. if (coopmat2_support) {
  3821. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3822. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  3823. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  3824. coopmat2_features.cooperativeMatrixReductions &&
  3825. coopmat2_features.cooperativeMatrixConversions &&
  3826. coopmat2_features.cooperativeMatrixPerElementOperations &&
  3827. coopmat2_features.cooperativeMatrixTensorAddressing &&
  3828. coopmat2_features.cooperativeMatrixBlockLoads &&
  3829. vk12_features.bufferDeviceAddress) {
  3830. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  3831. uint32_t count = 0;
  3832. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  3833. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  3834. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  3835. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  3836. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  3837. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  3838. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  3839. flexible_dimensions.resize(count, empty_prop);
  3840. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  3841. bool found_fp16_128 = false,
  3842. found_fp16_256 = false,
  3843. found_fp32_128 = false,
  3844. found_fp32_256 = false;
  3845. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  3846. // with 32x16x16 and 256 with 32x32x16.
  3847. for (auto &prop : flexible_dimensions) {
  3848. if (prop.saturatingAccumulation == VK_FALSE &&
  3849. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  3850. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3851. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3852. if (prop.workgroupInvocations == 128 &&
  3853. prop.MGranularity <= 32 &&
  3854. prop.NGranularity <= 16 &&
  3855. prop.KGranularity <= 16) {
  3856. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3857. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3858. found_fp16_128 = true;
  3859. }
  3860. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3861. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3862. found_fp32_128 = true;
  3863. }
  3864. }
  3865. if (prop.workgroupInvocations == 256 &&
  3866. prop.MGranularity <= 32 &&
  3867. prop.NGranularity <= 32 &&
  3868. prop.KGranularity <= 16) {
  3869. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3870. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3871. found_fp16_256 = true;
  3872. }
  3873. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3874. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3875. found_fp32_256 = true;
  3876. }
  3877. }
  3878. }
  3879. }
  3880. if (found_fp16_128 && found_fp16_256 &&
  3881. found_fp32_128 && found_fp32_256 &&
  3882. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  3883. device->coopmat2 = true;
  3884. }
  3885. }
  3886. #endif
  3887. }
  3888. if (!vk11_features.storageBuffer16BitAccess) {
  3889. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  3890. throw std::runtime_error("Unsupported device");
  3891. }
  3892. device_extensions.push_back("VK_KHR_16bit_storage");
  3893. #ifdef GGML_VULKAN_VALIDATE
  3894. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  3895. #endif
  3896. if (device->fp16) {
  3897. device_extensions.push_back("VK_KHR_shader_float16_int8");
  3898. }
  3899. #if defined(VK_KHR_cooperative_matrix)
  3900. if (device->coopmat_support) {
  3901. // Query supported shapes
  3902. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  3903. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  3904. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  3905. uint32_t cm_props_num;
  3906. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  3907. cm_props.resize(cm_props_num);
  3908. for (auto& prop : cm_props) {
  3909. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  3910. }
  3911. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  3912. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  3913. for (auto& prop : cm_props) {
  3914. 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));
  3915. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  3916. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  3917. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3918. ) {
  3919. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  3920. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  3921. // coopmat sizes not set yet
  3922. if (device->coopmat_m == 0) {
  3923. device->coopmat_acc_f32_support = true;
  3924. device->coopmat_m = prop.MSize;
  3925. device->coopmat_n = prop.NSize;
  3926. device->coopmat_k = prop.KSize;
  3927. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3928. // Only enable if shape is identical
  3929. device->coopmat_acc_f32_support = true;
  3930. }
  3931. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3932. device->coopmat_support_16x16x16_f32acc = true;
  3933. }
  3934. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  3935. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  3936. // coopmat sizes not set yet
  3937. if (device->coopmat_m == 0) {
  3938. device->coopmat_acc_f16_support = true;
  3939. device->coopmat_m = prop.MSize;
  3940. device->coopmat_n = prop.NSize;
  3941. device->coopmat_k = prop.KSize;
  3942. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3943. // Only enable if shape is identical
  3944. device->coopmat_acc_f16_support = true;
  3945. }
  3946. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3947. device->coopmat_support_16x16x16_f16acc = true;
  3948. }
  3949. }
  3950. } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 &&
  3951. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 &&
  3952. (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 &&
  3953. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 &&
  3954. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup &&
  3955. device->coopmat_int_m == 0
  3956. ) {
  3957. device->coopmat_int_support = true;
  3958. device->coopmat_int_m = prop.MSize;
  3959. device->coopmat_int_n = prop.NSize;
  3960. device->coopmat_int_k = prop.KSize;
  3961. }
  3962. #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3963. if (prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3964. prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3965. prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3966. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3967. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3968. ) {
  3969. // coopmat sizes not set yet
  3970. if (device->coopmat_m == 0) {
  3971. device->coopmat_bf16_support = true;
  3972. device->coopmat_m = prop.MSize;
  3973. device->coopmat_n = prop.NSize;
  3974. device->coopmat_k = prop.KSize;
  3975. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3976. // Only enable if shape is identical
  3977. device->coopmat_bf16_support = true;
  3978. }
  3979. }
  3980. #endif
  3981. }
  3982. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  3983. // No suitable matmul mode found
  3984. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  3985. device->coopmat_support = false;
  3986. }
  3987. if (getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3988. device->coopmat_bf16_support = false;
  3989. }
  3990. }
  3991. if (device->coopmat_support) {
  3992. device_extensions.push_back("VK_KHR_cooperative_matrix");
  3993. }
  3994. #if defined(VK_KHR_shader_bfloat16)
  3995. if (device->coopmat_bf16_support) {
  3996. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3997. }
  3998. #endif
  3999. #endif
  4000. device->name = GGML_VK_NAME + std::to_string(idx);
  4001. device_create_info = {
  4002. vk::DeviceCreateFlags(),
  4003. device_queue_create_infos,
  4004. {},
  4005. device_extensions
  4006. };
  4007. device_create_info.setPNext(&device_features2);
  4008. device->device = device->physical_device.createDevice(device_create_info);
  4009. // Queues
  4010. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  4011. // Shaders
  4012. // Disable matmul tile sizes early if performance low or not supported
  4013. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  4014. switch (device->vendor_id) {
  4015. #ifndef GGML_VULKAN_RUN_TESTS
  4016. case VK_VENDOR_ID_AMD:
  4017. case VK_VENDOR_ID_INTEL:
  4018. device->mul_mat_l[i] = false;
  4019. device->mul_mat_m[i] = true;
  4020. device->mul_mat_s[i] = true;
  4021. device->mul_mat_id_l[i] = false;
  4022. device->mul_mat_id_m[i] = true;
  4023. device->mul_mat_id_s[i] = true;
  4024. break;
  4025. case VK_VENDOR_ID_APPLE:
  4026. device->mul_mat_l[i] = false;
  4027. device->mul_mat_m[i] = true;
  4028. device->mul_mat_s[i] = false;
  4029. device->mul_mat_id_l[i] = false;
  4030. device->mul_mat_id_m[i] = true;
  4031. device->mul_mat_id_s[i] = false;
  4032. break;
  4033. #endif
  4034. default:
  4035. device->mul_mat_l[i] = true;
  4036. device->mul_mat_m[i] = true;
  4037. device->mul_mat_s[i] = true;
  4038. device->mul_mat_id_l[i] = true;
  4039. device->mul_mat_id_m[i] = true;
  4040. device->mul_mat_id_s[i] = true;
  4041. break;
  4042. }
  4043. }
  4044. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  4045. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  4046. for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
  4047. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  4048. dsl_binding_flags.push_back({});
  4049. }
  4050. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  4051. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  4052. {},
  4053. dsl_binding);
  4054. descriptor_set_layout_create_info.setPNext(&dslbfci);
  4055. device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  4056. ggml_vk_load_shaders(device);
  4057. if (!device->single_queue) {
  4058. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  4059. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  4060. } else {
  4061. // TODO: Use pointer or reference to avoid copy
  4062. device->transfer_queue.copyFrom(device->compute_queue);
  4063. device->transfer_queue.cmd_pool.init(device, &device->transfer_queue);
  4064. }
  4065. device->buffer_type = {
  4066. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  4067. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  4068. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  4069. };
  4070. device->fence = device->device.createFence({});
  4071. device->idx = idx;
  4072. device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr;
  4073. device->add_rms_fusion = !device->disable_fusion &&
  4074. device->subgroup_arithmetic &&
  4075. device->vendor_id != VK_VENDOR_ID_INTEL;
  4076. device->partials_binding_alignment =
  4077. std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment);
  4078. device->mmvq_mode = 0;
  4079. if (getenv("GGML_VK_DISABLE_MMVQ")) {
  4080. device->mmvq_mode = -1;
  4081. } else if (getenv("GGML_VK_FORCE_MMVQ")) {
  4082. device->mmvq_mode = 1;
  4083. }
  4084. return device;
  4085. }
  4086. return vk_instance.devices[idx];
  4087. }
  4088. static void ggml_vk_print_gpu_info(size_t idx) {
  4089. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4090. size_t dev_num = vk_instance.device_indices[idx];
  4091. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  4092. GGML_ASSERT(vk_instance_initialized);
  4093. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4094. if (dev_num >= devices.size()) {
  4095. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  4096. throw std::runtime_error("Device not found");
  4097. }
  4098. vk::PhysicalDevice physical_device = devices[dev_num];
  4099. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  4100. bool fp16_storage = false;
  4101. bool fp16_compute = false;
  4102. bool coopmat_support = false;
  4103. bool coopmat2_support = false;
  4104. bool integer_dot_product = false;
  4105. bool bfloat16_support = false;
  4106. for (auto properties : ext_props) {
  4107. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  4108. fp16_storage = true;
  4109. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  4110. fp16_compute = true;
  4111. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4112. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  4113. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  4114. coopmat_support = true;
  4115. #endif
  4116. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  4117. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  4118. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  4119. coopmat2_support = true;
  4120. #endif
  4121. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  4122. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  4123. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  4124. integer_dot_product = true;
  4125. #endif
  4126. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4127. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  4128. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4129. bfloat16_support = true;
  4130. #endif
  4131. }
  4132. }
  4133. const vk_device_architecture device_architecture = get_device_architecture(physical_device);
  4134. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  4135. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  4136. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  4137. vk::PhysicalDeviceProperties2 props2;
  4138. vk::PhysicalDeviceMaintenance3Properties props3;
  4139. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  4140. vk::PhysicalDeviceDriverProperties driver_props;
  4141. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  4142. props2.pNext = &props3;
  4143. props3.pNext = &subgroup_props;
  4144. subgroup_props.pNext = &driver_props;
  4145. // Pointer to the last chain element
  4146. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  4147. if (integer_dot_product) {
  4148. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4149. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4150. }
  4151. physical_device.getProperties2(&props2);
  4152. VkPhysicalDeviceFeatures2 device_features2;
  4153. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  4154. device_features2.pNext = nullptr;
  4155. VkPhysicalDeviceVulkan11Features vk11_features;
  4156. vk11_features.pNext = nullptr;
  4157. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  4158. device_features2.pNext = &vk11_features;
  4159. VkPhysicalDeviceVulkan12Features vk12_features;
  4160. vk12_features.pNext = nullptr;
  4161. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  4162. vk11_features.pNext = &vk12_features;
  4163. // Pointer to the last chain element
  4164. last_struct = (VkBaseOutStructure *)&vk12_features;
  4165. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4166. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  4167. coopmat_features.pNext = nullptr;
  4168. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  4169. coopmat_features.cooperativeMatrix = VK_FALSE;
  4170. if (coopmat_support) {
  4171. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  4172. last_struct = (VkBaseOutStructure *)&coopmat_features;
  4173. }
  4174. #endif
  4175. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  4176. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  4177. if (integer_dot_product) {
  4178. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4179. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4180. }
  4181. #if defined(VK_KHR_shader_bfloat16)
  4182. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  4183. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  4184. if (bfloat16_support) {
  4185. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  4186. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  4187. }
  4188. #endif
  4189. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  4190. fp16 = fp16 && vk12_features.shaderFloat16;
  4191. #if defined(VK_KHR_shader_bfloat16)
  4192. bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4193. #else
  4194. bool bf16 = false;
  4195. #endif
  4196. uint32_t default_subgroup_size = get_subgroup_size("", device_architecture);
  4197. const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize;
  4198. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  4199. integer_dot_product = integer_dot_product
  4200. && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated
  4201. && shader_integer_dot_product_features.shaderIntegerDotProduct;
  4202. coopmat_support = coopmat_support
  4203. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4204. && coopmat_features.cooperativeMatrix
  4205. #endif
  4206. && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture);
  4207. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  4208. std::string device_name = props2.properties.deviceName.data();
  4209. 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",
  4210. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, bf16, subgroup_size,
  4211. props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str());
  4212. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  4213. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  4214. }
  4215. }
  4216. static bool ggml_vk_instance_validation_ext_available();
  4217. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  4218. static bool ggml_vk_instance_debug_utils_ext_available(const std::vector<vk::ExtensionProperties> & instance_extensions);
  4219. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev);
  4220. static DispatchLoaderDynamic ggml_vk_default_dispatcher_instance;
  4221. DispatchLoaderDynamic & ggml_vk_default_dispatcher() {
  4222. return ggml_vk_default_dispatcher_instance;
  4223. }
  4224. static void ggml_vk_instance_init() {
  4225. if (vk_instance_initialized) {
  4226. return;
  4227. }
  4228. VK_LOG_DEBUG("ggml_vk_instance_init()");
  4229. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4230. ggml_vk_default_dispatcher_instance.init(vkGetInstanceProcAddr);
  4231. uint32_t api_version = vk::enumerateInstanceVersion();
  4232. if (api_version < VK_API_VERSION_1_2) {
  4233. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  4234. throw vk::SystemError(vk::Result::eErrorFeatureNotPresent, "Vulkan 1.2 required");
  4235. }
  4236. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  4237. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  4238. const bool validation_ext = ggml_vk_instance_validation_ext_available();
  4239. #ifdef __APPLE__
  4240. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  4241. #endif
  4242. const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr;
  4243. std::vector<const char*> layers;
  4244. if (validation_ext) {
  4245. layers.push_back("VK_LAYER_KHRONOS_validation");
  4246. }
  4247. std::vector<const char*> extensions;
  4248. if (validation_ext) {
  4249. extensions.push_back("VK_EXT_validation_features");
  4250. }
  4251. #ifdef __APPLE__
  4252. if (portability_enumeration_ext) {
  4253. extensions.push_back("VK_KHR_portability_enumeration");
  4254. }
  4255. #endif
  4256. if (debug_utils_ext) {
  4257. extensions.push_back("VK_EXT_debug_utils");
  4258. }
  4259. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions);
  4260. #ifdef __APPLE__
  4261. if (portability_enumeration_ext) {
  4262. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  4263. }
  4264. #endif
  4265. std::vector<vk::ValidationFeatureEnableEXT> features_enable;
  4266. vk::ValidationFeaturesEXT validation_features;
  4267. if (validation_ext) {
  4268. features_enable = { vk::ValidationFeatureEnableEXT::eBestPractices };
  4269. validation_features = {
  4270. features_enable,
  4271. {},
  4272. };
  4273. validation_features.setPNext(nullptr);
  4274. instance_create_info.setPNext(&validation_features);
  4275. GGML_LOG_DEBUG("ggml_vulkan: Validation layers enabled\n");
  4276. }
  4277. vk_instance.instance = vk::createInstance(instance_create_info);
  4278. vk_instance_initialized = true;
  4279. if (debug_utils_ext) {
  4280. vk_instance.debug_utils_support = true;
  4281. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT");
  4282. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT");
  4283. vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT");
  4284. vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT");
  4285. vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT");
  4286. vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT");
  4287. }
  4288. vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr;
  4289. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4290. VULKAN_HPP_DEFAULT_DISPATCHER.init(vk_instance.instance);
  4291. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4292. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  4293. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  4294. if (devices_env != nullptr) {
  4295. size_t num_available_devices = devices.size();
  4296. std::string devices(devices_env);
  4297. std::replace(devices.begin(), devices.end(), ',', ' ');
  4298. std::stringstream ss(devices);
  4299. size_t tmp;
  4300. while (ss >> tmp) {
  4301. if(tmp >= num_available_devices) {
  4302. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  4303. throw std::runtime_error("Invalid Vulkan device index");
  4304. }
  4305. vk_instance.device_indices.push_back(tmp);
  4306. }
  4307. } else {
  4308. // If no vulkan devices are found, return early
  4309. if (devices.empty()) {
  4310. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4311. return;
  4312. }
  4313. // Default to using all dedicated GPUs
  4314. for (size_t i = 0; i < devices.size(); i++) {
  4315. vk::PhysicalDeviceProperties2 new_props;
  4316. vk::PhysicalDeviceDriverProperties new_driver;
  4317. vk::PhysicalDeviceIDProperties new_id;
  4318. new_props.pNext = &new_driver;
  4319. new_driver.pNext = &new_id;
  4320. devices[i].getProperties2(&new_props);
  4321. if ((new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu || new_props.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) && ggml_vk_device_is_supported(devices[i])) {
  4322. // Check if there are two physical devices corresponding to the same GPU
  4323. auto old_device = std::find_if(
  4324. vk_instance.device_indices.begin(),
  4325. vk_instance.device_indices.end(),
  4326. [&devices, &new_id](const size_t k){
  4327. vk::PhysicalDeviceProperties2 old_props;
  4328. vk::PhysicalDeviceIDProperties old_id;
  4329. old_props.pNext = &old_id;
  4330. devices[k].getProperties2(&old_props);
  4331. bool equals = std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  4332. equals = equals || (
  4333. old_id.deviceLUIDValid && new_id.deviceLUIDValid &&
  4334. std::equal(std::begin(old_id.deviceLUID), std::end(old_id.deviceLUID), std::begin(new_id.deviceLUID))
  4335. );
  4336. return equals;
  4337. }
  4338. );
  4339. if (old_device == vk_instance.device_indices.end()) {
  4340. vk_instance.device_indices.push_back(i);
  4341. } else {
  4342. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  4343. // This can cause error when splitting layers aross the devices, need to keep only 1
  4344. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  4345. vk::PhysicalDeviceProperties2 old_props;
  4346. vk::PhysicalDeviceDriverProperties old_driver;
  4347. old_props.pNext = &old_driver;
  4348. devices[*old_device].getProperties2(&old_props);
  4349. std::map<vk::DriverId, int> driver_priorities {};
  4350. int old_priority = std::numeric_limits<int>::max();
  4351. int new_priority = std::numeric_limits<int>::max();
  4352. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  4353. // Smaller number -> higher priority
  4354. switch (old_props.properties.vendorID) {
  4355. case VK_VENDOR_ID_AMD:
  4356. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  4357. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  4358. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  4359. break;
  4360. case VK_VENDOR_ID_INTEL:
  4361. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  4362. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  4363. break;
  4364. case VK_VENDOR_ID_NVIDIA:
  4365. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  4366. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  4367. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  4368. #endif
  4369. break;
  4370. }
  4371. driver_priorities[vk::DriverId::eMesaDozen] = 100;
  4372. if (driver_priorities.count(old_driver.driverID)) {
  4373. old_priority = driver_priorities[old_driver.driverID];
  4374. }
  4375. if (driver_priorities.count(new_driver.driverID)) {
  4376. new_priority = driver_priorities[new_driver.driverID];
  4377. }
  4378. if (new_priority < old_priority) {
  4379. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  4380. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  4381. vk_instance.device_indices.push_back(i);
  4382. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  4383. }
  4384. else {
  4385. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  4386. }
  4387. }
  4388. }
  4389. }
  4390. // If no GPUs found, fall back to the first non-CPU device.
  4391. // If only CPU devices are available, return without devices.
  4392. if (vk_instance.device_indices.empty()) {
  4393. for (size_t i = 0; i < devices.size(); i++) {
  4394. if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) {
  4395. vk_instance.device_indices.push_back(i);
  4396. break;
  4397. }
  4398. }
  4399. }
  4400. if (vk_instance.device_indices.empty()) {
  4401. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4402. return;
  4403. }
  4404. }
  4405. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  4406. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  4407. vk::PhysicalDevice vkdev = devices[vk_instance.device_indices[i]];
  4408. std::vector<vk::ExtensionProperties> extensionprops = vkdev.enumerateDeviceExtensionProperties();
  4409. bool membudget_supported = false;
  4410. for (const auto & ext : extensionprops) {
  4411. if (strcmp(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, ext.extensionName) == 0) {
  4412. membudget_supported = true;
  4413. break;
  4414. }
  4415. }
  4416. vk_instance.device_supports_membudget.push_back(membudget_supported);
  4417. ggml_vk_print_gpu_info(i);
  4418. }
  4419. }
  4420. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  4421. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  4422. ggml_vk_instance_init();
  4423. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4424. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4425. ctx->device = ggml_vk_get_device(idx);
  4426. ctx->semaphore_idx = 0;
  4427. ctx->event_idx = 0;
  4428. ctx->prealloc_size_x = 0;
  4429. ctx->prealloc_size_y = 0;
  4430. ctx->prealloc_size_split_k = 0;
  4431. ctx->prealloc_size_add_rms_partials = 0;
  4432. ctx->fence = ctx->device->device.createFence({});
  4433. ctx->almost_ready_fence = ctx->device->device.createFence({});
  4434. ctx->compute_cmd_pool.init(ctx->device, &ctx->device->compute_queue);
  4435. ctx->transfer_cmd_pool.init(ctx->device, &ctx->device->transfer_queue);
  4436. #ifdef GGML_VULKAN_CHECK_RESULTS
  4437. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  4438. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  4439. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  4440. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  4441. #endif
  4442. }
  4443. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  4444. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  4445. switch (type) {
  4446. case GGML_TYPE_F32:
  4447. case GGML_TYPE_Q4_0:
  4448. case GGML_TYPE_Q4_1:
  4449. case GGML_TYPE_Q5_0:
  4450. case GGML_TYPE_Q5_1:
  4451. case GGML_TYPE_Q8_0:
  4452. case GGML_TYPE_Q2_K:
  4453. case GGML_TYPE_Q3_K:
  4454. case GGML_TYPE_Q4_K:
  4455. case GGML_TYPE_Q5_K:
  4456. case GGML_TYPE_Q6_K:
  4457. case GGML_TYPE_IQ1_S:
  4458. case GGML_TYPE_IQ1_M:
  4459. case GGML_TYPE_IQ2_XXS:
  4460. case GGML_TYPE_IQ2_XS:
  4461. case GGML_TYPE_IQ2_S:
  4462. case GGML_TYPE_IQ3_XXS:
  4463. case GGML_TYPE_IQ3_S:
  4464. case GGML_TYPE_IQ4_XS:
  4465. case GGML_TYPE_IQ4_NL:
  4466. case GGML_TYPE_MXFP4:
  4467. break;
  4468. default:
  4469. return nullptr;
  4470. }
  4471. return ctx->device->pipeline_dequant[type];
  4472. }
  4473. 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) {
  4474. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ", " << prec << ")");
  4475. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4476. return ctx->device->pipeline_matmul_f32;
  4477. }
  4478. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4479. return ctx->device->pipeline_matmul_f32_f16;
  4480. }
  4481. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4482. return ctx->device->pipeline_matmul_bf16;
  4483. }
  4484. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4485. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4486. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  4487. }
  4488. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4489. return ctx->device->pipeline_matmul_f16.f16acc;
  4490. }
  4491. } else {
  4492. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4493. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  4494. }
  4495. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4496. return ctx->device->pipeline_matmul_f16.f32acc;
  4497. }
  4498. }
  4499. // MMQ
  4500. if (src1_type == GGML_TYPE_Q8_1) {
  4501. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1[src0_type].f32acc;
  4502. if (pipelines->is_empty()) {
  4503. return nullptr;
  4504. }
  4505. return pipelines;
  4506. }
  4507. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  4508. return nullptr;
  4509. }
  4510. switch (src0_type) {
  4511. case GGML_TYPE_Q4_0:
  4512. case GGML_TYPE_Q4_1:
  4513. case GGML_TYPE_Q5_0:
  4514. case GGML_TYPE_Q5_1:
  4515. case GGML_TYPE_Q8_0:
  4516. case GGML_TYPE_Q2_K:
  4517. case GGML_TYPE_Q3_K:
  4518. case GGML_TYPE_Q4_K:
  4519. case GGML_TYPE_Q5_K:
  4520. case GGML_TYPE_Q6_K:
  4521. case GGML_TYPE_IQ1_S:
  4522. case GGML_TYPE_IQ1_M:
  4523. case GGML_TYPE_IQ2_XXS:
  4524. case GGML_TYPE_IQ2_XS:
  4525. case GGML_TYPE_IQ2_S:
  4526. case GGML_TYPE_IQ3_XXS:
  4527. case GGML_TYPE_IQ3_S:
  4528. case GGML_TYPE_IQ4_XS:
  4529. case GGML_TYPE_IQ4_NL:
  4530. case GGML_TYPE_MXFP4:
  4531. break;
  4532. default:
  4533. return nullptr;
  4534. }
  4535. if (ctx->device->coopmat2) {
  4536. assert(src1_type == GGML_TYPE_F16);
  4537. 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;
  4538. }
  4539. if (ctx->device->coopmat_support) {
  4540. 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;
  4541. }
  4542. 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;
  4543. }
  4544. 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) {
  4545. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  4546. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1);
  4547. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  4548. if (b_type == GGML_TYPE_Q8_1) {
  4549. switch (a_type) {
  4550. case GGML_TYPE_Q4_0:
  4551. case GGML_TYPE_Q4_1:
  4552. case GGML_TYPE_Q5_0:
  4553. case GGML_TYPE_Q5_1:
  4554. case GGML_TYPE_Q8_0:
  4555. break;
  4556. default:
  4557. return nullptr;
  4558. }
  4559. }
  4560. switch (a_type) {
  4561. case GGML_TYPE_F32:
  4562. case GGML_TYPE_F16:
  4563. case GGML_TYPE_BF16:
  4564. case GGML_TYPE_Q4_0:
  4565. case GGML_TYPE_Q4_1:
  4566. case GGML_TYPE_Q5_0:
  4567. case GGML_TYPE_Q5_1:
  4568. case GGML_TYPE_Q8_0:
  4569. case GGML_TYPE_Q2_K:
  4570. case GGML_TYPE_Q3_K:
  4571. case GGML_TYPE_Q4_K:
  4572. case GGML_TYPE_Q5_K:
  4573. case GGML_TYPE_Q6_K:
  4574. case GGML_TYPE_IQ1_S:
  4575. case GGML_TYPE_IQ1_M:
  4576. case GGML_TYPE_IQ2_XXS:
  4577. case GGML_TYPE_IQ2_XS:
  4578. case GGML_TYPE_IQ2_S:
  4579. case GGML_TYPE_IQ3_XXS:
  4580. case GGML_TYPE_IQ3_S:
  4581. case GGML_TYPE_IQ4_XS:
  4582. case GGML_TYPE_IQ4_NL:
  4583. case GGML_TYPE_MXFP4:
  4584. break;
  4585. default:
  4586. return nullptr;
  4587. }
  4588. // heuristic to choose workgroup size
  4589. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4590. 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) {
  4591. // Prefer larger workgroups when M is small, to spread the work out more
  4592. // and keep more SMs busy.
  4593. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4594. if (a_type == GGML_TYPE_Q6_K) {
  4595. if (m < 4096 && k >= 1024) {
  4596. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4597. }
  4598. } else {
  4599. if (m <= 8192 && k >= 1024) {
  4600. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4601. }
  4602. }
  4603. }
  4604. if (b_type == GGML_TYPE_Q8_1) {
  4605. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4606. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4607. }
  4608. return ctx->device->pipeline_dequant_mul_mat_vec_q8_1_f32[dmmv_wg][a_type][num_cols-1];
  4609. }
  4610. 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];
  4611. }
  4612. 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) {
  4613. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  4614. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4615. return ctx->device->pipeline_matmul_id_f32;
  4616. }
  4617. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4618. return ctx->device->pipeline_matmul_id_bf16;
  4619. }
  4620. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4621. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4622. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  4623. }
  4624. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4625. return ctx->device->pipeline_matmul_id_f16.f16acc;
  4626. }
  4627. } else {
  4628. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4629. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  4630. }
  4631. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4632. return ctx->device->pipeline_matmul_id_f16.f32acc;
  4633. }
  4634. }
  4635. // MMQ
  4636. if (src1_type == GGML_TYPE_Q8_1) {
  4637. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_id_q8_1[src0_type].f32acc;
  4638. if (pipelines->is_empty()) {
  4639. return nullptr;
  4640. }
  4641. return pipelines;
  4642. }
  4643. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  4644. switch (src0_type) {
  4645. case GGML_TYPE_Q4_0:
  4646. case GGML_TYPE_Q4_1:
  4647. case GGML_TYPE_Q5_0:
  4648. case GGML_TYPE_Q5_1:
  4649. case GGML_TYPE_Q8_0:
  4650. case GGML_TYPE_Q2_K:
  4651. case GGML_TYPE_Q3_K:
  4652. case GGML_TYPE_Q4_K:
  4653. case GGML_TYPE_Q5_K:
  4654. case GGML_TYPE_Q6_K:
  4655. case GGML_TYPE_IQ1_S:
  4656. case GGML_TYPE_IQ1_M:
  4657. case GGML_TYPE_IQ2_XXS:
  4658. case GGML_TYPE_IQ2_XS:
  4659. case GGML_TYPE_IQ2_S:
  4660. case GGML_TYPE_IQ3_XXS:
  4661. case GGML_TYPE_IQ3_S:
  4662. case GGML_TYPE_IQ4_XS:
  4663. case GGML_TYPE_IQ4_NL:
  4664. case GGML_TYPE_MXFP4:
  4665. break;
  4666. default:
  4667. return nullptr;
  4668. }
  4669. vk_matmul_pipeline2& mmp = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type];
  4670. // XXX TODO 'prec' is not actually allowed in mul_mat_id.
  4671. bool prefer_fp16acc = ctx->device->fp16 /*&& prec == GGML_PREC_DEFAULT*/;
  4672. bool support_fp16acc = !mmp.f16acc->is_empty();
  4673. bool support_fp32acc = !mmp.f32acc->is_empty();
  4674. if (support_fp16acc && (prefer_fp16acc || !support_fp32acc)) {
  4675. return mmp.f16acc;
  4676. } else {
  4677. GGML_ASSERT(support_fp32acc);
  4678. return mmp.f32acc;
  4679. }
  4680. }
  4681. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type) {
  4682. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()");
  4683. GGML_ASSERT(b_type == GGML_TYPE_F32);
  4684. switch (a_type) {
  4685. case GGML_TYPE_F32:
  4686. case GGML_TYPE_F16:
  4687. case GGML_TYPE_BF16:
  4688. case GGML_TYPE_Q4_0:
  4689. case GGML_TYPE_Q4_1:
  4690. case GGML_TYPE_Q5_0:
  4691. case GGML_TYPE_Q5_1:
  4692. case GGML_TYPE_Q8_0:
  4693. case GGML_TYPE_Q2_K:
  4694. case GGML_TYPE_Q3_K:
  4695. case GGML_TYPE_Q4_K:
  4696. case GGML_TYPE_Q5_K:
  4697. case GGML_TYPE_Q6_K:
  4698. case GGML_TYPE_IQ1_S:
  4699. case GGML_TYPE_IQ1_M:
  4700. case GGML_TYPE_IQ2_XXS:
  4701. case GGML_TYPE_IQ2_XS:
  4702. case GGML_TYPE_IQ2_S:
  4703. case GGML_TYPE_IQ3_XXS:
  4704. case GGML_TYPE_IQ3_S:
  4705. case GGML_TYPE_IQ4_XS:
  4706. case GGML_TYPE_IQ4_NL:
  4707. case GGML_TYPE_MXFP4:
  4708. break;
  4709. default:
  4710. return nullptr;
  4711. }
  4712. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[a_type];
  4713. }
  4714. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  4715. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  4716. vk_buffer buf = ggml_vk_create_buffer(device, size,
  4717. {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4718. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  4719. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  4720. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  4721. size/1024.0/1024.0);
  4722. device->device.freeMemory(buf->device_memory);
  4723. device->device.destroyBuffer(buf->buffer);
  4724. return nullptr;
  4725. }
  4726. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4727. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  4728. return buf->ptr;
  4729. }
  4730. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  4731. if (ptr == nullptr) {
  4732. return;
  4733. }
  4734. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  4735. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4736. vk_buffer buf;
  4737. size_t index;
  4738. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4739. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4740. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4741. if (ptr >= addr && ptr < endr) {
  4742. buf = std::get<2>(device->pinned_memory[i]);
  4743. index = i;
  4744. break;
  4745. }
  4746. }
  4747. if (buf == nullptr) {
  4748. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  4749. return;
  4750. }
  4751. ggml_vk_destroy_buffer(buf);
  4752. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  4753. }
  4754. static void ggml_vk_host_get(const vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  4755. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4756. buf = nullptr;
  4757. buf_offset = 0;
  4758. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4759. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4760. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4761. if (ptr >= addr && ptr < endr) {
  4762. buf = std::get<2>(device->pinned_memory[i]);
  4763. buf_offset = ((const uint8_t *)ptr) - addr;
  4764. break;
  4765. }
  4766. }
  4767. }
  4768. static vk_subbuffer ggml_vk_tensor_subbuffer(
  4769. const ggml_backend_vk_context * ctx, const ggml_tensor * tensor, bool allow_misalign = false) {
  4770. vk_buffer buffer = nullptr;
  4771. size_t offset = 0;
  4772. if (ctx->device->uma) {
  4773. ggml_vk_host_get(ctx->device, tensor->data, buffer, offset);
  4774. }
  4775. if (!buffer) {
  4776. auto buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  4777. buffer = buf_ctx->dev_buffer;
  4778. offset = vk_tensor_offset(tensor) + tensor->view_offs;
  4779. }
  4780. GGML_ASSERT(buffer != nullptr);
  4781. size_t size = ggml_nbytes(tensor);
  4782. size_t misalign_bytes = offset & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  4783. // The shader must support misaligned offsets when indexing into the buffer
  4784. GGML_ASSERT(allow_misalign || misalign_bytes == 0);
  4785. offset &= ~misalign_bytes;
  4786. size += misalign_bytes;
  4787. return vk_subbuffer{buffer, offset, size};
  4788. }
  4789. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) {
  4790. vk_submission s;
  4791. s.buffer = ggml_vk_create_cmd_buffer(device, p);
  4792. if (one_time) {
  4793. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  4794. } else {
  4795. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  4796. }
  4797. return s;
  4798. }
  4799. template <typename T> size_t push_constant_size(const T &t) {
  4800. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4801. GGML_UNUSED(t);
  4802. return sizeof(T);
  4803. }
  4804. template <typename T> size_t push_constant_size(const std::vector<T> &t) {
  4805. GGML_UNUSED(t);
  4806. return sizeof(T) * t.size();
  4807. }
  4808. template <typename T, uint32_t N> size_t push_constant_size(const std::array<T, N> &t) {
  4809. GGML_UNUSED(t);
  4810. return sizeof(T) * N;
  4811. }
  4812. template <typename T> const T *push_constant_data(const T &t) {
  4813. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4814. return &t;
  4815. }
  4816. template <typename T> const T *push_constant_data(const std::vector<T> &t) {
  4817. return t.data();
  4818. }
  4819. template <typename T, uint32_t N> const T *push_constant_data(const std::array<T, N> &t) {
  4820. return t.data();
  4821. }
  4822. template <typename T>
  4823. 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) {
  4824. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  4825. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  4826. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  4827. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  4828. for (auto& buffer : descriptor_buffer_infos) {
  4829. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  4830. }
  4831. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  4832. GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size());
  4833. GGML_ASSERT(descriptor_buffer_infos.size() <= MAX_PARAMETER_COUNT);
  4834. GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size());
  4835. vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[ctx->descriptor_set_idx++];
  4836. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  4837. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  4838. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size(push_constants), push_constant_data(push_constants));
  4839. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  4840. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  4841. pipeline->layout,
  4842. 0,
  4843. { descriptor_set },
  4844. {});
  4845. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  4846. }
  4847. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  4848. s.buffer.end();
  4849. s.wait_semaphores = std::move(wait_semaphores);
  4850. s.signal_semaphores = std::move(signal_semaphores);
  4851. }
  4852. static void ggml_vk_ctx_end(vk_context& ctx) {
  4853. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  4854. if (ctx->s == nullptr) {
  4855. return;
  4856. }
  4857. ctx->s->buffer.end();
  4858. ctx->s = nullptr;
  4859. }
  4860. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  4861. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  4862. if (subctx->s != nullptr) {
  4863. ggml_vk_ctx_end(subctx);
  4864. }
  4865. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) });
  4866. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  4867. }
  4868. static size_t ggml_vk_align_size(size_t width, size_t align) {
  4869. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  4870. return CEIL_DIV(width, align) * align;
  4871. }
  4872. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  4873. if (memcpys == nullptr) {
  4874. memcpy(dst, src, size);
  4875. } else {
  4876. memcpys->emplace_back(dst, src, size);
  4877. }
  4878. }
  4879. static void deferred_memset(void * dst, uint32_t val, size_t size, std::vector<vk_staging_memset>* memsets = nullptr) {
  4880. if (memsets == nullptr) {
  4881. memset(dst, val, size);
  4882. } else {
  4883. memsets->emplace_back(dst, val, size);
  4884. }
  4885. }
  4886. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  4887. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  4888. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  4889. ggml_vk_destroy_buffer(device->sync_staging);
  4890. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  4891. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4892. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  4893. }
  4894. }
  4895. static void ggml_vk_ensure_sync_staging_buffer(ggml_backend_vk_context * ctx, size_t size) {
  4896. if (ctx->sync_staging == nullptr || ctx->sync_staging->size < size) {
  4897. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  4898. ggml_vk_destroy_buffer(ctx->sync_staging);
  4899. ctx->sync_staging = ggml_vk_create_buffer_check(ctx->device, size,
  4900. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4901. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  4902. }
  4903. }
  4904. 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) {
  4905. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  4906. GGML_ASSERT(!ggml_is_contiguous(tensor));
  4907. // Buffer is already mapped
  4908. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4909. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4910. GGML_ABORT("fatal error");
  4911. }
  4912. // Check if src is pinned memory
  4913. vk_buffer buf = nullptr;
  4914. size_t buf_offset = 0;
  4915. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  4916. const uint64_t ne0 = tensor->ne[0];
  4917. const uint64_t ne1 = tensor->ne[1];
  4918. const uint64_t ne2 = tensor->ne[2];
  4919. const uint64_t ne3 = tensor->ne[3];
  4920. const uint64_t nb0 = tensor->nb[0];
  4921. const uint64_t nb1 = tensor->nb[1];
  4922. const uint64_t nb2 = tensor->nb[2];
  4923. const uint64_t nb3 = tensor->nb[3];
  4924. const ggml_type type = tensor->type;
  4925. const uint64_t ts = ggml_type_size(type);
  4926. const uint64_t bs = ggml_blck_size(type);
  4927. const uint64_t dstnb0 = ts;
  4928. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  4929. const uint64_t dstnb2 = dstnb1*ne1;
  4930. const uint64_t dstnb3 = dstnb2*ne2;
  4931. const uint64_t ne = ggml_nelements(tensor);
  4932. if (buf != nullptr) {
  4933. // Memory is pinned, use as staging buffer
  4934. std::vector<vk::BufferCopy> slices;
  4935. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4936. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4937. // Find longest contiguous slice
  4938. if (ne1*nb1 == dstnb2) {
  4939. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  4940. } else {
  4941. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4942. if (ne0*nb0/bs == dstnb1) {
  4943. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  4944. } else {
  4945. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4946. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4947. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4948. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  4949. }
  4950. }
  4951. }
  4952. }
  4953. }
  4954. }
  4955. ggml_vk_sync_buffers(ctx, subctx);
  4956. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  4957. return;
  4958. }
  4959. if (!sync_staging) {
  4960. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  4961. }
  4962. // Staging buffer required
  4963. vk_buffer& staging = ctx->device->sync_staging;
  4964. const uint64_t copy_size = ts*ne/bs;
  4965. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  4966. VkBufferCopy buf_copy{ 0, offset, copy_size };
  4967. ggml_vk_sync_buffers(ctx, subctx);
  4968. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  4969. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4970. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4971. // Find longest contiguous slice
  4972. if (ne1*nb1 == dstnb2) {
  4973. 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);
  4974. } else {
  4975. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4976. if (ne0*nb0/bs == dstnb1) {
  4977. 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);
  4978. } else {
  4979. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4980. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4981. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4982. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  4983. }
  4984. }
  4985. }
  4986. }
  4987. }
  4988. }
  4989. }
  4990. 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) {
  4991. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  4992. // Buffer is already mapped
  4993. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4994. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4995. GGML_ABORT("fatal error");
  4996. }
  4997. // Check if src is pinned memory
  4998. vk_buffer buf = nullptr;
  4999. size_t buf_offset = 0;
  5000. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  5001. if (buf != nullptr) {
  5002. // Memory is pinned, use as staging buffer
  5003. std::vector<vk::BufferCopy> slices(1);
  5004. if (width == spitch) {
  5005. // Only do single write if stride is equal
  5006. slices[0].srcOffset = buf_offset;
  5007. slices[0].dstOffset = offset;
  5008. slices[0].size = width * height;
  5009. } else {
  5010. slices.resize(height);
  5011. for (size_t i = 0; i < height; i++) {
  5012. slices[i].srcOffset = buf_offset + i * spitch;
  5013. slices[i].dstOffset = offset + i * width;
  5014. slices[i].size = width;
  5015. }
  5016. }
  5017. ggml_vk_sync_buffers(nullptr, subctx);
  5018. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  5019. return;
  5020. }
  5021. VK_LOG_DEBUG("STAGING");
  5022. if (!sync_staging) {
  5023. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  5024. }
  5025. // Staging buffer required
  5026. const size_t copy_size = width*height;
  5027. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  5028. vk_buffer& staging_buffer = dst->device->sync_staging;
  5029. VkBufferCopy buf_copy = {
  5030. 0,
  5031. offset,
  5032. copy_size};
  5033. ggml_vk_sync_buffers(nullptr, subctx);
  5034. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  5035. if (width == spitch) {
  5036. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  5037. } else {
  5038. for (size_t i = 0; i < height; i++) {
  5039. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  5040. }
  5041. }
  5042. }
  5043. 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) {
  5044. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  5045. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  5046. }
  5047. 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) {
  5048. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  5049. // Buffer is already mapped
  5050. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5051. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5052. for (size_t i = 0; i < height; i++) {
  5053. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  5054. }
  5055. } else {
  5056. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5057. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5058. ggml_vk_ctx_begin(dst->device, subctx);
  5059. ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  5060. ggml_vk_ctx_end(subctx);
  5061. for (auto& cpy : subctx->in_memcpys) {
  5062. memcpy(cpy.dst, cpy.src, cpy.n);
  5063. }
  5064. for (auto& mset : subctx->memsets) {
  5065. memset(mset.dst, mset.val, mset.n);
  5066. }
  5067. ggml_vk_submit(subctx, dst->device->fence);
  5068. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  5069. dst->device->device.resetFences({ dst->device->fence });
  5070. ggml_vk_queue_command_pools_cleanup(dst->device);
  5071. }
  5072. }
  5073. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  5074. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  5075. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  5076. }
  5077. static bool ggml_vk_buffer_read_2d_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t spitch, size_t dpitch, size_t width, size_t height, bool sync_staging = false) {
  5078. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  5079. GGML_ASSERT(width > 0);
  5080. GGML_ASSERT(height > 0);
  5081. GGML_ASSERT(src != nullptr);
  5082. // TODO: staging_offset is not used
  5083. // Check if dst is pinned memory
  5084. vk_buffer buf = nullptr;
  5085. size_t buf_offset = 0;
  5086. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  5087. std::vector<vk::BufferCopy> slices(1);
  5088. if (width == spitch && width == dpitch) {
  5089. // Only do single write if stride is equal
  5090. slices[0].srcOffset = offset;
  5091. slices[0].dstOffset = buf_offset;
  5092. slices[0].size = width * height;
  5093. } else {
  5094. slices.resize(height);
  5095. for (size_t i = 0; i < height; i++) {
  5096. slices[i].srcOffset = offset + i * spitch;
  5097. slices[i].dstOffset = buf_offset + i * dpitch;
  5098. slices[i].size = width;
  5099. }
  5100. }
  5101. if (buf != nullptr) {
  5102. // Memory is pinned, use as staging buffer
  5103. ggml_vk_sync_buffers(nullptr, subctx);
  5104. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  5105. return true;
  5106. }
  5107. VK_LOG_DEBUG("STAGING");
  5108. if (!sync_staging) {
  5109. // copy was not handled caller needs to fall back
  5110. return false;
  5111. }
  5112. // Fall back to staging buffer
  5113. const size_t copy_size = dpitch * height;
  5114. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  5115. vk_buffer& staging_buffer = src->device->sync_staging;
  5116. ggml_vk_sync_buffers(nullptr, subctx);
  5117. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  5118. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  5119. return true;
  5120. }
  5121. static bool ggml_vk_buffer_read_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t size, bool sync_staging = false) {
  5122. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  5123. }
  5124. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  5125. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  5126. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  5127. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  5128. // the HW device to host copy path.
  5129. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  5130. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5131. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  5132. } else {
  5133. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5134. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5135. ggml_vk_ctx_begin(src->device, subctx);
  5136. bool ret = ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  5137. GGML_ASSERT(ret);
  5138. ggml_vk_ctx_end(subctx);
  5139. ggml_vk_submit(subctx, src->device->fence);
  5140. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  5141. src->device->device.resetFences({ src->device->fence });
  5142. ggml_vk_queue_command_pools_cleanup(src->device);
  5143. for (auto& cpy : subctx->out_memcpys) {
  5144. memcpy(cpy.dst, cpy.src, cpy.n);
  5145. }
  5146. }
  5147. }
  5148. 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) {
  5149. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  5150. // Make sure both buffers are on same device
  5151. GGML_ASSERT(src->device == dst->device);
  5152. VkBufferCopy bc{ src_offset, dst_offset, size };
  5153. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  5154. }
  5155. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  5156. if (src->device == dst->device) {
  5157. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5158. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  5159. // Copy within the device
  5160. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5161. ggml_vk_ctx_begin(src->device, subctx);
  5162. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  5163. ggml_vk_ctx_end(subctx);
  5164. ggml_vk_submit(subctx, src->device->fence);
  5165. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  5166. src->device->device.resetFences({ src->device->fence });
  5167. ggml_vk_queue_command_pools_cleanup(src->device);
  5168. } else {
  5169. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  5170. // Copy device to device
  5171. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  5172. // Copy to src staging buffer
  5173. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  5174. // Copy to dst buffer
  5175. ggml_vk_buffer_write_2d(dst, dst_offset, src->device->sync_staging->ptr, 0, size, 1);
  5176. }
  5177. }
  5178. static void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5179. VK_LOG_DEBUG("ggml_vk_buffer_memset_async(" << offset << ", " << c << ", " << size << ")");
  5180. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5181. dst->device->uma) {
  5182. deferred_memset((uint8_t*)dst->ptr + offset, c, size, &ctx->memsets);
  5183. return;
  5184. }
  5185. // Fall back to GPU fillBuffer for non-UMA or non-host-visible buffers
  5186. ctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5187. }
  5188. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5189. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  5190. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5191. dst->device->uma) {
  5192. memset((uint8_t*)dst->ptr + offset, c, size);
  5193. return;
  5194. }
  5195. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5196. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5197. ggml_vk_ctx_begin(dst->device, subctx);
  5198. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5199. ggml_vk_ctx_end(subctx);
  5200. ggml_vk_submit(subctx, dst->device->fence);
  5201. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  5202. dst->device->device.resetFences({ dst->device->fence });
  5203. ggml_vk_queue_command_pools_cleanup(dst->device);
  5204. }
  5205. 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) {
  5206. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ", " << disable_split_k << ")");
  5207. if (disable_split_k) {
  5208. return 1;
  5209. }
  5210. uint32_t split_k = 1;
  5211. if (ctx->device->shader_core_count != 0 && m >= pipeline->wg_denoms[0] && n >= pipeline->wg_denoms[1]) {
  5212. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  5213. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  5214. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  5215. if (k >= 2048) {
  5216. if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) {
  5217. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  5218. } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) {
  5219. split_k = 3;
  5220. }
  5221. // Cap the split at 8x. Unless k is huge this is a lot of overhead.
  5222. split_k = std::min(split_k, 8u);
  5223. // ggml_vk_matmul will align the splits to be a multiple of 256.
  5224. // If this rounded up size would cause the last split to be empty,
  5225. // then reduce the split count.
  5226. while (true) {
  5227. if (split_k == 1) {
  5228. break;
  5229. }
  5230. uint32_t k_split = CEIL_DIV(k, split_k);
  5231. k_split = ROUNDUP_POW2(k_split, 256);
  5232. if (k_split * (split_k - 1) < k) {
  5233. break;
  5234. }
  5235. split_k--;
  5236. }
  5237. }
  5238. }
  5239. return split_k;
  5240. }
  5241. 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) {
  5242. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5243. if (ctx->device->coopmat2) {
  5244. const uint32_t shader_core_count = ctx->device->shader_core_count;
  5245. const uint32_t tiles_l = CEIL_DIV(m, mmp->a_l->wg_denoms[0]) * CEIL_DIV(n, mmp->a_l->wg_denoms[1]);
  5246. const uint32_t tiles_m = CEIL_DIV(m, mmp->a_m->wg_denoms[0]) * CEIL_DIV(n, mmp->a_m->wg_denoms[1]);
  5247. // Use large shader when the N dimension is greater than the medium shader's tile size
  5248. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5249. // Prefer large over medium if either:
  5250. // - medium or large tiles would overfill the GPU
  5251. // - large tiles with a split_k==3 fits in the GPU and medium tiles with split_k==2 does not
  5252. // (medium with split_k==2 is probably better if it fits - more workgroups running and less split_k overhead)
  5253. bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count ||
  5254. // split_k==3 with large tiles likely better than medium tiles with no split_k.
  5255. (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2);
  5256. 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])) {
  5257. return aligned ? mmp->a_l : mmp->l;
  5258. }
  5259. // Use medium shader when the N dimension is greater than the small shader's tile size
  5260. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5261. if ((ctx->device->mul_mat_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_s[src0_type]) {
  5262. return aligned ? mmp->a_m : mmp->m;
  5263. }
  5264. return aligned ? mmp->a_s : mmp->s;
  5265. }
  5266. 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])) {
  5267. return aligned ? mmp->a_s : mmp->s;
  5268. }
  5269. if ((ctx->device->mul_mat_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l[src0_type]) {
  5270. return aligned ? mmp->a_m : mmp->m;
  5271. }
  5272. return aligned ? mmp->a_l : mmp->l;
  5273. GGML_UNUSED(src1_type);
  5274. }
  5275. 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) {
  5276. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5277. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, src0_type, src1_type)->align;
  5278. }
  5279. static void ggml_vk_matmul(
  5280. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5281. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  5282. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5283. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5284. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3,
  5285. uint32_t padded_n) {
  5286. 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 << ")");
  5287. if (split_k == 1) {
  5288. 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 };
  5289. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc, { m, n, batch });
  5290. return;
  5291. }
  5292. if (ctx->prealloc_split_k_need_sync) {
  5293. ggml_vk_sync_buffers(ctx, subctx);
  5294. }
  5295. GGML_ASSERT(batch_stride_d == m * n);
  5296. // Round the split size up to a multiple of 256 (k-quant alignment)
  5297. uint32_t k_split = CEIL_DIV(k, split_k);
  5298. k_split = ROUNDUP_POW2(k_split, 256);
  5299. 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 };
  5300. // Make sure enough workgroups get assigned for split k to work
  5301. 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 });
  5302. ggml_vk_sync_buffers(ctx, subctx);
  5303. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  5304. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 });
  5305. ctx->prealloc_split_k_need_sync = true;
  5306. }
  5307. 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) {
  5308. VK_LOG_DEBUG("ggml_vk_guess_matmul_id_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ")");
  5309. if (ctx->device->coopmat2) {
  5310. // Use large shader when the N dimension is greater than the medium shader's tile size
  5311. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5312. 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])) {
  5313. return aligned ? mmp->a_l : mmp->l;
  5314. }
  5315. // Use medium shader when the N dimension is greater than the small shader's tile size
  5316. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5317. if ((ctx->device->mul_mat_id_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_id_s[src0_type]) {
  5318. return aligned ? mmp->a_m : mmp->m;
  5319. }
  5320. return aligned ? mmp->a_s : mmp->s;
  5321. }
  5322. 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])) {
  5323. return aligned ? mmp->a_s : mmp->s;
  5324. }
  5325. if ((ctx->device->mul_mat_id_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l[src0_type]) {
  5326. return aligned ? mmp->a_m : mmp->m;
  5327. }
  5328. return aligned ? mmp->a_l : mmp->l;
  5329. }
  5330. 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) {
  5331. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ")");
  5332. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true, src0_type)->align;
  5333. }
  5334. static void ggml_vk_matmul_id(
  5335. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5336. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  5337. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5338. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5339. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11,
  5340. uint32_t padded_n) {
  5341. 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 << "), " <<
  5342. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  5343. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  5344. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  5345. 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,
  5346. nei0, nei1, nbi1, ne11, padded_n };
  5347. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, pc, { m, nei1, n_as });
  5348. }
  5349. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  5350. return
  5351. tensor->nb[0] == ggml_type_size(tensor->type) &&
  5352. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  5353. (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]);
  5354. }
  5355. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  5356. // Choose "contiguous copy" shader if src/dst are contiguous
  5357. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  5358. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  5359. if (contig) {
  5360. return ctx->device->pipeline_contig_cpy_f32_f32;
  5361. } else {
  5362. return ctx->device->pipeline_cpy_f32_f32;
  5363. }
  5364. }
  5365. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  5366. if (contig) {
  5367. return ctx->device->pipeline_contig_cpy_f32_f16;
  5368. } else {
  5369. return ctx->device->pipeline_cpy_f32_f16;
  5370. }
  5371. }
  5372. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  5373. if (contig) {
  5374. return ctx->device->pipeline_contig_cpy_f16_f16;
  5375. } else {
  5376. return ctx->device->pipeline_cpy_f16_f16;
  5377. }
  5378. }
  5379. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) {
  5380. if (contig) {
  5381. return ctx->device->pipeline_contig_cpy_f16_f32;
  5382. } else {
  5383. return ctx->device->pipeline_cpy_f16_f32;
  5384. }
  5385. }
  5386. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) {
  5387. if (contig) {
  5388. return ctx->device->pipeline_contig_cpy_f32_bf16;
  5389. } else {
  5390. return ctx->device->pipeline_cpy_f32_bf16;
  5391. }
  5392. }
  5393. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
  5394. if (contig) {
  5395. return ctx->device->pipeline_contig_cpy_f32_i32;
  5396. } else {
  5397. return ctx->device->pipeline_cpy_f32_i32;
  5398. }
  5399. }
  5400. if (src->type == GGML_TYPE_I32 && to == GGML_TYPE_F32) {
  5401. if (contig) {
  5402. return ctx->device->pipeline_contig_cpy_i32_f32;
  5403. } else {
  5404. return ctx->device->pipeline_cpy_i32_f32;
  5405. }
  5406. }
  5407. if (src->type == GGML_TYPE_F32) {
  5408. switch (to) {
  5409. case GGML_TYPE_Q4_0:
  5410. case GGML_TYPE_Q4_1:
  5411. case GGML_TYPE_Q5_0:
  5412. case GGML_TYPE_Q5_1:
  5413. case GGML_TYPE_Q8_0:
  5414. case GGML_TYPE_IQ4_NL:
  5415. return ctx->device->pipeline_cpy_f32_quant[to];
  5416. default:
  5417. break;
  5418. }
  5419. }
  5420. if (to == GGML_TYPE_F32) {
  5421. switch (src->type) {
  5422. case GGML_TYPE_Q4_0:
  5423. case GGML_TYPE_Q4_1:
  5424. case GGML_TYPE_Q5_0:
  5425. case GGML_TYPE_Q5_1:
  5426. case GGML_TYPE_Q8_0:
  5427. case GGML_TYPE_IQ4_NL:
  5428. return ctx->device->pipeline_cpy_quant_f32[src->type];
  5429. default:
  5430. break;
  5431. }
  5432. }
  5433. if (src->type == to) {
  5434. // Copy two or four bytes at a time, depending on block size.
  5435. // For quantized types, we scale by block size/type size. But
  5436. // this path is also used for bf16->bf16 for example, where the
  5437. // type size must be exactly 2 or 4.
  5438. GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4);
  5439. if ((ggml_type_size(src->type) % 4) == 0) {
  5440. if (contig) {
  5441. return ctx->device->pipeline_contig_cpy_f32_f32;
  5442. } else {
  5443. return ctx->device->pipeline_cpy_f32_f32;
  5444. }
  5445. } else {
  5446. if (contig) {
  5447. return ctx->device->pipeline_contig_cpy_f16_f16;
  5448. } else {
  5449. return ctx->device->pipeline_cpy_f16_f16;
  5450. }
  5451. }
  5452. }
  5453. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  5454. GGML_ABORT("fatal error");
  5455. }
  5456. static void ggml_vk_cpy_to_contiguous(ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline pipeline, const ggml_tensor * tensor, const vk_subbuffer & in, const vk_subbuffer & out) {
  5457. 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] << "), ";
  5458. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  5459. const int tensor_type_size = ggml_type_size(tensor->type);
  5460. const uint32_t ne = ggml_nelements(tensor);
  5461. std::array<uint32_t, 3> elements;
  5462. if (ne > 262144) {
  5463. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  5464. } else if (ne > 512) {
  5465. elements = { 512, CEIL_DIV(ne, 512), 1 };
  5466. } else {
  5467. elements = { ne, 1, 1 };
  5468. }
  5469. vk_op_unary_push_constants pc = {
  5470. (uint32_t)ne,
  5471. (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,
  5472. (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]),
  5473. 0,
  5474. 0.0f, 0.0f,
  5475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5476. };
  5477. init_pushconst_fastdiv(pc);
  5478. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements);
  5479. ggml_vk_sync_buffers(ctx, subctx);
  5480. }
  5481. static vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type) {
  5482. switch(type) {
  5483. case GGML_TYPE_Q8_1:
  5484. return ctx->device->pipeline_quantize_q8_1_x4;
  5485. default:
  5486. std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl;
  5487. GGML_ABORT("fatal error");
  5488. }
  5489. }
  5490. static void ggml_vk_quantize_q8_1(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_subbuffer & in, const vk_subbuffer & out, uint32_t ne) {
  5491. VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")");
  5492. vk_pipeline pipeline = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5493. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, std::array<uint32_t, 1>{ne}, { ne, 1, 1 });
  5494. ggml_vk_sync_buffers(ctx, subctx);
  5495. }
  5496. 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) {
  5497. 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];
  5498. 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];
  5499. 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];
  5500. std::cerr << "))");
  5501. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5502. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5503. const uint64_t ne00 = src0->ne[0];
  5504. const uint64_t ne01 = src0->ne[1];
  5505. const uint64_t ne02 = src0->ne[2];
  5506. const uint64_t ne03 = src0->ne[3];
  5507. const uint64_t ne10 = src1->ne[0];
  5508. const uint64_t ne11 = src1->ne[1];
  5509. const uint64_t ne12 = src1->ne[2];
  5510. const uint64_t ne13 = src1->ne[3];
  5511. const uint64_t ne21 = dst->ne[1];
  5512. const uint32_t stride_d = dst->nb[1] / ggml_type_size(dst->type);
  5513. const uint32_t stride_batch_d = stride_d*ne21;
  5514. const uint64_t r2 = ne12 / ne02;
  5515. const uint64_t r3 = ne13 / ne03;
  5516. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5517. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5518. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5519. vk_buffer d_Qx = nullptr;
  5520. size_t qx_buf_offset = 0;
  5521. vk_buffer d_Qy = nullptr;
  5522. size_t qy_buf_offset = 0;
  5523. bool src0_uma = false;
  5524. bool src1_uma = false;
  5525. if (ctx->device->uma) {
  5526. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5527. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5528. src0_uma = d_Qx != nullptr;
  5529. src1_uma = d_Qy != nullptr;
  5530. }
  5531. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5532. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5533. !ggml_vk_dim01_contiguous(src0);
  5534. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5535. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5536. !ggml_vk_dim01_contiguous(src1);
  5537. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5538. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5539. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5540. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  5541. // Check for mmq first
  5542. 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;
  5543. if (mmp == nullptr) {
  5544. // Fall back to f16 dequant mul mat
  5545. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  5546. quantize_y = false;
  5547. }
  5548. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5549. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  5550. if (qx_needs_dequant) {
  5551. // Fall back to dequant + f16 mulmat
  5552. 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]);
  5553. }
  5554. // Not implemented
  5555. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5556. 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)));
  5557. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8;
  5558. 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));
  5559. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  5560. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11;
  5561. const uint64_t x_ne = ggml_nelements(src0);
  5562. // 128 elements per Q8_1 x4 block
  5563. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  5564. const uint64_t d_ne = ggml_nelements(dst);
  5565. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline);
  5566. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  5567. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5568. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  5569. 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);
  5570. const uint64_t d_sz = sizeof(float) * d_ne;
  5571. vk_pipeline to_fp16_vk_0 = nullptr;
  5572. vk_pipeline to_fp16_vk_1 = nullptr;
  5573. vk_pipeline to_q8_1 = nullptr;
  5574. if (x_non_contig) {
  5575. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  5576. } else {
  5577. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  5578. }
  5579. if (y_non_contig) {
  5580. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  5581. } else {
  5582. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5583. }
  5584. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5585. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5586. if (quantize_y) {
  5587. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5588. }
  5589. {
  5590. const uint64_t split_k_size = split_k > 1 ? d_sz * split_k : 0;
  5591. if (
  5592. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  5593. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  5594. (split_k > 1 && split_k_size > ctx->device->properties.limits.maxStorageBufferRange)) {
  5595. GGML_ABORT("Requested preallocation size is too large");
  5596. }
  5597. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  5598. ctx->prealloc_size_x = x_sz;
  5599. ggml_vk_preallocate_buffers(ctx, subctx);
  5600. }
  5601. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  5602. ctx->prealloc_size_y = y_sz;
  5603. ggml_vk_preallocate_buffers(ctx, subctx);
  5604. }
  5605. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  5606. ctx->prealloc_size_split_k = split_k_size;
  5607. ggml_vk_preallocate_buffers(ctx, subctx);
  5608. }
  5609. // Request descriptor sets
  5610. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  5611. if (qx_needs_dequant) {
  5612. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5613. }
  5614. if (qy_needs_dequant) {
  5615. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5616. }
  5617. if (quantize_y) {
  5618. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5619. }
  5620. if (split_k > 1) {
  5621. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  5622. }
  5623. }
  5624. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5625. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5626. GGML_ASSERT(d_D != nullptr);
  5627. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz);
  5628. vk_buffer d_X;
  5629. uint64_t x_buf_offset = 0;
  5630. vk_buffer d_Y;
  5631. uint64_t y_buf_offset = 0;
  5632. if (!src0_uma) {
  5633. d_Qx = src0_buf_ctx->dev_buffer;
  5634. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5635. GGML_ASSERT(d_Qx != nullptr);
  5636. }
  5637. if (!src1_uma) {
  5638. d_Qy = src1_buf_ctx->dev_buffer;
  5639. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5640. GGML_ASSERT(d_Qy != nullptr);
  5641. }
  5642. if (qx_needs_dequant) {
  5643. d_X = ctx->prealloc_x;
  5644. GGML_ASSERT(d_X->size >= x_sz);
  5645. } else {
  5646. d_X = d_Qx;
  5647. x_buf_offset = qx_buf_offset;
  5648. GGML_ASSERT(qx_sz == x_sz);
  5649. }
  5650. if (qy_needs_dequant) {
  5651. d_Y = ctx->prealloc_y;
  5652. GGML_ASSERT(d_Y->size >= y_sz);
  5653. } else if (quantize_y) {
  5654. d_Y = ctx->prealloc_y;
  5655. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  5656. } else {
  5657. d_Y = d_Qy;
  5658. y_buf_offset = qy_buf_offset;
  5659. GGML_ASSERT(qy_sz == y_sz);
  5660. }
  5661. if (x_non_contig || qx_needs_dequant) {
  5662. if (ctx->prealloc_x_need_sync) {
  5663. ggml_vk_sync_buffers(ctx, subctx);
  5664. }
  5665. }
  5666. if (x_non_contig) {
  5667. 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));
  5668. } else if (qx_needs_dequant) {
  5669. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  5670. 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});
  5671. ggml_vk_sync_buffers(ctx, subctx);
  5672. }
  5673. if (y_non_contig) {
  5674. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5675. ctx->prealloc_y_last_tensor_used != src1) {
  5676. if (ctx->prealloc_y_need_sync) {
  5677. ggml_vk_sync_buffers(ctx, subctx);
  5678. }
  5679. 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));
  5680. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5681. ctx->prealloc_y_last_tensor_used = src1;
  5682. }
  5683. }
  5684. if (quantize_y) {
  5685. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5686. ctx->prealloc_y_last_tensor_used != src1) {
  5687. if (ctx->prealloc_y_need_sync) {
  5688. ggml_vk_sync_buffers(ctx, subctx);
  5689. }
  5690. 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);
  5691. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5692. ctx->prealloc_y_last_tensor_used = src1;
  5693. }
  5694. }
  5695. uint32_t stride_batch_x = ne00*ne01;
  5696. uint32_t stride_batch_y = ne10*ne11;
  5697. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5698. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5699. }
  5700. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  5701. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5702. }
  5703. // compute
  5704. ggml_vk_matmul(
  5705. ctx, subctx, pipeline,
  5706. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  5707. ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, d_sz * split_k },
  5708. ne01, ne11, ne10,
  5709. ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d,
  5710. split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n
  5711. ); // NOLINT
  5712. if (x_non_contig || qx_needs_dequant) {
  5713. ctx->prealloc_x_need_sync = true;
  5714. }
  5715. if (y_non_contig || quantize_y) {
  5716. ctx->prealloc_y_need_sync = true;
  5717. }
  5718. }
  5719. // Device tuning
  5720. static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_t n, uint32_t k, ggml_type src0_type) {
  5721. if (device->mmvq_mode == 1) {
  5722. return true;
  5723. } else if (device->mmvq_mode == -1) {
  5724. return false;
  5725. }
  5726. // MMVQ is generally good for batches
  5727. if (n > 1) {
  5728. return true;
  5729. }
  5730. switch (device->vendor_id) {
  5731. case VK_VENDOR_ID_NVIDIA:
  5732. switch (src0_type) {
  5733. case GGML_TYPE_Q8_0:
  5734. return device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  5735. default:
  5736. return true;
  5737. }
  5738. case VK_VENDOR_ID_AMD:
  5739. switch (src0_type) {
  5740. case GGML_TYPE_Q8_0:
  5741. return device->architecture == vk_device_architecture::AMD_GCN;
  5742. default:
  5743. return true;
  5744. }
  5745. case VK_VENDOR_ID_INTEL:
  5746. switch (src0_type) {
  5747. // From tests on A770 Linux, may need more tuning
  5748. case GGML_TYPE_Q4_0:
  5749. case GGML_TYPE_Q5_1:
  5750. return false;
  5751. default:
  5752. return true;
  5753. }
  5754. default:
  5755. return true;
  5756. }
  5757. GGML_UNUSED(m);
  5758. GGML_UNUSED(k);
  5759. }
  5760. 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) {
  5761. ggml_tensor * dst = cgraph->nodes[node_idx];
  5762. const ggml_tensor * src0 = dst->src[0];
  5763. const ggml_tensor * src1 = dst->src[1];
  5764. 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];
  5765. 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];
  5766. 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];
  5767. std::cerr << ")),)");
  5768. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5769. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5770. const uint64_t ne00 = src0->ne[0];
  5771. const uint64_t ne01 = src0->ne[1];
  5772. const uint64_t ne02 = src0->ne[2];
  5773. const uint64_t ne03 = src0->ne[3];
  5774. const uint64_t ne10 = src1->ne[0];
  5775. const uint64_t ne11 = src1->ne[1];
  5776. const uint64_t ne12 = src1->ne[2];
  5777. const uint64_t ne13 = src1->ne[3];
  5778. const uint64_t ne20 = dst->ne[0];
  5779. const uint64_t ne21 = dst->ne[1];
  5780. // const uint64_t ne22 = dst->ne[2];
  5781. // const uint64_t ne23 = dst->ne[3];
  5782. const uint64_t r2 = ne12 / ne02;
  5783. const uint64_t r3 = ne13 / ne03;
  5784. // batch_n indicates that we need to compute a few vector results, and this assumes
  5785. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  5786. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  5787. bool batch_n = ne11 > 1;
  5788. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  5789. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  5790. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  5791. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && ggml_vk_should_use_mmvq(ctx->device, ne01, ne11, ne10, src0->type);
  5792. vk_pipeline to_fp16_vk_0 = nullptr;
  5793. vk_pipeline to_fp16_vk_1 = nullptr;
  5794. if (x_non_contig) {
  5795. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  5796. }
  5797. if (y_non_contig) {
  5798. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  5799. } else {
  5800. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5801. }
  5802. // Check for mmq first
  5803. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr;
  5804. vk_pipeline to_q8_1 = nullptr;
  5805. if (dmmv == nullptr) {
  5806. // Fall back to f16 dequant mul mat
  5807. dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11, ne20, ne00);
  5808. quantize_y = false;
  5809. }
  5810. if (quantize_y) {
  5811. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5812. }
  5813. const bool qx_needs_dequant = x_non_contig;
  5814. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  5815. // Not implemented
  5816. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5817. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5818. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5819. GGML_ASSERT(dmmv != nullptr);
  5820. const uint64_t x_ne = ggml_nelements(src0);
  5821. const uint64_t y_ne = ggml_nelements(src1);
  5822. 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);
  5823. 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;
  5824. 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)) :
  5825. (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  5826. {
  5827. if (
  5828. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  5829. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  5830. GGML_ABORT("Requested preallocation size is too large");
  5831. }
  5832. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  5833. ctx->prealloc_size_x = x_sz;
  5834. ggml_vk_preallocate_buffers(ctx, subctx);
  5835. }
  5836. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  5837. ctx->prealloc_size_y = y_sz;
  5838. ggml_vk_preallocate_buffers(ctx, subctx);
  5839. }
  5840. // Request descriptor sets
  5841. if (qx_needs_dequant) {
  5842. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5843. }
  5844. if (qy_needs_dequant) {
  5845. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5846. }
  5847. if (quantize_y) {
  5848. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5849. }
  5850. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  5851. }
  5852. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  5853. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  5854. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  5855. vk_subbuffer d_X, d_Y;
  5856. if (qx_needs_dequant) {
  5857. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  5858. } else {
  5859. d_X = d_Qx;
  5860. GGML_ASSERT(qx_sz == x_sz);
  5861. }
  5862. if (qy_needs_dequant || quantize_y) {
  5863. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  5864. } else {
  5865. d_Y = d_Qy;
  5866. }
  5867. if (x_non_contig) {
  5868. if (ctx->prealloc_x_need_sync) {
  5869. ggml_vk_sync_buffers(ctx, subctx);
  5870. }
  5871. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  5872. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  5873. }
  5874. if (y_non_contig) {
  5875. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  5876. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5877. ctx->prealloc_y_last_tensor_used != src1) {
  5878. if (ctx->prealloc_y_need_sync) {
  5879. ggml_vk_sync_buffers(ctx, subctx);
  5880. }
  5881. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  5882. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5883. ctx->prealloc_y_last_tensor_used = src1;
  5884. }
  5885. }
  5886. if (quantize_y) {
  5887. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5888. ctx->prealloc_y_last_tensor_used != src1) {
  5889. if (ctx->prealloc_y_need_sync) {
  5890. ggml_vk_sync_buffers(ctx, subctx);
  5891. }
  5892. ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne);
  5893. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5894. ctx->prealloc_y_last_tensor_used = src1;
  5895. }
  5896. }
  5897. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  5898. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  5899. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  5900. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  5901. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5902. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5903. }
  5904. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  5905. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5906. }
  5907. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  5908. uint32_t groups_x = ne01;
  5909. uint32_t groups_z = 1;
  5910. if (ne01 > max_groups_x) {
  5911. groups_z = 64;
  5912. groups_x = CEIL_DIV(groups_x, groups_z);
  5913. }
  5914. uint32_t fusion_flags = 0;
  5915. vk_subbuffer d_F0 = d_D;
  5916. if (ctx->num_additional_fused_ops > 0) {
  5917. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  5918. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  5919. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  5920. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  5921. }
  5922. vk_subbuffer d_F1 = d_D;
  5923. if (ctx->num_additional_fused_ops == 2) {
  5924. const ggml_tensor * add = cgraph->nodes[node_idx + 2];
  5925. const ggml_tensor * bias = add->src[0] == cgraph->nodes[node_idx + 1] ? add->src[1] : add->src[0];
  5926. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  5927. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  5928. }
  5929. // compute
  5930. const vk_mat_vec_push_constants pc = {
  5931. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  5932. stride_batch_x, stride_batch_y, stride_batch_d,
  5933. fusion_flags,
  5934. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  5935. };
  5936. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  5937. {
  5938. d_X,
  5939. d_Y,
  5940. d_D,
  5941. d_F0,
  5942. d_F1,
  5943. },
  5944. pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  5945. if (x_non_contig) {
  5946. ctx->prealloc_x_need_sync = true;
  5947. }
  5948. if (y_non_contig || quantize_y) {
  5949. ctx->prealloc_y_need_sync = true;
  5950. }
  5951. }
  5952. 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) {
  5953. ggml_tensor * dst = cgraph->nodes[node_idx];
  5954. const ggml_tensor * src0 = dst->src[0];
  5955. const ggml_tensor * src1 = dst->src[1];
  5956. 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];
  5957. 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];
  5958. 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];
  5959. std::cerr << "))");
  5960. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  5961. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  5962. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  5963. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  5964. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  5965. const uint64_t ne00 = src0->ne[0];
  5966. const uint64_t ne01 = src0->ne[1];
  5967. const uint64_t ne02 = src0->ne[2];
  5968. // const uint64_t ne03 = src0->ne[3];
  5969. //const uint64_t ne10 = src1->ne[0];
  5970. const uint64_t ne11 = src1->ne[1];
  5971. const uint64_t ne12 = src1->ne[2];
  5972. // const uint64_t ne13 = src1->ne[3];
  5973. GGML_ASSERT(ne11 == 1);
  5974. // With grouped query attention there are > 1 Q matrices per K, V matrix.
  5975. uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02;
  5976. if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) {
  5977. gqa_ratio = 1;
  5978. }
  5979. {
  5980. // Request descriptor sets
  5981. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], 1);
  5982. }
  5983. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  5984. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  5985. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  5986. vk_subbuffer d_F0 = d_D;
  5987. uint32_t fusion_flags = 0;
  5988. if (ctx->num_additional_fused_ops > 0) {
  5989. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  5990. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  5991. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  5992. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  5993. }
  5994. vk_subbuffer d_F1 = d_D;
  5995. if (ctx->num_additional_fused_ops > 1) {
  5996. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  5997. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  5998. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  5999. }
  6000. // compute
  6001. vk_mat_vec_p021_push_constants pc = {
  6002. (uint32_t)ne00, (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne12,
  6003. 0, 0, fusion_flags
  6004. };
  6005. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6006. uint32_t workgroups_z = (uint32_t)ne12;
  6007. // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups
  6008. if (gqa_ratio > 1) {
  6009. workgroups_z /= gqa_ratio;
  6010. }
  6011. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1],
  6012. {
  6013. d_Qx,
  6014. d_Qy,
  6015. d_D,
  6016. d_F0,
  6017. d_F1,
  6018. }, pc, { 1, (uint32_t)ne01, workgroups_z });
  6019. }
  6020. 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) {
  6021. ggml_tensor * dst = cgraph->nodes[node_idx];
  6022. const ggml_tensor * src0 = dst->src[0];
  6023. const ggml_tensor * src1 = dst->src[1];
  6024. 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];
  6025. 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];
  6026. 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];
  6027. std::cerr << "))");
  6028. GGML_ASSERT(!ggml_is_transposed(src0));
  6029. GGML_ASSERT(!ggml_is_transposed(src1));
  6030. GGML_ASSERT(!ggml_is_permuted(src0));
  6031. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6032. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6033. const uint64_t ne00 = src0->ne[0];
  6034. const uint64_t ne01 = src0->ne[1];
  6035. const uint64_t ne02 = src0->ne[2];
  6036. const uint64_t ne03 = src0->ne[3];
  6037. const uint64_t nb01 = src0->nb[1];
  6038. const uint64_t nb02 = src0->nb[2];
  6039. const uint64_t nb12 = src1->nb[2];
  6040. // const uint64_t ne10 = src1->ne[0];
  6041. const uint64_t ne11 = src1->ne[1];
  6042. const uint64_t ne12 = src1->ne[2];
  6043. // const uint64_t ne13 = src1->ne[3];
  6044. const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t));
  6045. const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float));
  6046. const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float));
  6047. GGML_ASSERT(ne11 == 1);
  6048. GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in supports_op
  6049. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  6050. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  6051. const uint32_t channel_stride_y = nb12 / sizeof(float);
  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_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  6057. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6058. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  6059. vk_subbuffer d_F0 = d_D;
  6060. uint32_t fusion_flags = 0;
  6061. if (ctx->num_additional_fused_ops > 0) {
  6062. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6063. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6064. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6065. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6066. }
  6067. vk_subbuffer d_F1 = d_D;
  6068. if (ctx->num_additional_fused_ops > 1) {
  6069. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  6070. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6071. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6072. }
  6073. // compute
  6074. vk_mat_vec_nc_push_constants pc = {
  6075. (uint32_t)ne00, (uint32_t)ne01,
  6076. row_stride_x, channel_stride_x, channel_stride_y,
  6077. (uint32_t)(ne12 / ne02), (uint32_t)ne12,
  6078. 0, 0,
  6079. nb03, nb13, nb23, fusion_flags
  6080. };
  6081. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6082. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  6083. {
  6084. d_Qx,
  6085. d_Qy,
  6086. d_D,
  6087. d_F0,
  6088. d_F1,
  6089. }, pc, { (uint32_t)ne03, (uint32_t)ne01, (uint32_t)ne12 });
  6090. }
  6091. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6092. ggml_tensor * dst = cgraph->nodes[node_idx];
  6093. ggml_tensor * src0 = dst->src[0];
  6094. ggml_tensor * src1 = dst->src[1];
  6095. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  6096. // Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases
  6097. // where the M dimension is very large.
  6098. // Split_k doesn't work with M splitting.
  6099. const size_t nbytes = ggml_nbytes(src0);
  6100. const bool needs_split = nbytes > ctx->device->properties.limits.maxStorageBufferRange;
  6101. if (needs_split) {
  6102. // Choose the number of rows that can fit (and divide by two, to allow for any additional offsets)
  6103. const uint32_t M_split = ctx->device->properties.limits.maxStorageBufferRange / (2 * src0->nb[1]);
  6104. uint32_t m_offset = 0;
  6105. while (m_offset < dst->ne[0]) {
  6106. const uint32_t cur_M_size = std::min(M_split, (uint32_t)(dst->ne[0] - m_offset));
  6107. ggml_tensor dst2 = *dst;
  6108. ggml_tensor src02 = *src0;
  6109. dst2.view_src = dst->view_src ? dst->view_src : dst;
  6110. src02.view_src = src0->view_src ? src0->view_src : src0;
  6111. dst2.view_offs += m_offset * dst->nb[0];
  6112. src02.view_offs += m_offset * src0->nb[1];
  6113. dst2.ne[0] = cur_M_size;
  6114. src02.ne[1] = cur_M_size;
  6115. ggml_vk_mul_mat_q_f16(ctx, subctx, &src02, src1, &dst2, true);
  6116. m_offset += cur_M_size;
  6117. }
  6118. } else if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  6119. // detect 0213 permutation, and batch size of 1
  6120. src0->nb[0] <= src0->nb[2] &&
  6121. src0->nb[2] <= src0->nb[1] &&
  6122. src0->nb[1] <= src0->nb[3] &&
  6123. src1->nb[0] <= src1->nb[2] &&
  6124. src1->nb[2] <= src1->nb[1] &&
  6125. src1->nb[1] <= src1->nb[3] &&
  6126. src0->ne[3] == 1 &&
  6127. src1->ne[3] == 1) {
  6128. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, cgraph, node_idx);
  6129. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  6130. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  6131. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, cgraph, node_idx);
  6132. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  6133. // when ne12 and ne13 are one.
  6134. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  6135. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
  6136. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx);
  6137. } else {
  6138. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false);
  6139. }
  6140. }
  6141. 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) {
  6142. 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];
  6143. 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];
  6144. 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];
  6145. 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] << "),)");
  6146. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6147. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6148. const uint64_t ne00 = src0->ne[0];
  6149. const uint64_t ne01 = src0->ne[1];
  6150. const uint64_t ne02 = src0->ne[2];
  6151. // const uint64_t ne03 = src0->ne[3];
  6152. const uint64_t ne10 = src1->ne[0];
  6153. const uint64_t ne11 = src1->ne[1];
  6154. const uint64_t ne12 = src1->ne[2];
  6155. const uint64_t ne13 = src1->ne[3];
  6156. const uint64_t nei0 = ids->ne[0];
  6157. const uint64_t nei1 = ids->ne[1];
  6158. const uint32_t nbi1 = ids->nb[1];
  6159. const uint32_t nbi2 = ids->nb[2];
  6160. const uint64_t ne20 = dst->ne[0];
  6161. const uint64_t ne21 = dst->ne[1];
  6162. // const uint64_t ne22 = dst->ne[2];
  6163. // const uint64_t ne23 = dst->ne[3];
  6164. const uint64_t n_as = ne02;
  6165. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6166. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6167. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6168. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6169. vk_buffer d_Qx = nullptr;
  6170. size_t qx_buf_offset = 0;
  6171. vk_buffer d_Qy = nullptr;
  6172. size_t qy_buf_offset = 0;
  6173. vk_buffer d_ids = nullptr;
  6174. size_t ids_buf_offset = 0;
  6175. bool src0_uma = false;
  6176. bool src1_uma = false;
  6177. bool ids_uma = false;
  6178. if (ctx->device->uma) {
  6179. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6180. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6181. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6182. src0_uma = d_Qx != nullptr;
  6183. src1_uma = d_Qy != nullptr;
  6184. ids_uma = d_ids != nullptr;
  6185. }
  6186. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  6187. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  6188. !ggml_vk_dim01_contiguous(src0);
  6189. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  6190. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  6191. !ggml_vk_dim01_contiguous(src1);
  6192. // If src0 is BF16, try to use a BF16 x BF16 multiply
  6193. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  6194. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  6195. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  6196. // Check for mmq first
  6197. 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;
  6198. if (mmp == nullptr) {
  6199. // Fall back to f16 dequant mul mat
  6200. 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]);
  6201. quantize_y = false;
  6202. }
  6203. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  6204. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  6205. if (qx_needs_dequant) {
  6206. // Fall back to dequant + f16 mulmat
  6207. 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]);
  6208. }
  6209. // Not implemented
  6210. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6211. 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));
  6212. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && nei1 > 8;
  6213. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned, qx_needs_dequant ? f16_type : src0->type);
  6214. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  6215. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) :ne11;
  6216. const uint64_t x_ne = ggml_nelements(src0);
  6217. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  6218. const uint64_t d_ne = ggml_nelements(dst);
  6219. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  6220. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6221. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  6222. 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);
  6223. const uint64_t ids_sz = nbi2;
  6224. const uint64_t d_sz = sizeof(float) * d_ne;
  6225. vk_pipeline to_fp16_vk_0 = nullptr;
  6226. vk_pipeline to_fp16_vk_1 = nullptr;
  6227. vk_pipeline to_q8_1 = nullptr;
  6228. if (x_non_contig) {
  6229. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  6230. } else {
  6231. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  6232. }
  6233. if (y_non_contig) {
  6234. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  6235. } else {
  6236. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6237. }
  6238. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6239. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6240. if (quantize_y) {
  6241. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6242. }
  6243. {
  6244. if (
  6245. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6246. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6247. GGML_ABORT("Requested preallocation size is too large");
  6248. }
  6249. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6250. ctx->prealloc_size_x = x_sz;
  6251. ggml_vk_preallocate_buffers(ctx, subctx);
  6252. }
  6253. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6254. ctx->prealloc_size_y = y_sz;
  6255. ggml_vk_preallocate_buffers(ctx, subctx);
  6256. }
  6257. // Request descriptor sets
  6258. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6259. if (qx_needs_dequant) {
  6260. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6261. }
  6262. if (qy_needs_dequant) {
  6263. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6264. }
  6265. if (quantize_y) {
  6266. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6267. }
  6268. }
  6269. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6270. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6271. GGML_ASSERT(d_D != nullptr);
  6272. vk_buffer d_X;
  6273. uint64_t x_buf_offset = 0;
  6274. vk_buffer d_Y;
  6275. uint64_t y_buf_offset = 0;
  6276. if (!src0_uma) {
  6277. d_Qx = src0_buf_ctx->dev_buffer;
  6278. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6279. GGML_ASSERT(d_Qx != nullptr);
  6280. }
  6281. if (!src1_uma) {
  6282. d_Qy = src1_buf_ctx->dev_buffer;
  6283. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6284. GGML_ASSERT(d_Qy != nullptr);
  6285. }
  6286. if (!ids_uma) {
  6287. d_ids = ids_buf_ctx->dev_buffer;
  6288. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6289. GGML_ASSERT(d_ids != nullptr);
  6290. }
  6291. if (qx_needs_dequant) {
  6292. d_X = ctx->prealloc_x;
  6293. GGML_ASSERT(d_X->size >= x_sz);
  6294. } else {
  6295. d_X = d_Qx;
  6296. x_buf_offset = qx_buf_offset;
  6297. GGML_ASSERT(qx_sz == x_sz);
  6298. }
  6299. if (qy_needs_dequant) {
  6300. d_Y = ctx->prealloc_y;
  6301. GGML_ASSERT(d_Y->size >= y_sz);
  6302. } else if (quantize_y) {
  6303. d_Y = ctx->prealloc_y;
  6304. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  6305. } else {
  6306. d_Y = d_Qy;
  6307. y_buf_offset = qy_buf_offset;
  6308. GGML_ASSERT(qy_sz == y_sz);
  6309. }
  6310. if (x_non_contig || qx_needs_dequant) {
  6311. if (ctx->prealloc_x_need_sync) {
  6312. ggml_vk_sync_buffers(ctx, subctx);
  6313. }
  6314. }
  6315. if (x_non_contig) {
  6316. 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));
  6317. } else if (qx_needs_dequant) {
  6318. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6319. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  6320. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)x_ne, 1, 1});
  6321. ggml_vk_sync_buffers(ctx, subctx);
  6322. }
  6323. if (y_non_contig) {
  6324. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6325. ctx->prealloc_y_last_tensor_used != src1) {
  6326. if (ctx->prealloc_y_need_sync) {
  6327. ggml_vk_sync_buffers(ctx, subctx);
  6328. }
  6329. 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));
  6330. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6331. ctx->prealloc_y_last_tensor_used = src1;
  6332. }
  6333. }
  6334. if (quantize_y) {
  6335. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6336. ctx->prealloc_y_last_tensor_used != src1) {
  6337. if (ctx->prealloc_y_need_sync) {
  6338. ggml_vk_sync_buffers(ctx, subctx);
  6339. }
  6340. 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);
  6341. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6342. ctx->prealloc_y_last_tensor_used = src1;
  6343. }
  6344. }
  6345. uint32_t stride_batch_x = ne00*ne01;
  6346. uint32_t stride_batch_y = ne10*ne11;
  6347. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6348. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6349. }
  6350. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  6351. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6352. }
  6353. // compute
  6354. ggml_vk_matmul_id(
  6355. ctx, subctx, pipeline,
  6356. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  6357. { d_D, d_buf_offset, d_sz }, { d_ids, ids_buf_offset, ids_sz },
  6358. ne01, ne21, ne10, ne10, ne10, ne01,
  6359. stride_batch_x, stride_batch_y, ne20*ne21,
  6360. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, padded_n
  6361. ); // NOLINT
  6362. if (x_non_contig || qx_needs_dequant) {
  6363. ctx->prealloc_x_need_sync = true;
  6364. }
  6365. if (y_non_contig) {
  6366. ctx->prealloc_y_need_sync = true;
  6367. }
  6368. }
  6369. 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) {
  6370. ggml_tensor * dst = cgraph->nodes[node_idx];
  6371. ggml_tensor * src0 = dst->src[0];
  6372. ggml_tensor * src1 = dst->src[1];
  6373. ggml_tensor * ids = dst->src[2];
  6374. 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];
  6375. 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];
  6376. 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];
  6377. 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];
  6378. std::cerr << "))");
  6379. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6380. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6381. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6382. const uint64_t ne00 = src0->ne[0];
  6383. const uint64_t ne01 = src0->ne[1];
  6384. // const uint64_t ne02 = src0->ne[2];
  6385. // const uint64_t ne03 = src0->ne[3];
  6386. const uint64_t ne10 = src1->ne[0];
  6387. const uint64_t ne11 = src1->ne[1];
  6388. // const uint64_t ne12 = src1->ne[2];
  6389. // const uint64_t ne13 = src1->ne[3];
  6390. const uint64_t nei0 = ids->ne[0];
  6391. const uint64_t nei1 = ids->ne[1];
  6392. GGML_ASSERT(nei1 == 1);
  6393. const uint64_t ne20 = dst->ne[0];
  6394. const uint64_t ne21 = dst->ne[1];
  6395. // const uint64_t ne22 = dst->ne[2];
  6396. // const uint64_t ne23 = dst->ne[3];
  6397. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6398. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6399. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6400. const bool qx_needs_dequant = x_non_contig;
  6401. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  6402. // Not implemented
  6403. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6404. const uint64_t x_ne = ggml_nelements(src0);
  6405. const uint64_t y_ne = ggml_nelements(src1);
  6406. 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);
  6407. 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;
  6408. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  6409. vk_pipeline to_fp16_vk_0 = nullptr;
  6410. vk_pipeline to_fp16_vk_1 = nullptr;
  6411. if (x_non_contig) {
  6412. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6413. }
  6414. if (y_non_contig) {
  6415. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6416. } else {
  6417. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6418. }
  6419. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type);
  6420. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6421. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6422. GGML_ASSERT(dmmv != nullptr);
  6423. {
  6424. if (
  6425. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6426. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6427. GGML_ABORT("Requested preallocation size is too large");
  6428. }
  6429. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6430. ctx->prealloc_size_x = x_sz;
  6431. ggml_vk_preallocate_buffers(ctx, subctx);
  6432. }
  6433. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz) {
  6434. ctx->prealloc_size_y = y_sz;
  6435. ggml_vk_preallocate_buffers(ctx, subctx);
  6436. }
  6437. // Request descriptor sets
  6438. if (qx_needs_dequant) {
  6439. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6440. }
  6441. if (qy_needs_dequant) {
  6442. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6443. }
  6444. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6445. }
  6446. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6447. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6448. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  6449. vk_subbuffer d_ids = ggml_vk_tensor_subbuffer(ctx, ids);
  6450. vk_subbuffer d_F0 = d_D;
  6451. vk_subbuffer d_X, d_Y;
  6452. if (qx_needs_dequant) {
  6453. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  6454. } else {
  6455. d_X = d_Qx;
  6456. }
  6457. if (qy_needs_dequant) {
  6458. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  6459. } else {
  6460. d_Y = d_Qy;
  6461. }
  6462. if (x_non_contig) {
  6463. if (ctx->prealloc_x_need_sync) {
  6464. ggml_vk_sync_buffers(ctx, subctx);
  6465. }
  6466. }
  6467. if (x_non_contig) {
  6468. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6469. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  6470. }
  6471. if (y_non_contig) {
  6472. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6473. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6474. ctx->prealloc_y_last_tensor_used != src1) {
  6475. if (ctx->prealloc_y_need_sync) {
  6476. ggml_vk_sync_buffers(ctx, subctx);
  6477. }
  6478. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  6479. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6480. ctx->prealloc_y_last_tensor_used = src1;
  6481. }
  6482. }
  6483. uint32_t stride_batch_y = ne10*ne11;
  6484. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6485. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6486. }
  6487. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6488. uint32_t groups_x = ne01;
  6489. uint32_t groups_z = 1;
  6490. if (ne01 > max_groups_x) {
  6491. groups_z = 64;
  6492. groups_x = CEIL_DIV(groups_x, groups_z);
  6493. }
  6494. uint32_t fusion_flags = 0;
  6495. if (ctx->num_additional_fused_ops > 0) {
  6496. const ggml_tensor * bias = cgraph->nodes[node_idx + 1]->src[1];
  6497. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6498. if (cgraph->nodes[node_idx + 1]->op == GGML_OP_MUL) {
  6499. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE0;
  6500. } else {
  6501. GGML_ASSERT(cgraph->nodes[node_idx + 1]->op == GGML_OP_ADD_ID);
  6502. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6503. }
  6504. }
  6505. vk_subbuffer d_F1 = d_D;
  6506. if (ctx->num_additional_fused_ops > 1) {
  6507. const ggml_tensor * scale = cgraph->nodes[node_idx + 2]->src[1];
  6508. d_F1 = ggml_vk_tensor_subbuffer(ctx, scale);
  6509. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE1;
  6510. }
  6511. // compute
  6512. const vk_mat_vec_id_push_constants pc = {
  6513. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6514. (uint32_t)(ne00 * ne01), stride_batch_y, (uint32_t)(ne20 * ne21),
  6515. fusion_flags,
  6516. (uint32_t)nei0, (uint32_t)ne11,
  6517. };
  6518. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6519. {
  6520. d_X,
  6521. d_Y,
  6522. d_D,
  6523. d_F0,
  6524. d_F1,
  6525. d_ids,
  6526. },
  6527. pc, { groups_x, (uint32_t)nei0, groups_z });
  6528. if (x_non_contig) {
  6529. ctx->prealloc_x_need_sync = true;
  6530. }
  6531. if (y_non_contig) {
  6532. ctx->prealloc_y_need_sync = true;
  6533. }
  6534. }
  6535. static bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx) {
  6536. ggml_tensor * dst = cgraph->nodes[node_idx];
  6537. ggml_tensor * src0 = dst->src[0];
  6538. ggml_tensor * src2 = dst->src[2];
  6539. return src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type));
  6540. }
  6541. static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6542. ggml_tensor * dst = cgraph->nodes[node_idx];
  6543. ggml_tensor * src0 = dst->src[0];
  6544. ggml_tensor * src1 = dst->src[1];
  6545. ggml_tensor * src2 = dst->src[2];
  6546. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  6547. if (ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  6548. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, cgraph, node_idx);
  6549. } else {
  6550. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst);
  6551. }
  6552. }
  6553. static bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv) {
  6554. // Needs to be kept up to date on shader changes
  6555. GGML_UNUSED(hsv);
  6556. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6557. const uint32_t Br = get_fa_scalar_num_large_rows(hsv);
  6558. const uint32_t Bc = scalar_flash_attention_Bc;
  6559. const uint32_t tmpsh = wg_size * sizeof(float);
  6560. const uint32_t tmpshv4 = wg_size * 4 * sizeof(float);
  6561. const uint32_t masksh = Bc * Br * sizeof(float);
  6562. const uint32_t Qf = Br * (hsk / 4 + 2) * 4 * sizeof(float);
  6563. const uint32_t total_size = tmpsh + tmpshv4 + masksh + Qf;
  6564. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6565. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported);
  6566. return supported;
  6567. }
  6568. static bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool f32acc) {
  6569. // Needs to be kept up to date on shader changes
  6570. GGML_UNUSED(hsv);
  6571. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6572. const uint32_t Br = coopmat1_flash_attention_num_large_rows;
  6573. const uint32_t Bc = scalar_flash_attention_Bc;
  6574. const uint32_t hsk_pad = ROUNDUP_POW2(hsk, 16);
  6575. const uint32_t acctype = f32acc ? 4 : 2;
  6576. const uint32_t f16vec4 = 8;
  6577. const uint32_t tmpsh = wg_size * sizeof(float);
  6578. const uint32_t tmpshv4 = wg_size * 4 * acctype;
  6579. const uint32_t qstride = hsk_pad / 4 + 2;
  6580. const uint32_t Qf = Br * qstride * f16vec4;
  6581. const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br;
  6582. const uint32_t sfsh = Bc * sfshstride * acctype;
  6583. const uint32_t kshstride = hsk_pad / 4 + 2;
  6584. const uint32_t ksh = Bc * kshstride * f16vec4;
  6585. const uint32_t slope = Br * sizeof(float);
  6586. const uint32_t total_size = tmpsh + tmpshv4 + Qf + sfsh + ksh + slope;
  6587. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6588. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported);
  6589. return supported;
  6590. }
  6591. 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) {
  6592. 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];
  6593. 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];
  6594. 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];
  6595. 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];
  6596. if (sinks) {
  6597. 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];
  6598. }
  6599. std::cerr << "))");
  6600. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  6601. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  6602. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  6603. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  6604. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  6605. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  6606. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  6607. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  6608. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  6609. const uint32_t nem2 = mask ? mask->ne[2] : 0;
  6610. const uint32_t nem3 = mask ? mask->ne[3] : 0;
  6611. const uint32_t HSK = nek0;
  6612. const uint32_t HSV = nev0;
  6613. uint32_t N = neq1;
  6614. const uint32_t KV = nek1;
  6615. GGML_ASSERT(ne0 == HSV);
  6616. GGML_ASSERT(ne2 == N);
  6617. // input tensor rows must be contiguous
  6618. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  6619. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  6620. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  6621. GGML_ASSERT(neq0 == HSK);
  6622. GGML_ASSERT(neq1 == N);
  6623. GGML_ASSERT(nev1 == nek1);
  6624. // dst cannot be transposed or permuted
  6625. GGML_ASSERT(nb0 == sizeof(float));
  6626. GGML_ASSERT(nb0 <= nb1);
  6627. GGML_ASSERT(nb1 <= nb2);
  6628. GGML_ASSERT(nb2 <= nb3);
  6629. assert(dst->type == GGML_TYPE_F32);
  6630. assert(q->type == GGML_TYPE_F32);
  6631. assert(k->type == v->type);
  6632. FaCodePath path = ctx->device->coopmat2 ? FA_COOPMAT2 :
  6633. ctx->device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;
  6634. if (path == FA_COOPMAT1) {
  6635. const bool coopmat_shape_supported = (dst->op_params[3] == GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f32acc) ||
  6636. (dst->op_params[3] != GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f16acc);
  6637. const bool coopmat_shmem_supported = ggml_vk_flash_attn_coopmat_shmem_support(ctx->device, HSK, HSV, dst->op_params[3] == GGML_PREC_F32);
  6638. if (!coopmat_shape_supported || !coopmat_shmem_supported) {
  6639. path = FA_SCALAR;
  6640. }
  6641. }
  6642. uint32_t gqa_ratio = 1;
  6643. uint32_t qk_ratio = neq2 / nek2;
  6644. uint32_t workgroups_x = (uint32_t)neq1;
  6645. uint32_t workgroups_y = (uint32_t)neq2;
  6646. uint32_t workgroups_z = (uint32_t)neq3;
  6647. // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga.
  6648. // For coopmat2 FA, we always use the small size (which is still pretty large for gqa).
  6649. uint32_t max_gqa;
  6650. switch (path) {
  6651. case FA_SCALAR:
  6652. case FA_COOPMAT1:
  6653. // We may switch from coopmat1 to scalar, so use the scalar limit for both
  6654. max_gqa = get_fa_scalar_num_large_rows(HSV);
  6655. break;
  6656. case FA_COOPMAT2:
  6657. max_gqa = get_fa_num_small_rows(FA_COOPMAT2);
  6658. break;
  6659. default:
  6660. GGML_ASSERT(0);
  6661. }
  6662. if (N == 1 && qk_ratio > 1 && qk_ratio <= max_gqa &&
  6663. qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) {
  6664. // grouped query attention - make the N dimension equal to gqa_ratio, reduce
  6665. // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1
  6666. // and change addressing calculations to index Q's dimension 2.
  6667. gqa_ratio = qk_ratio;
  6668. N = gqa_ratio;
  6669. workgroups_y /= N;
  6670. }
  6671. bool small_rows = N <= get_fa_num_small_rows(path);
  6672. // coopmat1 does not actually support "small rows" (it needs 16 rows).
  6673. // So use scalar instead.
  6674. if (small_rows && path == FA_COOPMAT1) {
  6675. path = FA_SCALAR;
  6676. }
  6677. // scalar is faster than coopmat2 when N==1
  6678. if (N == 1 && path == FA_COOPMAT2) {
  6679. path = FA_SCALAR;
  6680. }
  6681. // with large hsk/hsv, scalar path may need to use small_rows to fit in shared memory
  6682. if (path == FA_SCALAR &&
  6683. !ggml_vk_flash_attn_scalar_shmem_support(ctx->device, HSK, HSV)) {
  6684. small_rows = true;
  6685. }
  6686. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  6687. uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  6688. uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  6689. // For F32, the shader treats it as a block of size 4 (for vec4 loads)
  6690. if (k->type == GGML_TYPE_F32) {
  6691. k_stride /= 4;
  6692. }
  6693. if (v->type == GGML_TYPE_F32) {
  6694. v_stride /= 4;
  6695. }
  6696. uint32_t alignment = fa_align(path, HSK, HSV, k->type, small_rows);
  6697. bool aligned = (KV % alignment) == 0 &&
  6698. // the "aligned" shader variant will forcibly align strides, for performance
  6699. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  6700. // Need to use the coopmat2 variant that clamps loads when HSK/HSV aren't sufficiently aligned.
  6701. if (((HSK | HSV) % 16) != 0 && path == FA_COOPMAT2) {
  6702. aligned = false;
  6703. }
  6704. bool f32acc = path == FA_SCALAR || dst->op_params[3] == GGML_PREC_F32;
  6705. vk_fa_pipeline_state fa_pipeline_state(HSK, HSV, small_rows, path, aligned, f32acc);
  6706. vk_pipeline pipeline = nullptr;
  6707. {
  6708. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  6709. auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16[k->type];
  6710. auto it = pipelines.find(fa_pipeline_state);
  6711. if (it != pipelines.end()) {
  6712. pipeline = it->second;
  6713. } else {
  6714. pipelines[fa_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  6715. }
  6716. }
  6717. assert(pipeline);
  6718. uint32_t split_kv = KV;
  6719. uint32_t split_k = 1;
  6720. // Use a placeholder core count if one isn't available. split_k is a big help for perf.
  6721. const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count : 16;
  6722. // Try to use split_k when KV is large enough to be worth the overhead
  6723. if (workgroups_x == 1 && shader_core_count > 0) {
  6724. // Try to run two workgroups per SM.
  6725. split_k = shader_core_count * 2 / (workgroups_y * workgroups_z);
  6726. if (split_k > 1) {
  6727. // Try to evenly split KV into split_k chunks, but it needs to be a multiple
  6728. // of "align", so recompute split_k based on that.
  6729. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment);
  6730. split_k = CEIL_DIV(KV, split_kv);
  6731. workgroups_x = split_k;
  6732. }
  6733. }
  6734. // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1)
  6735. // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows.
  6736. const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne3 : 0;
  6737. if (split_k_size > ctx->device->properties.limits.maxStorageBufferRange) {
  6738. GGML_ABORT("Requested preallocation size is too large");
  6739. }
  6740. if (ctx->prealloc_size_split_k < split_k_size) {
  6741. ctx->prealloc_size_split_k = split_k_size;
  6742. ggml_vk_preallocate_buffers(ctx, subctx);
  6743. }
  6744. {
  6745. // Request descriptor sets
  6746. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6747. if (split_k > 1) {
  6748. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1);
  6749. }
  6750. }
  6751. float scale = 1.0f;
  6752. float max_bias = 0.0f;
  6753. float logit_softcap = 0.0f;
  6754. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  6755. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  6756. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  6757. if (logit_softcap != 0) {
  6758. scale /= logit_softcap;
  6759. }
  6760. const uint32_t n_head_kv = neq2;
  6761. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  6762. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  6763. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  6764. vk_subbuffer q_buf = ggml_vk_tensor_subbuffer(ctx, q);
  6765. vk_subbuffer k_buf = ggml_vk_tensor_subbuffer(ctx, k);
  6766. vk_subbuffer v_buf = ggml_vk_tensor_subbuffer(ctx, v);
  6767. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  6768. vk_subbuffer mask_buf = mask ? ggml_vk_tensor_subbuffer(ctx, mask) : q_buf;
  6769. vk_subbuffer sinks_buf = sinks ? ggml_vk_tensor_subbuffer(ctx, sinks) : q_buf;
  6770. uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | ((mask != nullptr) << 16) | n_head_log2;
  6771. const vk_flash_attn_push_constants pc = { N, KV,
  6772. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  6773. (uint32_t)neq2, (uint32_t)neq3,
  6774. (uint32_t)nek2, (uint32_t)nek3,
  6775. (uint32_t)nev2, (uint32_t)nev3,
  6776. nem1, nem2, nem3,
  6777. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  6778. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  6779. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  6780. scale, max_bias, logit_softcap,
  6781. mask_n_head_log2, m0, m1,
  6782. gqa_ratio, split_kv, split_k };
  6783. if (split_k > 1) {
  6784. if (ctx->prealloc_split_k_need_sync) {
  6785. ggml_vk_sync_buffers(ctx, subctx);
  6786. }
  6787. vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  6788. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6789. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf},
  6790. // We only use split_k when group query attention is enabled, which means
  6791. // there's no more than one tile of rows (i.e. workgroups_x would have been
  6792. // one). We reuse workgroups_x to mean the number of splits, so we need to
  6793. // cancel out the divide by wg_denoms[0].
  6794. pc, { workgroups_x * pipeline->wg_denoms[0], workgroups_y, workgroups_z });
  6795. ggml_vk_sync_buffers(ctx, subctx);
  6796. const std::array<uint32_t, 5> pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne3, split_k, (sinks != nullptr) };
  6797. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce,
  6798. {split_k_buf, sinks_buf, dst_buf},
  6799. pc2, { (uint32_t)ne1, HSV, (uint32_t)ne3 });
  6800. ctx->prealloc_split_k_need_sync = true;
  6801. } else {
  6802. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6803. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf},
  6804. pc, { workgroups_x, workgroups_y, workgroups_z });
  6805. }
  6806. }
  6807. static std::array<uint32_t, 3> ggml_vk_get_conv_elements(const ggml_tensor *dst) {
  6808. const ggml_tensor *src0 = dst->src[0];
  6809. const ggml_tensor *src1 = dst->src[1];
  6810. // src0 - kernel: [KW, KH, Cin, Cout]
  6811. // src1 - input: [W, H, Cin, N]
  6812. // dst - result: [OW, OH, Cout, N]
  6813. // Copied from ggml.c: int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d)
  6814. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6815. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  6816. };
  6817. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6818. int64_t W = src1->ne[0];
  6819. int64_t H = src1->ne[1];
  6820. int64_t KW = src0->ne[0];
  6821. int64_t KH = src0->ne[1];
  6822. int64_t Cout = src0->ne[3];
  6823. int64_t N = src1->ne[3];
  6824. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[1], dst->op_params[3], dst->op_params[5]);
  6825. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], dst->op_params[2], dst->op_params[4]);
  6826. int64_t NPQ = N * OW * OH;
  6827. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6828. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6829. return elements;
  6830. }
  6831. static std::array<uint32_t, 3> ggml_vk_get_conv_transpose_2d_elements(const ggml_tensor *dst) {
  6832. const ggml_tensor *src0 = dst->src[0];
  6833. const ggml_tensor *src1 = dst->src[1];
  6834. // src0 - kernel: [KW, KH, Cout, Cin]
  6835. // src1 - input: [W, H, Cin, N]
  6836. // dst - result: [OW, OH, Cout, N]
  6837. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6838. return (ins - 1) * s - 2 * p + (ks - 1) * d + 1;
  6839. };
  6840. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6841. int64_t W = src1->ne[0];
  6842. int64_t H = src1->ne[1];
  6843. int64_t KW = src0->ne[0];
  6844. int64_t KH = src0->ne[1];
  6845. int64_t Cout = src0->ne[2];
  6846. int64_t N = src1->ne[3];
  6847. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[0], 0, 1);
  6848. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], 0, 1);
  6849. int64_t NPQ = N * OW * OH;
  6850. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6851. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6852. return elements;
  6853. }
  6854. 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) {
  6855. switch (op) {
  6856. case GGML_OP_GET_ROWS:
  6857. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  6858. if (dst->type == GGML_TYPE_F16) {
  6859. return ctx->device->pipeline_get_rows[src0->type];
  6860. }
  6861. if (dst->type == GGML_TYPE_F32) {
  6862. return ctx->device->pipeline_get_rows_f32[src0->type];
  6863. }
  6864. return nullptr;
  6865. case GGML_OP_ACC:
  6866. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6867. return ctx->device->pipeline_acc_f32;
  6868. }
  6869. return nullptr;
  6870. case GGML_OP_ADD:
  6871. case GGML_OP_SUB:
  6872. case GGML_OP_MUL:
  6873. case GGML_OP_DIV:
  6874. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  6875. (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
  6876. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
  6877. return nullptr;
  6878. }
  6879. switch (op) {
  6880. case GGML_OP_ADD:
  6881. {
  6882. if (ctx->num_additional_fused_ops > 0) {
  6883. if (ctx->do_add_rms_partials) {
  6884. return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops];
  6885. } else {
  6886. return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  6887. }
  6888. }
  6889. if (ctx->do_add_rms_partials) {
  6890. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_rms_norepeat : ctx->device->pipeline_add_rms;
  6891. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6892. } else {
  6893. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add;
  6894. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6895. }
  6896. }
  6897. case GGML_OP_SUB:
  6898. {
  6899. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub;
  6900. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6901. }
  6902. case GGML_OP_MUL:
  6903. {
  6904. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul;
  6905. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6906. }
  6907. case GGML_OP_DIV:
  6908. {
  6909. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div;
  6910. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6911. }
  6912. default:
  6913. break;
  6914. }
  6915. return nullptr;
  6916. case GGML_OP_ADD_ID:
  6917. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) {
  6918. return ctx->device->pipeline_add_id_f32;
  6919. }
  6920. return nullptr;
  6921. case GGML_OP_CONCAT:
  6922. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6923. return ctx->device->pipeline_concat_f32;
  6924. }
  6925. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6926. return ctx->device->pipeline_concat_f16;
  6927. }
  6928. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  6929. return ctx->device->pipeline_concat_i32;
  6930. }
  6931. return nullptr;
  6932. case GGML_OP_UPSCALE:
  6933. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6934. ggml_scale_mode mode = (ggml_scale_mode)(ggml_get_op_params_i32(dst, 0) & 0xFF);
  6935. switch (mode) {
  6936. case GGML_SCALE_MODE_NEAREST:
  6937. return ctx->device->pipeline_upscale_nearest_f32;
  6938. case GGML_SCALE_MODE_BILINEAR:
  6939. return ctx->device->pipeline_upscale_bilinear_f32;
  6940. case GGML_SCALE_MODE_BICUBIC:
  6941. return ctx->device->pipeline_upscale_bicubic_f32;
  6942. default:
  6943. return nullptr;
  6944. }
  6945. }
  6946. return nullptr;
  6947. case GGML_OP_SCALE:
  6948. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6949. return ctx->device->pipeline_scale_f32;
  6950. }
  6951. return nullptr;
  6952. case GGML_OP_SQR:
  6953. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6954. return ctx->device->pipeline_sqr_f32;
  6955. }
  6956. return nullptr;
  6957. case GGML_OP_SQRT:
  6958. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6959. return ctx->device->pipeline_sqrt_f32;
  6960. }
  6961. return nullptr;
  6962. case GGML_OP_SIN:
  6963. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6964. return ctx->device->pipeline_sin_f32;
  6965. }
  6966. return nullptr;
  6967. case GGML_OP_COS:
  6968. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6969. return ctx->device->pipeline_cos_f32;
  6970. }
  6971. return nullptr;
  6972. case GGML_OP_LOG:
  6973. if (src0->type == dst->type &&
  6974. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  6975. return ctx->device->pipeline_log[dst->type == GGML_TYPE_F16];
  6976. }
  6977. return nullptr;
  6978. case GGML_OP_CLAMP:
  6979. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6980. return ctx->device->pipeline_clamp_f32;
  6981. }
  6982. return nullptr;
  6983. case GGML_OP_PAD:
  6984. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6985. return ctx->device->pipeline_pad_f32;
  6986. }
  6987. return nullptr;
  6988. case GGML_OP_ROLL:
  6989. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6990. return ctx->device->pipeline_roll_f32;
  6991. }
  6992. return nullptr;
  6993. case GGML_OP_REPEAT:
  6994. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  6995. return ctx->device->pipeline_repeat_f32;
  6996. }
  6997. return nullptr;
  6998. case GGML_OP_REPEAT_BACK:
  6999. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7000. return ctx->device->pipeline_repeat_back_f32;
  7001. }
  7002. return nullptr;
  7003. case GGML_OP_CPY:
  7004. case GGML_OP_CONT:
  7005. case GGML_OP_DUP:
  7006. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  7007. case GGML_OP_SET_ROWS:
  7008. if (src1->type == GGML_TYPE_I64) {
  7009. return ctx->device->pipeline_set_rows_i64[dst->type];
  7010. } else {
  7011. return ctx->device->pipeline_set_rows_i32[dst->type];
  7012. }
  7013. case GGML_OP_SILU_BACK:
  7014. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7015. return ctx->device->pipeline_silu_back_f32;
  7016. }
  7017. return nullptr;
  7018. case GGML_OP_NORM:
  7019. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7020. return ctx->device->pipeline_norm_f32;
  7021. }
  7022. return nullptr;
  7023. case GGML_OP_GROUP_NORM:
  7024. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7025. return ctx->device->pipeline_group_norm_f32;
  7026. }
  7027. return nullptr;
  7028. case GGML_OP_RMS_NORM:
  7029. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7030. if (ctx->do_add_rms_partials) {
  7031. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32;
  7032. } else {
  7033. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32;
  7034. }
  7035. }
  7036. return nullptr;
  7037. case GGML_OP_RMS_NORM_BACK:
  7038. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7039. return ctx->device->pipeline_rms_norm_back_f32;
  7040. }
  7041. return nullptr;
  7042. case GGML_OP_L2_NORM:
  7043. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7044. return ctx->device->pipeline_l2_norm_f32;
  7045. }
  7046. return nullptr;
  7047. case GGML_OP_UNARY:
  7048. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7049. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7050. (src0->type != dst->type)) {
  7051. return nullptr;
  7052. }
  7053. switch (ggml_get_unary_op(dst)) {
  7054. case GGML_UNARY_OP_EXP:
  7055. return ctx->device->pipeline_exp[dst->type == GGML_TYPE_F16];
  7056. case GGML_UNARY_OP_SILU:
  7057. return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16];
  7058. case GGML_UNARY_OP_GELU:
  7059. return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16];
  7060. case GGML_UNARY_OP_GELU_ERF:
  7061. return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16];
  7062. case GGML_UNARY_OP_GELU_QUICK:
  7063. return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16];
  7064. case GGML_UNARY_OP_RELU:
  7065. return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16];
  7066. case GGML_UNARY_OP_NEG:
  7067. return ctx->device->pipeline_neg[dst->type == GGML_TYPE_F16];
  7068. case GGML_UNARY_OP_TANH:
  7069. return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16];
  7070. case GGML_UNARY_OP_SIGMOID:
  7071. return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16];
  7072. case GGML_UNARY_OP_HARDSIGMOID:
  7073. return ctx->device->pipeline_hardsigmoid[dst->type == GGML_TYPE_F16];
  7074. case GGML_UNARY_OP_HARDSWISH:
  7075. return ctx->device->pipeline_hardswish[dst->type == GGML_TYPE_F16];
  7076. case GGML_UNARY_OP_ABS:
  7077. return ctx->device->pipeline_abs[dst->type == GGML_TYPE_F16];
  7078. default:
  7079. break;
  7080. }
  7081. return nullptr;
  7082. case GGML_OP_GLU:
  7083. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7084. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7085. (src0->type != dst->type)) {
  7086. return nullptr;
  7087. }
  7088. switch (ggml_get_glu_op(dst)) {
  7089. case GGML_GLU_OP_GEGLU:
  7090. return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16];
  7091. case GGML_GLU_OP_REGLU:
  7092. return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16];
  7093. case GGML_GLU_OP_SWIGLU:
  7094. return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16];
  7095. case GGML_GLU_OP_SWIGLU_OAI:
  7096. return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16];
  7097. case GGML_GLU_OP_GEGLU_ERF:
  7098. return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16];
  7099. case GGML_GLU_OP_GEGLU_QUICK:
  7100. return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16];
  7101. default:
  7102. break;
  7103. }
  7104. return nullptr;
  7105. case GGML_OP_DIAG_MASK_INF:
  7106. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7107. return ctx->device->pipeline_diag_mask_inf_f32;
  7108. }
  7109. return nullptr;
  7110. case GGML_OP_SOFT_MAX:
  7111. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  7112. GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32);
  7113. if (ctx->num_additional_fused_ops) {
  7114. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7115. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7116. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  7117. return ctx->device->pipeline_topk_moe[idx][mode];
  7118. }
  7119. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  7120. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  7121. }
  7122. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7123. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  7124. }
  7125. return nullptr;
  7126. case GGML_OP_SOFT_MAX_BACK:
  7127. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7128. return ctx->device->pipeline_soft_max_back_f32;
  7129. }
  7130. return nullptr;
  7131. case GGML_OP_ROPE:
  7132. case GGML_OP_ROPE_BACK:
  7133. {
  7134. const ggml_tensor *rope = ctx->num_additional_fused_ops == 2 ? dst->src[0]->src[0] : dst;
  7135. const int mode = ((const int32_t *) rope->op_params)[2];
  7136. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  7137. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  7138. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  7139. if (is_neox) {
  7140. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7141. return ctx->device->pipeline_rope_neox_f32;
  7142. }
  7143. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7144. return ctx->device->pipeline_rope_neox_f32_f16;
  7145. }
  7146. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7147. return ctx->device->pipeline_rope_neox_f16;
  7148. }
  7149. } else if (is_mrope && !is_vision) {
  7150. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7151. return ctx->device->pipeline_rope_multi_f32;
  7152. }
  7153. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7154. return ctx->device->pipeline_rope_multi_f16;
  7155. }
  7156. } else if (is_vision) {
  7157. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7158. return ctx->device->pipeline_rope_vision_f32;
  7159. }
  7160. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7161. return ctx->device->pipeline_rope_vision_f16;
  7162. }
  7163. } else {
  7164. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7165. return ctx->device->pipeline_rope_norm_f32;
  7166. }
  7167. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7168. return ctx->device->pipeline_rope_norm_f32_f16;
  7169. }
  7170. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7171. return ctx->device->pipeline_rope_norm_f16;
  7172. }
  7173. }
  7174. return nullptr;
  7175. }
  7176. case GGML_OP_ARGSORT:
  7177. if (ctx->num_additional_fused_ops) {
  7178. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7179. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7180. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  7181. return ctx->device->pipeline_topk_moe[idx][mode];
  7182. }
  7183. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7184. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7185. return ctx->device->pipeline_argsort_f32[idx];
  7186. }
  7187. return nullptr;
  7188. case GGML_OP_SUM:
  7189. case GGML_OP_SUM_ROWS:
  7190. case GGML_OP_MEAN:
  7191. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7192. return ctx->device->pipeline_sum_rows_f32;
  7193. }
  7194. return nullptr;
  7195. case GGML_OP_ARGMAX:
  7196. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7197. return ctx->device->pipeline_argmax_f32;
  7198. }
  7199. return nullptr;
  7200. case GGML_OP_COUNT_EQUAL:
  7201. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) {
  7202. return ctx->device->pipeline_count_equal_i32;
  7203. }
  7204. return nullptr;
  7205. case GGML_OP_IM2COL:
  7206. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7207. return ctx->device->pipeline_im2col_f32;
  7208. }
  7209. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7210. return ctx->device->pipeline_im2col_f32_f16;
  7211. }
  7212. return nullptr;
  7213. case GGML_OP_IM2COL_3D:
  7214. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7215. return ctx->device->pipeline_im2col_3d_f32;
  7216. }
  7217. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7218. return ctx->device->pipeline_im2col_3d_f32_f16;
  7219. }
  7220. return nullptr;
  7221. case GGML_OP_TIMESTEP_EMBEDDING:
  7222. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7223. return ctx->device->pipeline_timestep_embedding_f32;
  7224. }
  7225. return nullptr;
  7226. case GGML_OP_CONV_TRANSPOSE_1D:
  7227. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7228. return ctx->device->pipeline_conv_transpose_1d_f32;
  7229. }
  7230. return nullptr;
  7231. case GGML_OP_POOL_2D:
  7232. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7233. return ctx->device->pipeline_pool2d_f32;
  7234. }
  7235. return nullptr;
  7236. case GGML_OP_RWKV_WKV6:
  7237. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7238. return ctx->device->pipeline_rwkv_wkv6_f32;
  7239. }
  7240. return nullptr;
  7241. case GGML_OP_RWKV_WKV7:
  7242. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7243. return ctx->device->pipeline_rwkv_wkv7_f32;
  7244. }
  7245. return nullptr;
  7246. case GGML_OP_SSM_SCAN:
  7247. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7248. const uint32_t d_state = src0->ne[0];
  7249. if (d_state == 128) {
  7250. return ctx->device->pipeline_ssm_scan_f32_d128;
  7251. } else if (d_state == 256) {
  7252. return ctx->device->pipeline_ssm_scan_f32_d256;
  7253. }
  7254. }
  7255. return nullptr;
  7256. case GGML_OP_SSM_CONV:
  7257. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7258. return ctx->device->pipeline_ssm_conv_f32;
  7259. }
  7260. return nullptr;
  7261. case GGML_OP_OPT_STEP_ADAMW:
  7262. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7263. return ctx->device->pipeline_opt_step_adamw_f32;
  7264. }
  7265. return nullptr;
  7266. case GGML_OP_OPT_STEP_SGD:
  7267. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7268. return ctx->device->pipeline_opt_step_sgd_f32;
  7269. }
  7270. return nullptr;
  7271. case GGML_OP_LEAKY_RELU:
  7272. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7273. return ctx->device->pipeline_leaky_relu_f32;
  7274. }
  7275. return nullptr;
  7276. case GGML_OP_CONV_2D:
  7277. case GGML_OP_CONV_TRANSPOSE_2D:
  7278. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 &&
  7279. ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst)) {
  7280. std::array<uint32_t, 3> elements;
  7281. if (op == GGML_OP_CONV_2D) elements = ggml_vk_get_conv_elements(dst);
  7282. else if (op == GGML_OP_CONV_TRANSPOSE_2D) elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  7283. vk_conv_shapes shape;
  7284. uint32_t tiles[CONV_SHAPE_COUNT];
  7285. for (uint32_t i = 0; i < CONV_SHAPE_COUNT; ++i) {
  7286. tiles[i] = CEIL_DIV(elements[0], conv_shapes_wg_denoms[i][0]) * CEIL_DIV(elements[1], conv_shapes_wg_denoms[i][1]);
  7287. }
  7288. // We can't query number of shader cores on Intel, use 32 as a placeholder
  7289. // so small convolutions will still choose a smaller tile.
  7290. const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32;
  7291. if (elements[0] > 64 && tiles[CONV_SHAPE_128x128] >= shader_core_count * 2) {
  7292. shape = CONV_SHAPE_128x128;
  7293. } else if (elements[0] <= 32 && tiles[CONV_SHAPE_32x256] >= shader_core_count * 2) {
  7294. shape = CONV_SHAPE_32x256;
  7295. } else {
  7296. shape = CONV_SHAPE_64x32;
  7297. }
  7298. uint32_t KW = static_cast<uint32_t>(src0->ne[0]);
  7299. uint32_t KH = static_cast<uint32_t>(src0->ne[1]);
  7300. uint32_t s0 = static_cast<uint32_t>(dst->op_params[0]);
  7301. uint32_t s1 = op == GGML_OP_CONV_2D ? static_cast<uint32_t>(dst->op_params[1]) : static_cast<uint32_t>(dst->op_params[0]);
  7302. uint32_t p0 = op == GGML_OP_CONV_2D ? static_cast<uint32_t>(dst->op_params[2]) : 0;
  7303. uint32_t p1 = op == GGML_OP_CONV_2D ? static_cast<uint32_t>(dst->op_params[3]) : 0;
  7304. uint32_t d0 = op == GGML_OP_CONV_2D ? static_cast<uint32_t>(dst->op_params[4]) : 1;
  7305. uint32_t d1 = op == GGML_OP_CONV_2D ? static_cast<uint32_t>(dst->op_params[5]) : 1;
  7306. vk_conv2d_pipeline_state conv2d_pipeline_state(s0, s1, p0, p1, d0, d1, KW, KH);
  7307. std::map<vk_conv2d_pipeline_state, vk_pipeline> *pipelines = nullptr;
  7308. if (op == GGML_OP_CONV_2D) {
  7309. if (src0->type == GGML_TYPE_F32) {
  7310. pipelines = &ctx->device->pipeline_conv2d_f32[shape];
  7311. } else if (src0->type == GGML_TYPE_F16) {
  7312. pipelines = &ctx->device->pipeline_conv2d_f16_f32[shape];
  7313. }
  7314. } else if (op == GGML_OP_CONV_TRANSPOSE_2D) {
  7315. if (src0->type == GGML_TYPE_F32) {
  7316. pipelines = &ctx->device->pipeline_conv_transpose_2d_f32[shape];
  7317. } else if (src0->type == GGML_TYPE_F16) {
  7318. pipelines = &ctx->device->pipeline_conv_transpose_2d_f16_f32[shape];
  7319. }
  7320. }
  7321. vk_pipeline pipeline = nullptr;
  7322. {
  7323. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7324. auto it = pipelines->find(conv2d_pipeline_state);
  7325. if (it != pipelines->end()) {
  7326. pipeline = it->second;
  7327. } else {
  7328. (*pipelines)[conv2d_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7329. }
  7330. }
  7331. return pipeline;
  7332. }
  7333. return nullptr;
  7334. case GGML_OP_CONV_2D_DW:
  7335. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7336. if (ggml_is_contiguous(src1)) {
  7337. return ctx->device->pipeline_conv2d_dw_whcn_f32;
  7338. } else if (ggml_is_contiguous_channels(src1)) {
  7339. return ctx->device->pipeline_conv2d_dw_cwhn_f32;
  7340. }
  7341. } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7342. if (ggml_is_contiguous(src1)) {
  7343. return ctx->device->pipeline_conv2d_dw_whcn_f16_f32;
  7344. } else if (ggml_is_contiguous_channels(src1)) {
  7345. return ctx->device->pipeline_conv2d_dw_cwhn_f16_f32;
  7346. }
  7347. }
  7348. return nullptr;
  7349. default:
  7350. return nullptr;
  7351. }
  7352. GGML_UNUSED(src2);
  7353. }
  7354. static bool ggml_vk_op_supports_incontiguous(ggml_op op) {
  7355. switch (op) {
  7356. case GGML_OP_CPY:
  7357. case GGML_OP_GET_ROWS:
  7358. case GGML_OP_ADD:
  7359. case GGML_OP_SUB:
  7360. case GGML_OP_MUL:
  7361. case GGML_OP_DIV:
  7362. case GGML_OP_ADD_ID:
  7363. case GGML_OP_CONCAT:
  7364. case GGML_OP_UPSCALE:
  7365. case GGML_OP_SQR:
  7366. case GGML_OP_SQRT:
  7367. case GGML_OP_SIN:
  7368. case GGML_OP_COS:
  7369. case GGML_OP_LOG:
  7370. case GGML_OP_CLAMP:
  7371. case GGML_OP_PAD:
  7372. case GGML_OP_REPEAT:
  7373. case GGML_OP_REPEAT_BACK:
  7374. case GGML_OP_ROPE:
  7375. case GGML_OP_RMS_NORM:
  7376. case GGML_OP_CONV_2D_DW:
  7377. case GGML_OP_IM2COL:
  7378. case GGML_OP_IM2COL_3D:
  7379. case GGML_OP_SET_ROWS:
  7380. case GGML_OP_SUM:
  7381. case GGML_OP_SUM_ROWS:
  7382. case GGML_OP_MEAN:
  7383. return true;
  7384. default:
  7385. return false;
  7386. }
  7387. }
  7388. 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) {
  7389. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7390. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7391. p.misalign_offsets = (a_offset << 16) | d_offset;
  7392. GGML_UNUSED(src1);
  7393. GGML_UNUSED(src2);
  7394. GGML_UNUSED(src3);
  7395. }
  7396. 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) {
  7397. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7398. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7399. p.misalign_offsets = (a_offset << 16) | d_offset;
  7400. GGML_UNUSED(src1);
  7401. GGML_UNUSED(src2);
  7402. GGML_UNUSED(src3);
  7403. }
  7404. 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) {
  7405. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7406. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7407. p.misalign_offsets = (a_offset << 16) | d_offset;
  7408. GGML_UNUSED(src1);
  7409. GGML_UNUSED(src2);
  7410. GGML_UNUSED(src3);
  7411. }
  7412. 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) {
  7413. const uint32_t a_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7414. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7415. p.misalign_offsets = (a_offset << 16) | d_offset;
  7416. GGML_UNUSED(src0);
  7417. GGML_UNUSED(src2);
  7418. GGML_UNUSED(src3);
  7419. }
  7420. 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) {
  7421. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7422. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7423. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7424. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  7425. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  7426. GGML_UNUSED(src2);
  7427. GGML_UNUSED(src3);
  7428. }
  7429. 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) {
  7430. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7431. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7432. p.a_offset = a_offset;
  7433. p.d_offset = d_offset;
  7434. GGML_UNUSED(src1);
  7435. GGML_UNUSED(src2);
  7436. GGML_UNUSED(src3);
  7437. }
  7438. template<typename PC>
  7439. 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) {
  7440. 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];
  7441. if (src1 != nullptr) {
  7442. 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];
  7443. }
  7444. if (src2 != nullptr) {
  7445. 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];
  7446. }
  7447. if (src3 != nullptr) {
  7448. 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];
  7449. }
  7450. 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];
  7451. std::cerr << "), " << ggml_op_name(op) << ")");
  7452. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  7453. GGML_ASSERT(ggml_vk_op_supports_incontiguous(op) || ggml_vk_dim01_contiguous(src0)); // NOLINT
  7454. GGML_ASSERT(dst->buffer != nullptr);
  7455. const uint64_t ne00 = src0->ne[0];
  7456. const uint64_t ne01 = src0->ne[1];
  7457. const uint64_t ne02 = src0->ne[2];
  7458. const uint64_t ne03 = src0->ne[3];
  7459. const bool use_src1 = src1 != nullptr;
  7460. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  7461. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  7462. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  7463. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  7464. const bool use_src2 = src2 != nullptr;
  7465. const bool use_src3 = src3 != nullptr;
  7466. init_pushconst_fastdiv(pc);
  7467. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  7468. if (pipeline == nullptr) {
  7469. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  7470. if (src1 != nullptr) {
  7471. std::cerr << " and " << ggml_type_name(src1->type);
  7472. }
  7473. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  7474. GGML_ABORT("fatal error");
  7475. }
  7476. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7477. const bool op_supports_incontiguous = ggml_vk_op_supports_incontiguous(op);
  7478. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0, op_supports_incontiguous);
  7479. vk_subbuffer src1_buf = use_src1 ? ggml_vk_tensor_subbuffer(ctx, src1, op_supports_incontiguous) : vk_subbuffer{};
  7480. vk_subbuffer src2_buf = use_src2 ? ggml_vk_tensor_subbuffer(ctx, src2, op_supports_incontiguous) : vk_subbuffer{};
  7481. vk_subbuffer src3_buf = use_src3 ? ggml_vk_tensor_subbuffer(ctx, src3, op_supports_incontiguous) : vk_subbuffer{};
  7482. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, op_supports_incontiguous);
  7483. // Compute misalignment offset for descriptors and store it in in push constants.
  7484. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, src3, dst);
  7485. std::array<uint32_t, 3> elements;
  7486. // Single call if dimension 2 is contiguous
  7487. GGML_ASSERT(op_supports_incontiguous || (ggml_is_contiguous(src0) && (src1 == nullptr || ggml_is_contiguous(src1))));
  7488. switch (op) {
  7489. case GGML_OP_NORM:
  7490. case GGML_OP_RMS_NORM_BACK:
  7491. case GGML_OP_L2_NORM:
  7492. case GGML_OP_SOFT_MAX:
  7493. case GGML_OP_SOFT_MAX_BACK:
  7494. case GGML_OP_SUM_ROWS:
  7495. case GGML_OP_MEAN:
  7496. case GGML_OP_ARGMAX:
  7497. {
  7498. const uint32_t nr = ggml_nrows(src0);
  7499. if (nr > 262144) {
  7500. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7501. } else if (nr > 512) {
  7502. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7503. } else {
  7504. elements = { nr, 1, 1 };
  7505. }
  7506. } break;
  7507. case GGML_OP_RMS_NORM:
  7508. if (ctx->do_add_rms_partials) {
  7509. // Run one element per thread, 128 threads per workgroup
  7510. elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 };
  7511. } else {
  7512. elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 };
  7513. }
  7514. break;
  7515. case GGML_OP_SUM:
  7516. // We use GGML_OP_SUM_ROWS with 1 row.
  7517. elements = { 1, 1, 1 };
  7518. break;
  7519. case GGML_OP_GROUP_NORM:
  7520. {
  7521. const uint32_t num_groups = dst->op_params[0];
  7522. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  7523. } break;
  7524. case GGML_OP_DIAG_MASK_INF:
  7525. case GGML_OP_ROPE:
  7526. case GGML_OP_ROPE_BACK:
  7527. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  7528. break;
  7529. case GGML_OP_GET_ROWS:
  7530. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  7531. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7532. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7533. break;
  7534. case GGML_OP_ARGSORT:
  7535. elements = { (uint32_t)ne00, (uint32_t)ggml_nrows(src0), 1 };
  7536. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7537. break;
  7538. case GGML_OP_IM2COL:
  7539. {
  7540. const bool is_2D = dst->op_params[6] == 1;
  7541. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  7542. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  7543. const uint32_t KW = src0->ne[0];
  7544. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  7545. const uint32_t OW = dst->ne[1];
  7546. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  7547. elements = { OW * KW * KH, OH, batch * IC };
  7548. } break;
  7549. case GGML_OP_IM2COL_3D:
  7550. {
  7551. const uint32_t IC = ((const uint32_t *)(dst->op_params))[9];
  7552. const uint32_t N = ne13 / IC;
  7553. const uint32_t KD = ne02;
  7554. const uint32_t KH = ne01;
  7555. const uint32_t KW = ne00;
  7556. const uint32_t OD = dst->ne[3] / N;
  7557. const uint32_t OH = dst->ne[2];
  7558. const uint32_t OW = dst->ne[1];
  7559. const uint32_t IC_KD_KH_KW = IC*KD*KH*KW;
  7560. const uint32_t N_OD_OH = N*OD*OH;
  7561. elements = { IC_KD_KH_KW, OW, N_OD_OH };
  7562. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7563. } break;
  7564. case GGML_OP_TIMESTEP_EMBEDDING:
  7565. {
  7566. const uint32_t dim = dst->op_params[0];
  7567. uint32_t half_ceil = (dim + 1) / 2;
  7568. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  7569. } break;
  7570. case GGML_OP_CONV_TRANSPOSE_1D:
  7571. {
  7572. elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1}
  7573. } break;
  7574. case GGML_OP_POOL_2D:
  7575. {
  7576. const uint32_t N = dst->ne[3];
  7577. const uint32_t OC = dst->ne[2];
  7578. const uint32_t OH = dst->ne[1];
  7579. const uint32_t OW = dst->ne[0];
  7580. elements = { N * OC * OH * OW, 1, 1};
  7581. } break;
  7582. case GGML_OP_CONV_2D:
  7583. {
  7584. elements = ggml_vk_get_conv_elements(dst);
  7585. } break;
  7586. case GGML_OP_CONV_TRANSPOSE_2D:
  7587. {
  7588. elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  7589. } break;
  7590. case GGML_OP_ADD:
  7591. case GGML_OP_SUB:
  7592. case GGML_OP_DIV:
  7593. case GGML_OP_MUL:
  7594. case GGML_OP_SCALE:
  7595. case GGML_OP_SQR:
  7596. case GGML_OP_SQRT:
  7597. case GGML_OP_SIN:
  7598. case GGML_OP_COS:
  7599. case GGML_OP_LOG:
  7600. case GGML_OP_CLAMP:
  7601. case GGML_OP_PAD:
  7602. case GGML_OP_ROLL:
  7603. case GGML_OP_REPEAT:
  7604. case GGML_OP_REPEAT_BACK:
  7605. case GGML_OP_CPY:
  7606. case GGML_OP_CONCAT:
  7607. case GGML_OP_UPSCALE:
  7608. case GGML_OP_UNARY:
  7609. case GGML_OP_GLU:
  7610. case GGML_OP_CONV_2D_DW:
  7611. {
  7612. uint32_t ne = ggml_nelements(dst);
  7613. if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7614. // Convert from number of logical elements to 2- or 4-byte units.
  7615. ne /= ggml_blck_size(src0->type);
  7616. if ((ggml_type_size(src0->type) % 4) == 0) {
  7617. ne *= ggml_type_size(src0->type) / 4;
  7618. } else {
  7619. ne *= ggml_type_size(src0->type) / 2;
  7620. }
  7621. }
  7622. // copy_to_quant has block size of 32, and each thread does QUANT_K elements.
  7623. // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements.
  7624. // So divide by block size here before splitting into 512x512 groups.
  7625. if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7626. ne = CEIL_DIV(ne, ggml_blck_size(dst->type));
  7627. }
  7628. if (ne > 262144) {
  7629. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7630. } else if (ne > 512) {
  7631. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7632. } else {
  7633. elements = { ne, 1, 1 };
  7634. }
  7635. } break;
  7636. case GGML_OP_ADD_ID:
  7637. {
  7638. elements = { (uint32_t)ne01, (uint32_t)ne02, 1 };
  7639. } break;
  7640. case GGML_OP_SET_ROWS:
  7641. {
  7642. uint32_t ne = ggml_nelements(src0);
  7643. if (ggml_is_quantized(dst->type)) {
  7644. // quants run 32 threads each doing QUANT_K elements
  7645. ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type));
  7646. } else {
  7647. // scalar types do one element per thread, running 512 threads
  7648. ne = CEIL_DIV(ne, 512);
  7649. }
  7650. if (ne > 262144) {
  7651. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7652. } else if (ne > 512) {
  7653. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7654. } else {
  7655. elements = { ne, 1, 1 };
  7656. }
  7657. }
  7658. break;
  7659. case GGML_OP_SSM_CONV:
  7660. {
  7661. const uint32_t nr = src0->ne[1];
  7662. const uint32_t n_t = dst->ne[1];
  7663. const uint32_t n_s = dst->ne[2];
  7664. elements = { nr, n_t, n_s };
  7665. }
  7666. break;
  7667. default:
  7668. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  7669. break;
  7670. }
  7671. if (op == GGML_OP_ADD || op == GGML_OP_RMS_NORM) {
  7672. vk_subbuffer a_buf = src0_buf;
  7673. if (ctx->do_add_rms_partials) {
  7674. a_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset);
  7675. }
  7676. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7677. { src0_buf, src1_buf, dst_buf, a_buf }, pc, elements);
  7678. } else if (op == GGML_OP_GLU) {
  7679. // Empty src1 is possible in glu, but the shader needs a buffer
  7680. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  7681. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc, elements);
  7682. } else if (op == GGML_OP_SOFT_MAX) {
  7683. // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer
  7684. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  7685. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  7686. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, subbuf2, dst_buf }, pc, elements);
  7687. } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) {
  7688. // Empty src2 and src3 is possible in rope, but the shader needs a buffer
  7689. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  7690. vk_subbuffer subbuf3 = use_src3 ? src3_buf : src0_buf;
  7691. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, subbuf2, dst_buf, subbuf3 }, pc, elements);
  7692. } else if (op == GGML_OP_IM2COL || op == GGML_OP_IM2COL_3D) {
  7693. if (ctx->device->shader_int64 && ctx->device->buffer_device_address) {
  7694. // buffer device address path doesn't use dst buffer
  7695. dst_buf.size = 1;
  7696. }
  7697. // im2col uses only src1 and dst buffers
  7698. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src1_buf, dst_buf }, pc, elements);
  7699. } else if (op == GGML_OP_COUNT_EQUAL) {
  7700. // count_equal assumes that destination buffer is initialized with zeroes
  7701. ggml_vk_buffer_memset_async(subctx, dst_buf.buffer, dst_buf.offset, 0, dst_buf.size);
  7702. ggml_vk_sync_buffers(ctx, subctx);
  7703. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  7704. } else if (op == GGML_OP_OPT_STEP_SGD) {
  7705. // OPT_STEP_SGD works on src0, it does not need dst
  7706. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf }, pc, elements);
  7707. } else if (use_src3) {
  7708. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, src3_buf, dst_buf }, pc, elements);
  7709. } else if (use_src2) {
  7710. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, dst_buf }, pc, elements);
  7711. } else if (use_src1) {
  7712. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  7713. } else {
  7714. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, dst_buf }, pc, elements);
  7715. }
  7716. }
  7717. 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) {
  7718. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7719. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7720. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7721. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GET_ROWS, {
  7722. (uint32_t)ggml_nelements(src0),
  7723. (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,
  7724. (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,
  7725. (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,
  7726. 0,
  7727. 0.0f, 0.0f, 0,
  7728. });
  7729. }
  7730. static void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7731. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7732. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7733. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7734. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  7735. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  7736. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  7737. int offset = dst->op_params[3] / 4; // offset in bytes
  7738. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ACC, {
  7739. (uint32_t)ggml_nelements(src0),
  7740. (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,
  7741. (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,
  7742. (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,
  7743. 0,
  7744. 0.0f, 0.0f, offset,
  7745. });
  7746. }
  7747. static void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  7748. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  7749. const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  7750. // Make a list of all the tensors used by the op.
  7751. // Last element of the list is the dest tensor.
  7752. const ggml_tensor *tensors[MAX_PARAMETER_COUNT];
  7753. uint32_t num_srcs = ctx->num_additional_fused_ops + 2;
  7754. uint32_t num_tensors = num_srcs + 1;
  7755. GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT);
  7756. tensors[0] = first_node->src[0];
  7757. tensors[1] = first_node->src[1];
  7758. for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) {
  7759. // check whether the previous result is src[0] or src[1]
  7760. if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) {
  7761. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1];
  7762. } else {
  7763. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0];
  7764. }
  7765. }
  7766. tensors[num_srcs] = dst;
  7767. vk_op_multi_add_push_constants pc;
  7768. pc.ne20 = (uint32_t)dst->ne[0];
  7769. pc.ne21 = (uint32_t)dst->ne[1];
  7770. pc.ne22 = (uint32_t)dst->ne[2];
  7771. pc.ne23 = (uint32_t)dst->ne[3];
  7772. for (uint32_t i = 0; i < num_tensors; ++i) {
  7773. const ggml_tensor *t = tensors[i];
  7774. pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float);
  7775. pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float);
  7776. pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float);
  7777. pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float);
  7778. }
  7779. pc.rms_partials = ctx->do_add_rms_partials;
  7780. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, tensors[0], tensors[1], nullptr, dst, dst->op);
  7781. if (pipeline == nullptr) {
  7782. std::cerr << "ggml_vulkan: Error: Missing multi_add";
  7783. GGML_ABORT("fatal error");
  7784. }
  7785. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7786. ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT];
  7787. vk_buffer buf[MAX_PARAMETER_COUNT];
  7788. size_t offset[MAX_PARAMETER_COUNT];
  7789. bool uma[MAX_PARAMETER_COUNT];
  7790. for (uint32_t i = 0; i < num_tensors; ++i) {
  7791. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  7792. buf[i] = nullptr;
  7793. offset[i] = 0;
  7794. uma[i] = false;
  7795. if (ctx->device->uma) {
  7796. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  7797. uma[i] = buf[i] != nullptr;
  7798. }
  7799. if (!uma[i]) {
  7800. buf[i] = buf_ctx[i]->dev_buffer;
  7801. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  7802. }
  7803. GGML_ASSERT(buf[i] != nullptr);
  7804. }
  7805. // If any remaining descriptors are unused, just point them at src[0]
  7806. for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) {
  7807. buf[i] = buf[0];
  7808. offset[i] = 0;
  7809. }
  7810. if (ctx->do_add_rms_partials) {
  7811. buf[num_tensors] = ctx->prealloc_add_rms_partials;
  7812. offset[num_tensors] = ctx->prealloc_size_add_rms_partials_offset;
  7813. }
  7814. std::array<uint32_t, 3> elements;
  7815. uint32_t ne = ggml_nelements(dst);
  7816. if (ne > 262144) {
  7817. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7818. } else if (ne > 512) {
  7819. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7820. } else {
  7821. elements = { ne, 1, 1 };
  7822. }
  7823. static_assert(MAX_PARAMETER_COUNT == 12);
  7824. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7825. {
  7826. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  7827. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  7828. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  7829. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  7830. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  7831. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  7832. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  7833. ggml_vk_subbuffer(ctx, buf[7], offset[7]),
  7834. ggml_vk_subbuffer(ctx, buf[8], offset[8]),
  7835. ggml_vk_subbuffer(ctx, buf[9], offset[9]),
  7836. ggml_vk_subbuffer(ctx, buf[10], offset[10]),
  7837. ggml_vk_subbuffer(ctx, buf[11], offset[11]),
  7838. }, pc, elements);
  7839. }
  7840. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7841. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7842. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7843. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7844. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD, {
  7845. (uint32_t)ggml_nelements(src0),
  7846. (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,
  7847. (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,
  7848. (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,
  7849. 0,
  7850. 0.0f, 0.0f, ctx->do_add_rms_partials,
  7851. });
  7852. }
  7853. static void ggml_vk_sub(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7854. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7855. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7856. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7857. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SUB, {
  7858. (uint32_t)ggml_nelements(src0),
  7859. (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,
  7860. (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,
  7861. (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,
  7862. 0,
  7863. 0.0f, 0.0f, 0,
  7864. });
  7865. }
  7866. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7867. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7868. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7869. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7870. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_MUL, {
  7871. (uint32_t)ggml_nelements(src0),
  7872. (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,
  7873. (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,
  7874. (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,
  7875. 0,
  7876. 0.0f, 0.0f, 0,
  7877. });
  7878. }
  7879. static void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7880. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7881. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7882. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7883. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_DIV, {
  7884. (uint32_t)ggml_nelements(src0),
  7885. (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,
  7886. (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,
  7887. (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,
  7888. 0,
  7889. 0.0f, 0.0f, 0,
  7890. });
  7891. }
  7892. 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) {
  7893. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7894. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7895. const uint32_t src2_type_size = ggml_type_size(src2->type);
  7896. ggml_vk_op_f32<vk_op_add_id_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_ADD_ID, {
  7897. (uint32_t)dst->ne[0],
  7898. (uint32_t)dst->ne[1],
  7899. (uint32_t)src0->nb[1] / src0_type_size,
  7900. (uint32_t)src0->nb[2] / src0_type_size,
  7901. (uint32_t)src1->nb[1] / src1_type_size,
  7902. (uint32_t)src2->nb[1] / src2_type_size,
  7903. });
  7904. }
  7905. 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) {
  7906. GGML_ASSERT(version == 6 || version == 7);
  7907. int num_srcs = version == 6 ? 6 : 7;
  7908. for (int i = 0; i < num_srcs; i++) {
  7909. GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type));
  7910. }
  7911. GGML_ASSERT(dst->buffer != nullptr);
  7912. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op);
  7913. GGML_ASSERT(pipeline != nullptr);
  7914. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7915. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  7916. vk_subbuffer src_buf[7] = {};
  7917. for (int i = 0; i < num_srcs; i++) {
  7918. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  7919. }
  7920. std::array<uint32_t, 3> elements = {
  7921. (uint32_t)(pc.B * pc.H),
  7922. 1,
  7923. 1
  7924. };
  7925. if (version == 6) {
  7926. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7927. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf},
  7928. pc, elements);
  7929. } else if (version == 7) {
  7930. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7931. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  7932. pc, elements);
  7933. } else {
  7934. // shouldn't happen
  7935. GGML_ASSERT(false);
  7936. }
  7937. }
  7938. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  7939. const size_t seq_length = dst->src[0]->ne[2];
  7940. const size_t n_embed = dst->ne[0];
  7941. const size_t n_heads = dst->src[0]->ne[1];
  7942. const size_t n_seqs = dst->src[5]->ne[1];
  7943. ggml_vk_op_f32_wkv(
  7944. ctx, subctx, dst,
  7945. {
  7946. (uint32_t)n_seqs,
  7947. (uint32_t)seq_length,
  7948. (uint32_t)n_embed,
  7949. (uint32_t)n_heads,
  7950. },
  7951. 6
  7952. );
  7953. }
  7954. static void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  7955. const size_t seq_length = dst->src[0]->ne[2];
  7956. const size_t n_embed = dst->ne[0];
  7957. const size_t n_heads = dst->src[0]->ne[1];
  7958. const size_t n_seqs = dst->src[6]->ne[1];
  7959. ggml_vk_op_f32_wkv(
  7960. ctx, subctx, dst,
  7961. {
  7962. (uint32_t)n_seqs,
  7963. (uint32_t)seq_length,
  7964. (uint32_t)n_embed,
  7965. (uint32_t)n_heads,
  7966. },
  7967. 7
  7968. );
  7969. }
  7970. static void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  7971. const ggml_tensor * src0 = dst->src[0];
  7972. const ggml_tensor * src1 = dst->src[1];
  7973. const ggml_tensor * src2 = dst->src[2];
  7974. const ggml_tensor * src3 = dst->src[3];
  7975. const ggml_tensor * src4 = dst->src[4];
  7976. const ggml_tensor * src5 = dst->src[5];
  7977. GGML_ASSERT(dst->buffer != nullptr);
  7978. const uint32_t head_dim = src0->ne[1];
  7979. const uint32_t n_head = src1->ne[1];
  7980. const uint32_t n_group = src4->ne[1];
  7981. const uint32_t n_tok = src1->ne[2];
  7982. const uint32_t n_seq = src1->ne[3];
  7983. bool is_mamba2 = (src3->nb[1] == sizeof(float));
  7984. GGML_ASSERT(is_mamba2);
  7985. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op);
  7986. GGML_ASSERT(pipeline != nullptr);
  7987. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7988. const int64_t s_off = ggml_nelements(src1) * sizeof(float);
  7989. const vk_op_ssm_scan_push_constants pc = {
  7990. (uint32_t)src0->nb[2], (uint32_t)src0->nb[3],
  7991. (uint32_t)src1->nb[2], (uint32_t)src1->nb[3],
  7992. (uint32_t)src2->nb[1], (uint32_t)src2->nb[2],
  7993. (uint32_t)src3->nb[1],
  7994. (uint32_t)src4->nb[2], (uint32_t)src4->nb[3],
  7995. (uint32_t)src5->nb[2], (uint32_t)src5->nb[3],
  7996. (uint32_t)s_off,
  7997. n_head, head_dim, n_group, n_tok
  7998. };
  7999. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8000. vk_subbuffer src_buf[7] = {};
  8001. for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
  8002. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8003. }
  8004. std::array<uint32_t, 3> elements;
  8005. const int splitH = 16;
  8006. const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, splitH);
  8007. const uint32_t num_workgroups_y = n_seq;
  8008. elements = { num_workgroups_x, num_workgroups_y, 1 };
  8009. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8010. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8011. pc, elements);
  8012. }
  8013. static void ggml_vk_ssm_conv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8014. const ggml_tensor * src0 = dst->src[0];
  8015. const ggml_tensor * src1 = dst->src[1];
  8016. ggml_vk_op_f32<vk_op_ssm_conv_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SSM_CONV, {
  8017. (uint32_t)src0->nb[1], (uint32_t)src0->nb[2],
  8018. (uint32_t)src1->nb[1],
  8019. (uint32_t)dst->nb[0], (uint32_t)dst->nb[1], (uint32_t)dst->nb[2],
  8020. (uint32_t)src1->ne[0],
  8021. (uint32_t)src0->ne[0],
  8022. (uint32_t)src0->ne[1],
  8023. (uint32_t)dst->ne[1],
  8024. (uint32_t)dst->ne[2],
  8025. });
  8026. }
  8027. 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) {
  8028. const ggml_tensor * x = dst->src[0];
  8029. const ggml_tensor * g = dst->src[1];
  8030. const ggml_tensor * gm = dst->src[2];
  8031. const ggml_tensor * gv = dst->src[3];
  8032. const ggml_tensor * p = dst->src[4];
  8033. GGML_ASSERT(x->type == GGML_TYPE_F32);
  8034. GGML_ASSERT(g->type == GGML_TYPE_F32);
  8035. GGML_ASSERT(gm->type == GGML_TYPE_F32);
  8036. GGML_ASSERT(gv->type == GGML_TYPE_F32);
  8037. GGML_ASSERT(p->type == GGML_TYPE_F32);
  8038. GGML_ASSERT(dst->buffer != nullptr);
  8039. GGML_ASSERT(ggml_is_contiguous(x));
  8040. GGML_ASSERT(ggml_is_contiguous(g));
  8041. GGML_ASSERT(ggml_is_contiguous(gm));
  8042. GGML_ASSERT(ggml_is_contiguous(gv));
  8043. GGML_ASSERT(ggml_is_contiguous(p));
  8044. GGML_ASSERT(ggml_are_same_shape(x, g));
  8045. GGML_ASSERT(ggml_are_same_shape(x, gm));
  8046. GGML_ASSERT(ggml_are_same_shape(x, gv));
  8047. GGML_ASSERT(ggml_nelements(p) == 7);
  8048. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW);
  8049. GGML_ASSERT(pipeline != nullptr);
  8050. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8051. vk_subbuffer x_buf = ggml_vk_tensor_subbuffer(ctx, x);
  8052. vk_subbuffer g_buf = ggml_vk_tensor_subbuffer(ctx, g);
  8053. vk_subbuffer gm_buf = ggml_vk_tensor_subbuffer(ctx, gm);
  8054. vk_subbuffer gv_buf = ggml_vk_tensor_subbuffer(ctx, gv);
  8055. vk_subbuffer p_buf = ggml_vk_tensor_subbuffer(ctx, p);
  8056. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(x), 1, 1 };
  8057. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8058. {x_buf, g_buf, gm_buf, gv_buf, p_buf},
  8059. pc, elements);
  8060. }
  8061. static void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8062. const size_t n = ggml_nelements(dst->src[0]);
  8063. ggml_vk_op_f32_opt_step_adamw(
  8064. ctx, subctx, dst,
  8065. { (uint32_t)n, 0, 0.0f, 0.0f }
  8066. );
  8067. }
  8068. 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) {
  8069. const size_t n = ggml_nelements(dst->src[0]);
  8070. 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 });
  8071. }
  8072. static void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8073. int * op_params = (int *)dst->op_params;
  8074. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8075. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8076. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8077. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONCAT, {
  8078. (uint32_t)ggml_nelements(dst),
  8079. (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,
  8080. (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,
  8081. (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,
  8082. 0,
  8083. 0.0f, 0.0f, op_params[0],
  8084. });
  8085. }
  8086. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8087. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8088. const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0);
  8089. GGML_TENSOR_UNARY_OP_LOCALS
  8090. float sf0 = (float)ne0 / ne00;
  8091. float sf1 = (float)ne1 / ne01;
  8092. float sf2 = (float)ne2 / ne02;
  8093. float sf3 = (float)ne3 / ne03;
  8094. float pixel_offset = 0.5f;
  8095. if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) {
  8096. sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0;
  8097. sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1;
  8098. pixel_offset = 0.0f;
  8099. }
  8100. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  8101. (uint32_t)ggml_nelements(dst), 0, 0,
  8102. (uint32_t)ne00, (uint32_t)ne01,
  8103. (uint32_t)nb00 / src0_type_size, (uint32_t)nb01 / src0_type_size, (uint32_t)nb02 / src0_type_size, (uint32_t)nb03 / src0_type_size,
  8104. (uint32_t)ne0, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  8105. sf0, sf1, sf2, sf3, pixel_offset
  8106. });
  8107. }
  8108. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8109. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8110. p.param1 = ggml_get_op_params_f32(dst, 0);
  8111. p.param2 = ggml_get_op_params_f32(dst, 1);
  8112. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p));
  8113. }
  8114. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8115. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst));
  8116. }
  8117. static void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8118. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst));
  8119. }
  8120. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8121. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst));
  8122. }
  8123. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8124. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst));
  8125. }
  8126. static void ggml_vk_log(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8127. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_LOG, vk_op_unary_push_constants_init(src0, dst));
  8128. }
  8129. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8130. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8131. p.param1 = ggml_get_op_params_f32(dst, 0);
  8132. p.param2 = ggml_get_op_params_f32(dst, 1);
  8133. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p));
  8134. }
  8135. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8136. vk_op_pad_push_constants p = vk_op_pad_push_constants_init(src0, dst);
  8137. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p));
  8138. }
  8139. static void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8140. const int32_t s0 = ggml_get_op_params_i32(dst, 0);
  8141. const int32_t s1 = ggml_get_op_params_i32(dst, 1);
  8142. const int32_t s2 = ggml_get_op_params_i32(dst, 2);
  8143. const int32_t s3 = ggml_get_op_params_i32(dst, 3);
  8144. const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
  8145. const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
  8146. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8147. memcpy(&p.param1, &s01_packed, sizeof(float));
  8148. memcpy(&p.param2, &s23_packed, sizeof(float));
  8149. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p));
  8150. }
  8151. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8152. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8153. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p));
  8154. }
  8155. static void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8156. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8157. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p));
  8158. }
  8159. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8160. uint32_t ne = (uint32_t)ggml_nelements(src0);
  8161. if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8162. // Convert from number of logical elements to 2- or 4-byte units.
  8163. ne /= ggml_blck_size(src0->type);
  8164. if ((ggml_type_size(src0->type) % 4) == 0) {
  8165. ne *= ggml_type_size(src0->type) / 4;
  8166. } else {
  8167. ne *= ggml_type_size(src0->type) / 2;
  8168. }
  8169. }
  8170. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne);
  8171. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p));
  8172. }
  8173. 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) {
  8174. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8175. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8176. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8177. // Skip empty skip_rows operations. For most ops the empty check at the start
  8178. // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst
  8179. // with empty srcs.
  8180. if (ggml_is_empty(src0) || ggml_is_empty(src1)) {
  8181. return;
  8182. }
  8183. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SET_ROWS, {
  8184. (uint32_t)ggml_nelements(src0),
  8185. (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,
  8186. (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,
  8187. (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,
  8188. 0,
  8189. 0.0f, 0.0f, 0,
  8190. });
  8191. }
  8192. 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) {
  8193. 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 });
  8194. }
  8195. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8196. float * op_params = (float *)dst->op_params;
  8197. 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 });
  8198. }
  8199. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8200. const int * int_op_params = (const int *)dst->op_params;
  8201. const float * float_op_params = (const float *)dst->op_params;
  8202. const uint32_t num_groups = int_op_params[0];
  8203. const float eps = float_op_params[1];
  8204. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  8205. 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 });
  8206. }
  8207. static uint32_t ggml_vk_rms_num_partials(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8208. const uint32_t ne = (uint32_t)node->ne[0];
  8209. const uint32_t denom = ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0];
  8210. const uint32_t num_partials = CEIL_DIV(ne, denom);
  8211. return num_partials;
  8212. }
  8213. static uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8214. const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node);
  8215. const uint32_t num_bytes = ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment);
  8216. return num_bytes;
  8217. }
  8218. 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) {
  8219. const int n_dims = ((const int32_t *) dst->op_params)[1];
  8220. const int mode = ((const int32_t *) dst->op_params)[2];
  8221. // const int n_ctx = ((const int32_t *) dst->op_params)[3];
  8222. const int n_ctx_orig = ((const int32_t *) dst->op_params)[4];
  8223. const float freq_base = ((const float *) dst->op_params)[5];
  8224. const float freq_scale = ((const float *) dst->op_params)[6];
  8225. const float ext_factor = ((const float *) dst->op_params)[7];
  8226. const float attn_factor = ((const float *) dst->op_params)[8];
  8227. const float beta_fast = ((const float *) dst->op_params)[9];
  8228. const float beta_slow = ((const float *) dst->op_params)[10];
  8229. int sections[4] {};
  8230. if (mode & GGML_ROPE_TYPE_MROPE) {
  8231. memcpy(sections, (const int32_t *) dst->op_params + 11, sizeof(int)*4);
  8232. }
  8233. const bool is_imrope = mode == GGML_ROPE_TYPE_IMROPE;
  8234. float corr_dims[2];
  8235. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8236. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  8237. uint32_t nb01 = src0->nb[1] / ggml_type_size(src0->type);
  8238. uint32_t nb02 = src0->nb[2] / ggml_type_size(src0->type);
  8239. vk_op_rope_push_constants rope {
  8240. (uint32_t)mode, (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  8241. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  8242. has_ff, (uint32_t)src0->ne[2], nb01, nb02,
  8243. { sections[0], sections[1], sections[2], sections[3] }, is_imrope, backprop, set_rows_stride,
  8244. };
  8245. return rope;
  8246. }
  8247. 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) {
  8248. ggml_tensor * dst;
  8249. const ggml_tensor * src0;
  8250. const ggml_tensor * src1;
  8251. if (ctx->num_additional_fused_ops > 0) {
  8252. // fused rms_norm + mul
  8253. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8254. ggml_tensor *other_src = mul->src[0] == cgraph->nodes[node_idx + 0] ? mul->src[1] : mul->src[0];
  8255. dst = mul;
  8256. src0 = cgraph->nodes[node_idx]->src[0];
  8257. src1 = other_src;
  8258. } else {
  8259. dst = cgraph->nodes[node_idx];
  8260. src0 = src1 = dst->src[0];
  8261. }
  8262. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8263. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8264. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8265. uint32_t param3 = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0;
  8266. vk_op_binary_push_constants bin {
  8267. (uint32_t)ggml_nelements(src0),
  8268. (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,
  8269. (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,
  8270. (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,
  8271. 0,
  8272. op_params[0], 0.0f, (int32_t)param3,
  8273. };
  8274. // more than one fused op means rms_norm+mul+rope
  8275. if (ctx->num_additional_fused_ops > 1) {
  8276. static constexpr uint32_t max_tensors = 7;
  8277. const ggml_tensor *tensors[max_tensors] {};
  8278. ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  8279. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8280. ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  8281. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  8282. bool do_set_rows = ctx->num_additional_fused_ops == 4;
  8283. tensors[0] = rms->src[0];
  8284. tensors[1] = other_src;
  8285. tensors[2] = mul;
  8286. tensors[3] = rope->src[1]; // pos
  8287. tensors[4] = rope->src[2]; // ff
  8288. tensors[5] = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; // dst
  8289. tensors[6] = do_set_rows ? tensors[5]->src[1] : nullptr;
  8290. const uint32_t set_rows_stride = do_set_rows ? tensors[5]->nb[1] / ggml_type_size(tensors[5]->type) : 0;
  8291. vk_op_rms_norm_mul_rope_push_constants pc;
  8292. pc.bin = bin;
  8293. pc.rope = ggml_vk_make_rope_constants(rope, rope->src[0], tensors[4] != nullptr, false, set_rows_stride);
  8294. 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;
  8295. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8296. ggml_backend_vk_buffer_context * buf_ctx[max_tensors];
  8297. vk_buffer buf[max_tensors];
  8298. size_t offset[max_tensors];
  8299. bool uma[max_tensors];
  8300. for (uint32_t i = 0; i < max_tensors; ++i) {
  8301. if (!tensors[i]) {
  8302. // If any remaining descriptors are unused, just point them at src[0]
  8303. buf[i] = buf[0];
  8304. offset[i] = 0;
  8305. continue;
  8306. }
  8307. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8308. buf[i] = nullptr;
  8309. offset[i] = 0;
  8310. uma[i] = false;
  8311. if (ctx->device->uma) {
  8312. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8313. uma[i] = buf[i] != nullptr;
  8314. }
  8315. if (!uma[i]) {
  8316. buf[i] = buf_ctx[i]->dev_buffer;
  8317. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8318. }
  8319. GGML_ASSERT(buf[i] != nullptr);
  8320. }
  8321. std::array<uint32_t, 3> elements;
  8322. elements = { (uint32_t)rms->src[0]->ne[1], (uint32_t)rms->src[0]->ne[2], (uint32_t)rms->src[0]->ne[3] };
  8323. static_assert(max_tensors == 7);
  8324. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8325. {
  8326. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8327. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8328. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8329. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8330. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8331. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8332. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8333. }, pc, elements);
  8334. } else {
  8335. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM, std::move(bin));
  8336. }
  8337. if (ctx->do_add_rms_partials_offset_calculation) {
  8338. ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0);
  8339. ctx->do_add_rms_partials = false;
  8340. ctx->do_add_rms_partials_offset_calculation = false;
  8341. }
  8342. }
  8343. 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) {
  8344. float * op_params = (float *)dst->op_params;
  8345. 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 });
  8346. }
  8347. static void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8348. float * op_params = (float *)dst->op_params;
  8349. 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 });
  8350. }
  8351. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8352. 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 });
  8353. }
  8354. static void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8355. const float * op_params_f = (const float *)dst->op_params;
  8356. const bool swapped = (bool)dst->op_params[1];
  8357. const bool split = src1 != nullptr;
  8358. const float alpha = op_params_f[2];
  8359. const float limit = op_params_f[3];
  8360. GGML_ASSERT(ggml_is_contiguous(src0));
  8361. if (!split) {
  8362. GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]);
  8363. } else {
  8364. GGML_ASSERT(src0->ne[0] == src1->ne[0]);
  8365. GGML_ASSERT(src0->ne[0] == dst->ne[0]);
  8366. GGML_ASSERT(src0->type == src1->type);
  8367. }
  8368. const uint32_t mode = split ? 2 : (swapped ? 1 : 0);
  8369. ggml_vk_op_f32<vk_op_glu_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GLU,
  8370. {
  8371. (uint32_t)ggml_nelements(dst),
  8372. (uint32_t)src0->ne[0],
  8373. (uint32_t)dst->ne[0],
  8374. mode,
  8375. alpha,
  8376. limit
  8377. });
  8378. }
  8379. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8380. int32_t * op_params = (int32_t *)dst->op_params;
  8381. 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] });
  8382. }
  8383. 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) {
  8384. float * op_params = (float *)dst->op_params;
  8385. float scale = op_params[0];
  8386. float max_bias = op_params[1];
  8387. const uint32_t ncols = (uint32_t)src0->ne[0];
  8388. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  8389. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  8390. const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u;
  8391. const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u;
  8392. const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u;
  8393. const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u;
  8394. const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u;
  8395. const uint32_t n_head_kv = src0->ne[2];
  8396. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  8397. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  8398. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  8399. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_SOFT_MAX, {
  8400. ncols,
  8401. src1 != nullptr ? nrows_y : (uint32_t)0,
  8402. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],
  8403. ne12, ne13,
  8404. nb11, nb12, nb13,
  8405. scale, max_bias,
  8406. m0, m1,
  8407. n_head_log2,
  8408. nrows_x,
  8409. src2 != nullptr
  8410. });
  8411. }
  8412. 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) {
  8413. float * op_params = (float *)dst->op_params;
  8414. 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] });
  8415. }
  8416. static void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  8417. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  8418. ggml_tensor * logits = cgraph->nodes[node_idx + 0]->src[0];
  8419. ggml_tensor * weights = (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) ? cgraph->nodes[node_idx + 9] :
  8420. (mode == TOPK_MOE_EARLY_SOFTMAX) ? cgraph->nodes[node_idx + 4] :
  8421. cgraph->nodes[node_idx + 5];
  8422. ggml_tensor * ids = (mode == TOPK_MOE_LATE_SOFTMAX) ? cgraph->nodes[node_idx + 1] : cgraph->nodes[node_idx + 3];
  8423. GGML_ASSERT(logits->type == GGML_TYPE_F32);
  8424. GGML_ASSERT(weights->type == GGML_TYPE_F32);
  8425. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  8426. const int n_experts = logits->ne[0];
  8427. const int n_rows = logits->ne[1];
  8428. const int n_expert_used = weights->ne[1];
  8429. GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) n_experts);
  8430. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, cgraph->nodes[node_idx], GGML_OP_SOFT_MAX);
  8431. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8432. vk_subbuffer logits_buf = ggml_vk_tensor_subbuffer(ctx, logits);
  8433. vk_subbuffer weights_buf = ggml_vk_tensor_subbuffer(ctx, weights);
  8434. vk_subbuffer ids_buf = ggml_vk_tensor_subbuffer(ctx, ids);
  8435. vk_op_topk_moe_push_constants pc {};
  8436. pc.n_rows = n_rows;
  8437. pc.n_expert_used = n_expert_used;
  8438. if (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) {
  8439. ggml_tensor * clamp = cgraph->nodes[node_idx + 7];
  8440. pc.clamp_min = ggml_get_op_params_f32(clamp, 0);
  8441. pc.clamp_max = ggml_get_op_params_f32(clamp, 1);
  8442. }
  8443. GGML_ASSERT(n_expert_used <= n_experts);
  8444. const uint32_t rows_per_block = 4;
  8445. std::array<uint32_t, 3> elements = { CEIL_DIV(n_rows, rows_per_block), 1, 1 };
  8446. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {logits_buf, weights_buf, ids_buf}, pc, elements);
  8447. }
  8448. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_cgraph * cgraph, int node_idx, bool backprop) {
  8449. ggml_tensor * dst = cgraph->nodes[node_idx];
  8450. const ggml_tensor * src0 = dst->src[0];
  8451. const ggml_tensor * src1 = dst->src[1];
  8452. const ggml_tensor * src2 = dst->src[2];
  8453. const ggml_tensor * src3 = nullptr;
  8454. const int n_dims = ((int32_t *) dst->op_params)[1];
  8455. const int mode = ((int32_t *) dst->op_params)[2];
  8456. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  8457. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  8458. const float freq_base = ((float *) dst->op_params)[5];
  8459. const float beta_fast = ((float *) dst->op_params)[9];
  8460. const float beta_slow = ((float *) dst->op_params)[10];
  8461. int sections[4] {};
  8462. if (mode & GGML_ROPE_TYPE_MROPE) {
  8463. memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4);
  8464. }
  8465. float corr_dims[2];
  8466. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8467. uint32_t set_rows_stride = 0;
  8468. // Fused rope + view + set_rows passes the set_rows destination stride in set_rows_stride
  8469. // and overrides the dst and sets src3=row_indices
  8470. if (ctx->num_additional_fused_ops > 0) {
  8471. set_rows_stride = cgraph->nodes[node_idx + 2]->nb[1] / ggml_type_size(cgraph->nodes[node_idx + 2]->type);
  8472. src3 = cgraph->nodes[node_idx + 2]->src[1];
  8473. dst = cgraph->nodes[node_idx + 2];
  8474. }
  8475. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, src3, dst, GGML_OP_ROPE,
  8476. ggml_vk_make_rope_constants(cgraph->nodes[node_idx], src0, src2 != nullptr, backprop, set_rows_stride));
  8477. }
  8478. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8479. int32_t * op_params = (int32_t *)dst->op_params;
  8480. uint32_t ncols = src0->ne[0];
  8481. uint32_t nrows = ggml_nrows(src0);
  8482. ggml_vk_op_f32<vk_op_argsort_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ARGSORT, {
  8483. ncols,
  8484. nrows,
  8485. op_params[0],
  8486. });
  8487. }
  8488. static void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8489. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, ggml_nelements(src0));
  8490. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM, p);
  8491. }
  8492. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8493. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8494. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, p);
  8495. }
  8496. static void ggml_vk_mean(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8497. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8498. p.weight = 1.0f / (float)src0->ne[0];
  8499. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_MEAN, p);
  8500. }
  8501. static void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8502. 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 });
  8503. }
  8504. 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) {
  8505. 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 });
  8506. }
  8507. static void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8508. const int32_t s0 = dst->op_params[0];
  8509. const int32_t s1 = dst->op_params[1];
  8510. const int32_t p0 = dst->op_params[2];
  8511. const int32_t p1 = dst->op_params[3];
  8512. const int32_t d0 = dst->op_params[4];
  8513. const int32_t d1 = dst->op_params[5];
  8514. const bool is_2D = dst->op_params[6] == 1;
  8515. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  8516. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  8517. const uint32_t IW = src1->ne[0];
  8518. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  8519. const uint32_t KW = src0->ne[0];
  8520. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  8521. const uint32_t OW = dst->ne[1];
  8522. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  8523. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  8524. const uint32_t pelements = OW * KW * KH;
  8525. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8526. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  8527. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  8528. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL, {
  8529. dst_addr,
  8530. batch_offset, offset_delta,
  8531. IC, IW, IH, OW, OH, KW, KH,
  8532. pelements,
  8533. IC * KH * KW,
  8534. s0, s1, p0, p1, d0, d1,
  8535. });
  8536. }
  8537. 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) {
  8538. GGML_TENSOR_BINARY_OP_LOCALS
  8539. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  8540. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  8541. const int32_t s2 = ((const int32_t *)(dst->op_params))[2];
  8542. const int32_t p0 = ((const int32_t *)(dst->op_params))[3];
  8543. const int32_t p1 = ((const int32_t *)(dst->op_params))[4];
  8544. const int32_t p2 = ((const int32_t *)(dst->op_params))[5];
  8545. const int32_t d0 = ((const int32_t *)(dst->op_params))[6];
  8546. const int32_t d1 = ((const int32_t *)(dst->op_params))[7];
  8547. const int32_t d2 = ((const int32_t *)(dst->op_params))[8];
  8548. const int32_t IC = ((const int32_t *)(dst->op_params))[9];
  8549. const int64_t N = ne13 / IC;
  8550. const int64_t ID = ne12;
  8551. const int64_t IH = ne11;
  8552. const int64_t IW = ne10;
  8553. const int64_t KD = ne02;
  8554. const int64_t KH = ne01;
  8555. const int64_t KW = ne00;
  8556. const int64_t OD = ne3 / N;
  8557. const int64_t OH = ne2;
  8558. const int64_t OW = ne1;
  8559. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8560. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  8561. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  8562. vk_op_im2col_3d_push_constants pc {};
  8563. pc.dst_addr = dst_addr;
  8564. pc.nb10 = nb10 / ggml_type_size(src1->type);
  8565. pc.nb11 = nb11 / ggml_type_size(src1->type);
  8566. pc.nb12 = nb12 / ggml_type_size(src1->type);
  8567. pc.nb13 = nb13 / ggml_type_size(src1->type);
  8568. pc.s0 = s0;
  8569. pc.s1 = s1;
  8570. pc.s2 = s2;
  8571. pc.p0 = p0;
  8572. pc.p1 = p1;
  8573. pc.p2 = p2;
  8574. pc.d0 = d0;
  8575. pc.d1 = d1;
  8576. pc.d2 = d2;
  8577. pc.IW = IW;
  8578. pc.IH = IH;
  8579. pc.ID = ID;
  8580. pc.IC = IC;
  8581. pc.KW = KW;
  8582. pc.OH = OH;
  8583. pc.KD_KH_KW = KD*KH*KW;
  8584. pc.KH_KW = KH*KW;
  8585. pc.IC_KD_KH_KW = IC*KD*KH*KW;
  8586. pc.N_OD_OH = N*OD*OH;
  8587. pc.OD_OH = OD*OH;
  8588. pc.OD_OH_OW_IC_KD_KH_KW = OD*OH*OW*IC*KD*KH*KW;
  8589. pc.OH_OW_IC_KD_KH_KW = OH*OW*IC*KD*KH*KW;
  8590. pc.OW_IC_KD_KH_KW = OW*IC*KD*KH*KW;
  8591. ggml_vk_op_f32<vk_op_im2col_3d_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL_3D, std::move(pc));
  8592. }
  8593. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8594. const uint32_t dim = dst->op_params[0];
  8595. const uint32_t max_period = dst->op_params[1];
  8596. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  8597. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  8598. nb1, dim, max_period,
  8599. });
  8600. }
  8601. 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) {
  8602. // src0: (K, Cout, Cin, 1) -- kernel
  8603. // src1: (L, Cin, 1, 1) -- input
  8604. // dst: (*, Cout, 1, 1)
  8605. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  8606. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8607. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  8608. GGML_TENSOR_BINARY_OP_LOCALS
  8609. GGML_ASSERT(nb00 == sizeof(float));
  8610. GGML_ASSERT(nb10 == sizeof(float));
  8611. const int32_t s0 = dst->op_params[0];
  8612. vk_op_conv_transpose_1d_push_constants p{};
  8613. p.Cout = static_cast<uint32_t>(ne01);
  8614. p.Cin = static_cast<uint32_t>(ne02);
  8615. p.K = static_cast<uint32_t>(ne00);
  8616. p.L = static_cast<uint32_t>(ne10);
  8617. p.KL = static_cast<uint32_t>(ne0);
  8618. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8619. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8620. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8621. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8622. p.s0 = static_cast<uint32_t>(s0);
  8623. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p));
  8624. }
  8625. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8626. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  8627. const int32_t k1 = dst->op_params[1];
  8628. const int32_t k0 = dst->op_params[2];
  8629. const int32_t s1 = dst->op_params[3];
  8630. const int32_t s0 = dst->op_params[4];
  8631. const int32_t p1 = dst->op_params[5];
  8632. const int32_t p0 = dst->op_params[6];
  8633. const uint32_t IH = src0->ne[1];
  8634. const uint32_t IW = src0->ne[0];
  8635. const uint32_t N = dst->ne[3];
  8636. const uint32_t OC = dst->ne[2];
  8637. const uint32_t OH = dst->ne[1];
  8638. const uint32_t OW = dst->ne[0];
  8639. const uint32_t parallel_elements = N * OC * OH * OW;
  8640. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  8641. IW, IH, OW, OH, OC,
  8642. parallel_elements,
  8643. op,
  8644. k0, k1, s0, s1, p0, p1,
  8645. });
  8646. }
  8647. static void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8648. const ggml_tensor * src1, ggml_tensor * dst) {
  8649. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8650. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8651. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8652. GGML_TENSOR_BINARY_OP_LOCALS
  8653. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8654. GGML_ASSERT(nb10 == sizeof(float));
  8655. GGML_ASSERT(nb0 == sizeof(float));
  8656. vk_op_conv2d_push_constants p{};
  8657. p.Cout = static_cast<uint32_t>(ne03);
  8658. p.Cin = static_cast<uint32_t>(ne02);
  8659. p.N = static_cast<uint32_t>(ne13);
  8660. p.KW = static_cast<uint32_t>(ne00);
  8661. p.KH = static_cast<uint32_t>(ne01);
  8662. p.W = static_cast<uint32_t>(ne10);
  8663. p.H = static_cast<uint32_t>(ne11);
  8664. p.OW = static_cast<uint32_t>(ne0);
  8665. p.OH = static_cast<uint32_t>(ne1);
  8666. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8667. p.s1 = static_cast<uint32_t>(dst->op_params[1]);
  8668. p.p0 = static_cast<uint32_t>(dst->op_params[2]);
  8669. p.p1 = static_cast<uint32_t>(dst->op_params[3]);
  8670. p.d0 = static_cast<uint32_t>(dst->op_params[4]);
  8671. p.d1 = static_cast<uint32_t>(dst->op_params[5]);
  8672. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8673. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8674. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  8675. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8676. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  8677. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  8678. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8679. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  8680. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  8681. GGML_ASSERT(ne03 == ne2);
  8682. GGML_ASSERT(ne02 == ne12);
  8683. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D, std::move(p));
  8684. }
  8685. static void ggml_vk_conv_transpose_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8686. const ggml_tensor * src1, ggml_tensor * dst) {
  8687. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8688. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8689. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8690. GGML_TENSOR_BINARY_OP_LOCALS
  8691. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8692. GGML_ASSERT(nb10 == sizeof(float));
  8693. GGML_ASSERT(nb0 == sizeof(float));
  8694. vk_op_conv_transpose_2d_push_constants p{};
  8695. p.Cout = static_cast<uint32_t>(ne02);
  8696. p.Cin = static_cast<uint32_t>(ne03);
  8697. p.N = static_cast<uint32_t>(ne13);
  8698. p.KW = static_cast<uint32_t>(ne00);
  8699. p.KH = static_cast<uint32_t>(ne01);
  8700. p.W = static_cast<uint32_t>(ne10);
  8701. p.H = static_cast<uint32_t>(ne11);
  8702. p.OW = static_cast<uint32_t>(ne0);
  8703. p.OH = static_cast<uint32_t>(ne1);
  8704. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8705. p.s1 = static_cast<uint32_t>(dst->op_params[0]);
  8706. p.p0 = 0;
  8707. p.p1 = 0;
  8708. p.d0 = 1;
  8709. p.d1 = 1;
  8710. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8711. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8712. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  8713. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8714. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  8715. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  8716. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8717. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  8718. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  8719. GGML_ASSERT(ne02 == ne2);
  8720. GGML_ASSERT(ne03 == ne12);
  8721. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_2D, std::move(p));
  8722. }
  8723. 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) {
  8724. vk_op_conv2d_dw_push_constants p{};
  8725. p.ne = ggml_nelements(dst);
  8726. p.channels = dst->ne[2];
  8727. p.batches = dst->ne[3];
  8728. p.dst_w = dst->ne[0];
  8729. p.dst_h = dst->ne[1];
  8730. p.src_w = src1->ne[0];
  8731. p.src_h = src1->ne[1];
  8732. p.knl_w = src0->ne[0];
  8733. p.knl_h = src0->ne[1];
  8734. p.stride_x = dst->op_params[0];
  8735. p.stride_y = dst->op_params[1];
  8736. p.pad_x = dst->op_params[2];
  8737. p.pad_y = dst->op_params[3];
  8738. p.dilation_x = dst->op_params[4];
  8739. p.dilation_y = dst->op_params[5];
  8740. GGML_ASSERT(src0->ne[3] == p.channels);
  8741. GGML_ASSERT(src1->ne[3] == p.batches);
  8742. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p));
  8743. }
  8744. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8745. const float * op_params = (const float *)dst->op_params;
  8746. 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 });
  8747. }
  8748. #ifdef GGML_VULKAN_RUN_TESTS
  8749. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  8750. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  8751. return;
  8752. }
  8753. i0 = std::max(i0, 5);
  8754. i1 = std::max(i1, 5);
  8755. i2 = std::max(i2, 0);
  8756. fprintf(stderr, " ");
  8757. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8758. fprintf(stderr, "%7d ", idx1);
  8759. }
  8760. fprintf(stderr, "\n");
  8761. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  8762. fprintf(stderr, "%7d: ", idx0);
  8763. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8764. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  8765. float val;
  8766. if (type == GGML_TYPE_F32) {
  8767. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  8768. } else if (type == GGML_TYPE_F16) {
  8769. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  8770. } else {
  8771. GGML_ABORT("fatal error");
  8772. }
  8773. fprintf(stderr, "% 7.2f ", val);
  8774. } else {
  8775. fprintf(stderr, " ");
  8776. }
  8777. }
  8778. fprintf(stderr, "\n");
  8779. }
  8780. }
  8781. template <typename X_TYPE, typename Y_TYPE>
  8782. 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) {
  8783. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  8784. const size_t x_ne = m * k * batch;
  8785. const size_t y_ne = k * n * batch;
  8786. const size_t d_ne = m * n * batch;
  8787. vk_pipeline p;
  8788. std::string shname;
  8789. if (shader_size == 0) {
  8790. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8791. p = ctx->device->pipeline_matmul_f32->a_s;
  8792. shname = "F32_ALIGNED_S";
  8793. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8794. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  8795. shname = "F32_F16_ALIGNED_S";
  8796. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8797. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  8798. shname = "F16_F32_ALIGNED_S";
  8799. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8800. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  8801. shname = "F16_ALIGNED_S";
  8802. } else {
  8803. GGML_ABORT("fatal error");
  8804. }
  8805. } else if (shader_size == 1) {
  8806. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8807. p = ctx->device->pipeline_matmul_f32->a_m;
  8808. shname = "F32_ALIGNED_M";
  8809. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8810. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  8811. shname = "F32_F16_ALIGNED_M";
  8812. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8813. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  8814. shname = "F16_F32_ALIGNED_M";
  8815. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8816. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  8817. shname = "F16_ALIGNED_M";
  8818. } else {
  8819. GGML_ABORT("fatal error");
  8820. }
  8821. } else if (shader_size == 2) {
  8822. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8823. p = ctx->device->pipeline_matmul_f32->a_l;
  8824. shname = "F32_ALIGNED_L";
  8825. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8826. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  8827. shname = "F32_F16_ALIGNED_L";
  8828. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8829. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  8830. shname = "F16_F32_ALIGNED_L";
  8831. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8832. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  8833. shname = "F16_ALIGNED_L";
  8834. } else {
  8835. GGML_ABORT("fatal error");
  8836. }
  8837. } else {
  8838. GGML_ASSERT(0);
  8839. }
  8840. const size_t kpad = ggml_vk_align_size(k, p->align);
  8841. if (k != kpad) {
  8842. if (shader_size == 0) {
  8843. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8844. p = ctx->device->pipeline_matmul_f32->s;
  8845. shname = "F32_S";
  8846. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8847. p = ctx->device->pipeline_matmul_f32_f16->s;
  8848. shname = "F32_F16_S";
  8849. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8850. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  8851. shname = "F16_F32_S";
  8852. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8853. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  8854. shname = "F16_S";
  8855. }
  8856. } else if (shader_size == 1) {
  8857. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8858. p = ctx->device->pipeline_matmul_f32->m;
  8859. shname = "F32_M";
  8860. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8861. p = ctx->device->pipeline_matmul_f32_f16->m;
  8862. shname = "F32_F16_M";
  8863. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8864. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  8865. shname = "F16_F32_M";
  8866. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8867. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  8868. shname = "F16_M";
  8869. }
  8870. } else if (shader_size == 2) {
  8871. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8872. p = ctx->device->pipeline_matmul_f32->l;
  8873. shname = "F32_L";
  8874. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8875. p = ctx->device->pipeline_matmul_f32_f16->l;
  8876. shname = "F32_F16_L";
  8877. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8878. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  8879. shname = "F16_F32_L";
  8880. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8881. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  8882. shname = "F16_L";
  8883. }
  8884. }
  8885. }
  8886. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  8887. if (split_k > 1) {
  8888. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  8889. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  8890. // Resize buffer
  8891. if (ctx->prealloc_split_k != nullptr) {
  8892. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  8893. }
  8894. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8895. }
  8896. }
  8897. ggml_pipeline_allocate_descriptor_sets(ctx);
  8898. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8899. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8900. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8901. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  8902. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  8903. float* d = (float *) malloc(sizeof(float) * d_ne);
  8904. for (size_t i = 0; i < x_ne; i++) {
  8905. if (std::is_same<float, X_TYPE>()) {
  8906. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  8907. // x[i] = 1.0f;
  8908. // x[i] = i + 1;
  8909. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  8910. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  8911. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  8912. // x[i] = ggml_fp32_to_fp16(1.0f);
  8913. // x[i] = ggml_fp32_to_fp16(i + 1);
  8914. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  8915. } else {
  8916. GGML_ABORT("fatal error");
  8917. }
  8918. }
  8919. for (size_t i = 0; i < y_ne; i++) {
  8920. if (std::is_same<float, Y_TYPE>()) {
  8921. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  8922. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  8923. // y[i] = i + 1;
  8924. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8925. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  8926. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  8927. // y[i] = ggml_fp32_to_fp16(i + 1);
  8928. } else {
  8929. GGML_ABORT("fatal error");
  8930. }
  8931. }
  8932. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  8933. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  8934. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  8935. ggml_vk_ctx_begin(ctx->device, subctx);
  8936. for (size_t i = 0; i < num_it; i++) {
  8937. ggml_vk_matmul(
  8938. 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),
  8939. m, n, k,
  8940. k, k, m, k*m, k*n, m*n,
  8941. split_k, batch, batch, batch, 1, 1, n
  8942. );
  8943. }
  8944. ggml_vk_ctx_end(subctx);
  8945. auto begin = std::chrono::high_resolution_clock::now();
  8946. ggml_vk_submit(subctx, ctx->fence);
  8947. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  8948. ctx->device->device.resetFences({ ctx->fence });
  8949. ggml_vk_queue_command_pools_cleanup(ctx->device);
  8950. auto end = std::chrono::high_resolution_clock::now();
  8951. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  8952. // copy dst to host
  8953. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  8954. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  8955. ggml_init_params iparams = {
  8956. /*.mem_size =*/ 1024*1024*1024,
  8957. /*.mem_buffer =*/ NULL,
  8958. /*.no_alloc =*/ true,
  8959. };
  8960. ggml_context * ggml_ctx = ggml_init(iparams);
  8961. ggml_type src0_type;
  8962. ggml_type src1_type;
  8963. if (std::is_same<float, X_TYPE>()) {
  8964. src0_type = GGML_TYPE_F32;
  8965. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  8966. src0_type = GGML_TYPE_F16;
  8967. } else {
  8968. GGML_ABORT("fatal error");
  8969. }
  8970. if (std::is_same<float, Y_TYPE>()) {
  8971. src1_type = GGML_TYPE_F32;
  8972. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8973. src1_type = GGML_TYPE_F16;
  8974. } else {
  8975. GGML_ABORT("fatal error");
  8976. }
  8977. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  8978. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  8979. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  8980. src0_ggml->data = x;
  8981. src1_ggml->data = y;
  8982. tensor_ggml->data = d_chk;
  8983. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  8984. ggml_build_forward_expand(cgraph, tensor_ggml);
  8985. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  8986. ggml_free(ggml_ctx);
  8987. double avg_err = 0.0;
  8988. int first_err_n = -1;
  8989. int first_err_m = -1;
  8990. int first_err_b = -1;
  8991. for (size_t i = 0; i < m*n*batch; i++) {
  8992. double err = std::fabs(d[i] - d_chk[i]);
  8993. avg_err += err;
  8994. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  8995. first_err_b = i / (m * n);
  8996. first_err_n = (i % (m * n)) / m;
  8997. first_err_m = (i % (m * n)) % m;
  8998. }
  8999. }
  9000. avg_err /= m * n;
  9001. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9002. 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;
  9003. if (avg_err > 0.1 || std::isnan(avg_err)) {
  9004. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9005. std::cerr << "Actual result: " << std::endl << std::endl;
  9006. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9007. std::cerr << "Expected result: " << std::endl << std::endl;
  9008. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9009. if (split_k > 1) {
  9010. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9011. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9012. std::cerr << "d_buf0: " << std::endl << std::endl;
  9013. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9014. std::cerr << "d_buf1: " << std::endl << std::endl;
  9015. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9016. std::cerr << "d_buf2: " << std::endl << std::endl;
  9017. 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);
  9018. std::cerr << "d_buf3: " << std::endl << std::endl;
  9019. 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);
  9020. free(split_k_buf);
  9021. }
  9022. }
  9023. free(d_chk);
  9024. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  9025. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  9026. ggml_vk_destroy_buffer(d_X);
  9027. ggml_vk_destroy_buffer(d_Y);
  9028. ggml_vk_destroy_buffer(d_D);
  9029. free(x);
  9030. free(y);
  9031. free(d);
  9032. }
  9033. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  9034. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  9035. return;
  9036. }
  9037. i0 = std::max(i0, 5);
  9038. i1 = std::max(i1, 5);
  9039. i2 = std::max(i2, 0);
  9040. i3 = std::max(i3, 0);
  9041. fprintf(stderr, " ");
  9042. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9043. fprintf(stderr, "%7d ", idx1);
  9044. }
  9045. fprintf(stderr, "\n");
  9046. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9047. fprintf(stderr, "%7d: ", idx0);
  9048. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9049. 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]) {
  9050. float val;
  9051. if (tensor->type == GGML_TYPE_F32) {
  9052. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  9053. } else if (tensor->type == GGML_TYPE_F16) {
  9054. 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]));
  9055. } else {
  9056. GGML_ABORT("fatal error");
  9057. }
  9058. fprintf(stderr, "% 7.2f ", val);
  9059. } else {
  9060. fprintf(stderr, " ");
  9061. }
  9062. }
  9063. fprintf(stderr, "\n");
  9064. }
  9065. }
  9066. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  9067. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  9068. }
  9069. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  9070. if (quant == GGML_TYPE_F32) {
  9071. memcpy(to, from, sizeof(float) * ne);
  9072. return;
  9073. }
  9074. const auto * tt = ggml_get_type_traits(quant);
  9075. ggml_to_float_t dequant_fn = tt->to_float;
  9076. dequant_fn(from, to, ne);
  9077. }
  9078. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9079. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  9080. const size_t x_sz = sizeof(float) * ne;
  9081. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  9082. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9083. float * x = (float *) malloc(x_sz);
  9084. void * qx = malloc(qx_sz);
  9085. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9086. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9087. float * x_ref = (float *) malloc(x_sz);
  9088. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  9089. for (size_t i = 0; i < ne; i++) {
  9090. x[i] = rand() / (float)RAND_MAX;
  9091. }
  9092. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  9093. ggml_vk_quantize_data(x, qx, ne, quant);
  9094. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  9095. ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9096. ggml_pipeline_allocate_descriptor_sets(ctx);
  9097. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9098. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9099. ggml_vk_ctx_begin(ctx->device, subctx);
  9100. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  9101. 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});
  9102. ggml_vk_ctx_end(subctx);
  9103. auto begin = std::chrono::high_resolution_clock::now();
  9104. ggml_vk_submit(subctx, ctx->fence);
  9105. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9106. ctx->device->device.resetFences({ ctx->fence });
  9107. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9108. auto end = std::chrono::high_resolution_clock::now();
  9109. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9110. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  9111. int first_err = -1;
  9112. double avg_err = 0.0;
  9113. for (size_t i = 0; i < ne; i++) {
  9114. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  9115. avg_err += error;
  9116. if (first_err < 0 && error > 0.05) {
  9117. first_err = i;
  9118. }
  9119. }
  9120. avg_err /= ne;
  9121. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  9122. if (avg_err > 0.1) {
  9123. std::cerr << "first_error = " << first_err << std::endl;
  9124. std::cerr << "Actual result: " << std::endl << std::endl;
  9125. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9126. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  9127. }
  9128. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  9129. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9130. std::cerr << x_ref[i] << ", ";
  9131. }
  9132. std::cerr << std::endl;
  9133. }
  9134. ggml_vk_destroy_buffer(x_buf);
  9135. ggml_vk_destroy_buffer(qx_buf);
  9136. free(x);
  9137. free(qx);
  9138. free(x_ref);
  9139. free(x_chk);
  9140. }
  9141. // This does not work without ggml q8_1 quantization support
  9142. //
  9143. // typedef uint16_t ggml_half;
  9144. // typedef uint32_t ggml_half2;
  9145. //
  9146. // #define QK8_1 32
  9147. // typedef struct {
  9148. // union {
  9149. // struct {
  9150. // ggml_half d; // delta
  9151. // ggml_half s; // d * sum(qs[i])
  9152. // } GGML_COMMON_AGGR_S;
  9153. // ggml_half2 ds;
  9154. // } GGML_COMMON_AGGR_U;
  9155. // int8_t qs[QK8_1]; // quants
  9156. // } block_q8_1;
  9157. //
  9158. // static void ggml_vk_test_quantize(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9159. // VK_LOG_DEBUG("ggml_vk_test_quantize(" << ne << ")");
  9160. // GGML_ASSERT(quant == GGML_TYPE_Q8_1);
  9161. //
  9162. // const size_t x_sz = sizeof(float) * ne;
  9163. // const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9164. // float * x = (float *) malloc(x_sz);
  9165. // block_q8_1 * qx = (block_q8_1 *)malloc(qx_sz);
  9166. // block_q8_1 * qx_res = (block_q8_1 *)malloc(qx_sz);
  9167. // vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9168. // vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9169. //
  9170. // for (size_t i = 0; i < ne; i++) {
  9171. // x[i] = rand() / (float)RAND_MAX;
  9172. // }
  9173. //
  9174. // vk_pipeline p = ggml_vk_get_quantize_pipeline(ctx, quant);
  9175. //
  9176. // ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9177. //
  9178. // ggml_pipeline_allocate_descriptor_sets(ctx);
  9179. //
  9180. // ggml_vk_buffer_write(x_buf, 0, x, x_sz);
  9181. //
  9182. // vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9183. // ggml_vk_ctx_begin(ctx->device, subctx);
  9184. // ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, x_buf), ggml_vk_subbuffer(ctx, qx_buf), ne);
  9185. // ggml_vk_ctx_end(subctx);
  9186. //
  9187. // auto begin = std::chrono::high_resolution_clock::now();
  9188. //
  9189. // ggml_vk_submit(subctx, ctx->fence);
  9190. // VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_quantize waitForFences");
  9191. // ctx->device->device.resetFences({ ctx->fence });
  9192. // ggml_vk_queue_command_pools_cleanup(ctx->device);
  9193. //
  9194. // auto end = std::chrono::high_resolution_clock::now();
  9195. //
  9196. // double ms_quant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9197. // ggml_vk_buffer_read(qx_buf, 0, qx, qx_sz);
  9198. //
  9199. // ggml_vk_quantize_data(x, qx_res, ne, quant);
  9200. //
  9201. // int first_err = -1;
  9202. //
  9203. // for (size_t i = 0; i < ne / 32; i++) {
  9204. // 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));
  9205. //
  9206. // if (first_err < 0 && error > 0.1) {
  9207. // first_err = i;
  9208. // }
  9209. //
  9210. // 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));
  9211. //
  9212. // if (first_err < 0 && error > 0.1) {
  9213. // first_err = i;
  9214. // }
  9215. //
  9216. // for (size_t j = 0; j < 32; j++) {
  9217. // uint64_t error = std::abs(qx_res[i].qs[j] - qx[i].qs[j]);
  9218. //
  9219. // if (first_err < 0 && error > 1) {
  9220. // first_err = i;
  9221. // }
  9222. // }
  9223. // }
  9224. //
  9225. // std::cerr << "TEST QUANTIZE " << ggml_type_name(quant) << " time=" << ms_quant << "ms " << (first_err == -1 ? "CORRECT" : "INCORRECT") << std::endl;
  9226. //
  9227. // if (first_err != -1) {
  9228. // std::cerr << "first_error = " << first_err << std::endl;
  9229. // std::cerr << "Actual result: " << std::endl << std::endl;
  9230. // 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) << " ";
  9231. // for (size_t j = 0; j < 32; j++) {
  9232. // std::cout << " qs" << j << "=" << (uint32_t)qx[first_err].qs[j] << " ";
  9233. // }
  9234. // std::cerr << std::endl << std::endl << "Expected result: " << std::endl << std::endl;
  9235. // 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) << " ";
  9236. // for (size_t j = 0; j < 32; j++) {
  9237. // std::cout << " qs" << j << "=" << (uint32_t)qx_res[first_err].qs[j] << " ";
  9238. // }
  9239. // std::cerr << std::endl;
  9240. // }
  9241. //
  9242. // ggml_vk_destroy_buffer(x_buf);
  9243. // ggml_vk_destroy_buffer(qx_buf);
  9244. //
  9245. // free(x);
  9246. // free(qx);
  9247. // free(qx_res);
  9248. // }
  9249. 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) {
  9250. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  9251. const size_t x_ne = m * k * batch;
  9252. const size_t y_ne = k * n * batch;
  9253. const size_t d_ne = m * n * batch;
  9254. vk_matmul_pipeline2 * pipelines;
  9255. if (mmq) {
  9256. pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1;
  9257. } else {
  9258. pipelines = ctx->device->pipeline_dequant_mul_mat_mat;
  9259. }
  9260. const bool fp16acc = ctx->device->fp16;
  9261. vk_pipeline p;
  9262. std::string shname;
  9263. if (shader_size == 0) {
  9264. p = fp16acc ? pipelines[quant].f16acc->a_s : pipelines[quant].f32acc->a_s;
  9265. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  9266. } else if (shader_size == 1) {
  9267. p = fp16acc ? pipelines[quant].f16acc->a_m : pipelines[quant].f32acc->a_m;
  9268. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  9269. } else if (shader_size == 2) {
  9270. p = fp16acc ? pipelines[quant].f16acc->a_l : pipelines[quant].f32acc->a_l;
  9271. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  9272. } else {
  9273. GGML_ASSERT(0);
  9274. }
  9275. const size_t kpad = mmq ? 0 : ggml_vk_align_size(k, p->align);
  9276. if (mmq || k != kpad) {
  9277. if (shader_size == 0) {
  9278. p = fp16acc ? pipelines[quant].f16acc->s : pipelines[quant].f32acc->s;
  9279. shname = std::string(ggml_type_name(quant)) + "_S";
  9280. } else if (shader_size == 1) {
  9281. p = fp16acc ? pipelines[quant].f16acc->m : pipelines[quant].f32acc->m;
  9282. shname = std::string(ggml_type_name(quant)) + "_M";
  9283. } else if (shader_size == 2) {
  9284. p = fp16acc ? pipelines[quant].f16acc->l : pipelines[quant].f32acc->l;
  9285. shname = std::string(ggml_type_name(quant)) + "_L";
  9286. } else {
  9287. GGML_ASSERT(0);
  9288. }
  9289. }
  9290. if (p == nullptr) {
  9291. std::cerr << "error: no pipeline for ggml_vk_test_dequant_matmul " << ggml_type_name(quant) << std::endl;
  9292. return;
  9293. }
  9294. const size_t x_sz = sizeof(float) * x_ne;
  9295. const size_t y_sz = sizeof(float) * y_ne;
  9296. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9297. const size_t qy_sz = mmq ? y_ne * ggml_type_size(GGML_TYPE_Q8_1)/ggml_blck_size(GGML_TYPE_Q8_1) : y_sz;
  9298. const size_t d_sz = sizeof(float) * d_ne;
  9299. float * x = (float *) malloc(x_sz);
  9300. float * y = (float *) malloc(y_sz);
  9301. void * qx = malloc(qx_sz);
  9302. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9303. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9304. vk_buffer qy_buf = ggml_vk_create_buffer_check(ctx->device, qy_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9305. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9306. float * d = (float *) malloc(d_sz);
  9307. float * d_chk = (float *) malloc(d_sz);
  9308. for (size_t i = 0; i < x_ne; i++) {
  9309. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9310. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9311. // x[i] = i % k;
  9312. }
  9313. ggml_vk_quantize_data(x, qx, x_ne, quant);
  9314. for (size_t i = 0; i < y_ne; i++) {
  9315. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9316. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9317. // y[i] = i % k;
  9318. }
  9319. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9320. if (split_k > 1) {
  9321. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9322. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9323. // Resize buffer
  9324. if (ctx->prealloc_split_k != nullptr) {
  9325. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9326. }
  9327. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9328. }
  9329. }
  9330. if (mmq) {
  9331. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_quantize_q8_1, num_it);
  9332. }
  9333. ggml_pipeline_allocate_descriptor_sets(ctx);
  9334. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9335. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  9336. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9337. ggml_vk_ctx_begin(ctx->device, subctx);
  9338. if (mmq) {
  9339. for (size_t i = 0; i < num_it; i++) {
  9340. ggml_vk_quantize_q8_1(ctx, subctx, { y_buf, 0, y_sz }, { qy_buf, 0, qy_sz }, y_ne);
  9341. ggml_vk_matmul(
  9342. 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 },
  9343. m, n, k,
  9344. k, k, m, k*m, k*n, m*n,
  9345. split_k, batch, batch, batch, 1, 1, n
  9346. );
  9347. }
  9348. } else {
  9349. for (size_t i = 0; i < num_it; i++) {
  9350. ggml_vk_matmul(
  9351. 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 },
  9352. m, n, k,
  9353. k, k, m, k*m, k*n, m*n,
  9354. split_k, batch, batch, batch, 1, 1, n
  9355. );
  9356. }
  9357. }
  9358. ggml_vk_ctx_end(subctx);
  9359. auto begin = std::chrono::high_resolution_clock::now();
  9360. ggml_vk_submit(subctx, ctx->fence);
  9361. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9362. ctx->device->device.resetFences({ ctx->fence });
  9363. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9364. auto end = std::chrono::high_resolution_clock::now();
  9365. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9366. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  9367. ggml_init_params iparams = {
  9368. /*.mem_size =*/ 1024*1024*1024,
  9369. /*.mem_buffer =*/ NULL,
  9370. /*.no_alloc =*/ true,
  9371. };
  9372. ggml_context * ggml_ctx = ggml_init(iparams);
  9373. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  9374. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  9375. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9376. src0_ggml->data = qx;
  9377. src1_ggml->data = y;
  9378. tensor_ggml->data = d_chk;
  9379. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9380. ggml_build_forward_expand(cgraph, tensor_ggml);
  9381. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9382. ggml_free(ggml_ctx);
  9383. double avg_err = 0.0;
  9384. int first_err_n = -1;
  9385. int first_err_m = -1;
  9386. int first_err_b = -1;
  9387. for (size_t i = 0; i < m*n*batch; i++) {
  9388. double err = std::fabs(d[i] - d_chk[i]);
  9389. avg_err += err;
  9390. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9391. first_err_b = i / (m * n);
  9392. first_err_n = (i % (m * n)) / m;
  9393. first_err_m = (i % (m * n)) % m;
  9394. }
  9395. }
  9396. avg_err /= m * n;
  9397. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9398. std::cerr << "TEST dequant matmul " << shname;
  9399. if (mmq) {
  9400. std::cerr << " mmq";
  9401. }
  9402. 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;
  9403. if (avg_err > 0.01 || std::isnan(avg_err)) {
  9404. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9405. std::cerr << "Actual result: " << std::endl << std::endl;
  9406. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9407. std::cerr << std::endl;
  9408. std::cerr << "Expected result: " << std::endl << std::endl;
  9409. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9410. std::cerr << "src0: " << std::endl << std::endl;
  9411. ggml_vk_print_matrix_area(x, GGML_TYPE_F32, k, m, first_err_m, first_err_n, first_err_b);
  9412. std::cerr << std::endl;
  9413. std::cerr << "src1: " << std::endl << std::endl;
  9414. ggml_vk_print_matrix_area(y, GGML_TYPE_F32, k, n, first_err_m, first_err_n, first_err_b);
  9415. if (split_k > 1) {
  9416. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9417. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9418. std::cerr << "d_buf0: " << std::endl << std::endl;
  9419. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9420. std::cerr << "d_buf1: " << std::endl << std::endl;
  9421. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9422. std::cerr << "d_buf2: " << std::endl << std::endl;
  9423. 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);
  9424. std::cerr << "d_buf3: " << std::endl << std::endl;
  9425. 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);
  9426. free(split_k_buf);
  9427. }
  9428. }
  9429. ggml_vk_destroy_buffer(qx_buf);
  9430. ggml_vk_destroy_buffer(y_buf);
  9431. ggml_vk_destroy_buffer(qy_buf);
  9432. ggml_vk_destroy_buffer(d_buf);
  9433. free(x);
  9434. free(qx);
  9435. free(y);
  9436. free(d);
  9437. free(d_chk);
  9438. }
  9439. #endif
  9440. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx) {
  9441. #if defined(GGML_VULKAN_RUN_TESTS)
  9442. const std::vector<size_t> vals {
  9443. 512, 512, 128,
  9444. 128, 512, 512,
  9445. 4096, 512, 4096,
  9446. 11008, 512, 4096,
  9447. 4096, 512, 11008,
  9448. 32000, 512, 4096,
  9449. 8, 8, 8,
  9450. 100, 46, 576,
  9451. 623, 111, 128,
  9452. 100, 46, 558,
  9453. 512, 1, 256,
  9454. 128, 110, 622,
  9455. 511, 511, 127,
  9456. 511, 511, 7,
  9457. 511, 511, 17,
  9458. 49, 49, 128,
  9459. 128, 49, 49,
  9460. 4096, 49, 4096,
  9461. };
  9462. const size_t num_it = 100;
  9463. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9464. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9465. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9466. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true);
  9467. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true);
  9468. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true);
  9469. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0);
  9470. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0);
  9471. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0);
  9472. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true);
  9473. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true);
  9474. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true);
  9475. abort();
  9476. for (size_t i = 0; i < vals.size(); i += 3) {
  9477. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  9478. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  9479. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  9480. std::cerr << '\n';
  9481. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  9482. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  9483. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  9484. std::cerr << '\n';
  9485. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  9486. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  9487. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  9488. std::cerr << '\n' << std::endl;
  9489. if (vals[i + 2] % 32 == 0) {
  9490. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9491. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9492. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9493. std::cerr << '\n';
  9494. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  9495. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  9496. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  9497. std::cerr << '\n';
  9498. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  9499. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  9500. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  9501. std::cerr << '\n' << std::endl;
  9502. }
  9503. if (vals[i + 2] % 256 == 0) {
  9504. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  9505. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  9506. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  9507. std::cerr << '\n';
  9508. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  9509. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  9510. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  9511. std::cerr << '\n';
  9512. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  9513. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  9514. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  9515. std::cerr << '\n' << std::endl;
  9516. }
  9517. }
  9518. GGML_ABORT("fatal error");
  9519. #endif
  9520. if (subctx) {
  9521. // Submit and wait for any pending work before reallocating the buffers
  9522. ggml_vk_ctx_end(subctx);
  9523. ggml_vk_submit(subctx, {});
  9524. ctx->submit_pending = true;
  9525. ggml_vk_synchronize(ctx);
  9526. ggml_vk_ctx_begin(ctx->device, subctx);
  9527. }
  9528. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  9529. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  9530. // Resize buffer
  9531. if (ctx->prealloc_x != nullptr) {
  9532. ggml_vk_destroy_buffer(ctx->prealloc_x);
  9533. }
  9534. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  9535. }
  9536. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  9537. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  9538. // Resize buffer
  9539. if (ctx->prealloc_y != nullptr) {
  9540. ggml_vk_destroy_buffer(ctx->prealloc_y);
  9541. }
  9542. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  9543. }
  9544. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  9545. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  9546. // Resize buffer
  9547. if (ctx->prealloc_split_k != nullptr) {
  9548. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9549. }
  9550. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  9551. }
  9552. 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)) {
  9553. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")");
  9554. // Resize buffer
  9555. if (ctx->prealloc_add_rms_partials != nullptr) {
  9556. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  9557. }
  9558. ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials);
  9559. }
  9560. }
  9561. static bool ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_cgraph * cgraph, ggml_tensor* tensor, int tensor_idx, bool almost_ready);
  9562. // Returns true if node has enqueued work into the queue, false otherwise
  9563. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  9564. 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){
  9565. ggml_tensor * node = cgraph->nodes[node_idx];
  9566. if (ggml_is_empty(node) || !node->buffer) {
  9567. return false;
  9568. }
  9569. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  9570. ctx->semaphore_idx = 0;
  9571. ggml_tensor * src0 = node->src[0];
  9572. ggml_tensor * src1 = node->src[1];
  9573. ggml_tensor * src2 = node->src[2];
  9574. ggml_tensor * src3 = node->src[3];
  9575. switch (node->op) {
  9576. // Return on empty ops to avoid generating a compute_ctx and setting exit_tensor
  9577. case GGML_OP_RESHAPE:
  9578. case GGML_OP_VIEW:
  9579. case GGML_OP_PERMUTE:
  9580. case GGML_OP_TRANSPOSE:
  9581. case GGML_OP_NONE:
  9582. return false;
  9583. case GGML_OP_UNARY:
  9584. switch (ggml_get_unary_op(node)) {
  9585. case GGML_UNARY_OP_EXP:
  9586. case GGML_UNARY_OP_SILU:
  9587. case GGML_UNARY_OP_GELU:
  9588. case GGML_UNARY_OP_GELU_ERF:
  9589. case GGML_UNARY_OP_GELU_QUICK:
  9590. case GGML_UNARY_OP_RELU:
  9591. case GGML_UNARY_OP_NEG:
  9592. case GGML_UNARY_OP_TANH:
  9593. case GGML_UNARY_OP_SIGMOID:
  9594. case GGML_UNARY_OP_HARDSIGMOID:
  9595. case GGML_UNARY_OP_HARDSWISH:
  9596. case GGML_UNARY_OP_ABS:
  9597. break;
  9598. default:
  9599. return false;
  9600. }
  9601. break;
  9602. case GGML_OP_GLU:
  9603. switch (ggml_get_glu_op(node)) {
  9604. case GGML_GLU_OP_GEGLU:
  9605. case GGML_GLU_OP_REGLU:
  9606. case GGML_GLU_OP_SWIGLU:
  9607. case GGML_GLU_OP_SWIGLU_OAI:
  9608. case GGML_GLU_OP_GEGLU_ERF:
  9609. case GGML_GLU_OP_GEGLU_QUICK:
  9610. break;
  9611. default:
  9612. return false;
  9613. }
  9614. break;
  9615. case GGML_OP_ADD:
  9616. {
  9617. int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops;
  9618. if (next_node_idx < cgraph->n_nodes &&
  9619. cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM &&
  9620. cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] &&
  9621. ggml_nrows(cgraph->nodes[next_node_idx]) == 1 &&
  9622. ctx->device->add_rms_fusion) {
  9623. uint32_t size = ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]);
  9624. ctx->do_add_rms_partials_offset_calculation = true;
  9625. if (ctx->prealloc_size_add_rms_partials_offset + size <= ctx->prealloc_size_add_rms_partials) {
  9626. ctx->do_add_rms_partials = true;
  9627. }
  9628. }
  9629. } break;
  9630. case GGML_OP_REPEAT:
  9631. case GGML_OP_REPEAT_BACK:
  9632. case GGML_OP_GET_ROWS:
  9633. case GGML_OP_ADD_ID:
  9634. case GGML_OP_ACC:
  9635. case GGML_OP_SUB:
  9636. case GGML_OP_MUL:
  9637. case GGML_OP_DIV:
  9638. case GGML_OP_CONCAT:
  9639. case GGML_OP_UPSCALE:
  9640. case GGML_OP_SCALE:
  9641. case GGML_OP_SQR:
  9642. case GGML_OP_SQRT:
  9643. case GGML_OP_SIN:
  9644. case GGML_OP_COS:
  9645. case GGML_OP_LOG:
  9646. case GGML_OP_CLAMP:
  9647. case GGML_OP_PAD:
  9648. case GGML_OP_ROLL:
  9649. case GGML_OP_CPY:
  9650. case GGML_OP_SET_ROWS:
  9651. case GGML_OP_CONT:
  9652. case GGML_OP_DUP:
  9653. case GGML_OP_SILU_BACK:
  9654. case GGML_OP_NORM:
  9655. case GGML_OP_GROUP_NORM:
  9656. case GGML_OP_RMS_NORM:
  9657. case GGML_OP_RMS_NORM_BACK:
  9658. case GGML_OP_L2_NORM:
  9659. case GGML_OP_DIAG_MASK_INF:
  9660. case GGML_OP_SOFT_MAX:
  9661. case GGML_OP_SOFT_MAX_BACK:
  9662. case GGML_OP_ROPE:
  9663. case GGML_OP_ROPE_BACK:
  9664. case GGML_OP_MUL_MAT:
  9665. case GGML_OP_MUL_MAT_ID:
  9666. case GGML_OP_ARGSORT:
  9667. case GGML_OP_SUM:
  9668. case GGML_OP_SUM_ROWS:
  9669. case GGML_OP_MEAN:
  9670. case GGML_OP_ARGMAX:
  9671. case GGML_OP_COUNT_EQUAL:
  9672. case GGML_OP_IM2COL:
  9673. case GGML_OP_IM2COL_3D:
  9674. case GGML_OP_TIMESTEP_EMBEDDING:
  9675. case GGML_OP_CONV_TRANSPOSE_1D:
  9676. case GGML_OP_POOL_2D:
  9677. case GGML_OP_CONV_2D:
  9678. case GGML_OP_CONV_TRANSPOSE_2D:
  9679. case GGML_OP_CONV_2D_DW:
  9680. case GGML_OP_RWKV_WKV6:
  9681. case GGML_OP_RWKV_WKV7:
  9682. case GGML_OP_SSM_SCAN:
  9683. case GGML_OP_SSM_CONV:
  9684. case GGML_OP_LEAKY_RELU:
  9685. case GGML_OP_FLASH_ATTN_EXT:
  9686. case GGML_OP_OPT_STEP_ADAMW:
  9687. case GGML_OP_OPT_STEP_SGD:
  9688. break;
  9689. default:
  9690. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(node->op) << std::endl;
  9691. GGML_ABORT("fatal error");
  9692. }
  9693. vk_context compute_ctx;
  9694. if (ctx->compute_ctx.expired()) {
  9695. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9696. ctx->compute_ctx = compute_ctx;
  9697. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  9698. } else {
  9699. compute_ctx = ctx->compute_ctx.lock();
  9700. }
  9701. {
  9702. // This logic detects dependencies between modes in the graph and calls ggml_vk_sync_buffers
  9703. // to synchronize them. This handles most "normal" synchronization when computing the graph, and when
  9704. // there is no auxiliary memory use, it shouldn't be necessary to call ggml_vk_sync_buffers
  9705. // outside of this logic. When a node uses one of the prealloc buffers for something like
  9706. // dequantization or split_k, additional synchronization is needed between those passes.
  9707. bool need_sync = false;
  9708. // Check whether "node" requires synchronization. The node requires synchronization if it
  9709. // overlaps in memory with another unsynchronized node and at least one of them is a write.
  9710. // Destination nodes are checked against both the written/read lists. Source nodes are only
  9711. // checked against the written list. Two nodes overlap in memory if they come from the same
  9712. // buffer and the tensor or view ranges overlap.
  9713. auto const &overlaps_unsynced = [&](const ggml_tensor *node, const std::vector<const ggml_tensor *> &unsynced_nodes) -> bool {
  9714. if (unsynced_nodes.size() == 0) {
  9715. return false;
  9716. }
  9717. auto n_base = vk_tensor_offset(node) + node->view_offs;
  9718. auto n_size = ggml_nbytes(node);
  9719. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context;
  9720. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  9721. for (auto &other : unsynced_nodes) {
  9722. ggml_backend_vk_buffer_context * o_buf_ctx = (ggml_backend_vk_buffer_context *)other->buffer->context;
  9723. vk_buffer o_buf = o_buf_ctx->dev_buffer;
  9724. if (a_buf == o_buf) {
  9725. auto o_base = vk_tensor_offset(other) + other->view_offs;
  9726. auto o_size = ggml_nbytes(other);
  9727. if ((o_base <= n_base && n_base < o_base + o_size) ||
  9728. (n_base <= o_base && o_base < n_base + n_size)) {
  9729. return true;
  9730. }
  9731. }
  9732. }
  9733. return false;
  9734. };
  9735. // For all fused ops, check if the destination node or any of the source
  9736. // nodes require synchronization.
  9737. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) {
  9738. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  9739. // If the node actually writes to memory, then check if it needs to sync
  9740. if (ctx->fused_ops_write_mask & (1 << i)) {
  9741. if (overlaps_unsynced(cur_node, ctx->unsynced_nodes_read) || overlaps_unsynced(cur_node, ctx->unsynced_nodes_written)) {
  9742. need_sync = true;
  9743. break;
  9744. }
  9745. }
  9746. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  9747. if (!cur_node->src[j]) {
  9748. continue;
  9749. }
  9750. if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) {
  9751. need_sync = true;
  9752. break;
  9753. }
  9754. }
  9755. }
  9756. #define ENABLE_SYNC_LOGGING 0
  9757. if (need_sync) {
  9758. #if ENABLE_SYNC_LOGGING
  9759. std::cerr << "sync" << std::endl;
  9760. #endif
  9761. ctx->unsynced_nodes_written.clear();
  9762. ctx->unsynced_nodes_read.clear();
  9763. ggml_vk_sync_buffers(ctx, compute_ctx);
  9764. }
  9765. // Add all fused nodes to the unsynchronized lists.
  9766. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  9767. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  9768. // Multiple outputs could be written, e.g. in topk_moe. Add them all to the list.
  9769. if (ctx->fused_ops_write_mask & (1 << i)) {
  9770. ctx->unsynced_nodes_written.push_back(cur_node);
  9771. }
  9772. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  9773. if (!cur_node->src[j]) {
  9774. continue;
  9775. }
  9776. ctx->unsynced_nodes_read.push_back(cur_node->src[j]);
  9777. }
  9778. }
  9779. }
  9780. #if ENABLE_SYNC_LOGGING
  9781. for (int i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  9782. auto *n = cgraph->nodes[node_idx + i];
  9783. std::cerr << node_idx + i << " " << ggml_op_name(n->op) << " " << n->name;
  9784. if (n->op == GGML_OP_GLU) {
  9785. std::cerr << " " << ggml_glu_op_name(ggml_get_glu_op(n)) << " " << (n->src[1] ? "split" : "single") << " ";
  9786. }
  9787. if (n->op == GGML_OP_ROPE) {
  9788. const int mode = ((const int32_t *) n->op_params)[2];
  9789. std::cerr << " rope mode: " << mode;
  9790. }
  9791. std::cerr << std::endl;
  9792. }
  9793. #endif
  9794. switch (node->op) {
  9795. case GGML_OP_REPEAT:
  9796. ggml_vk_repeat(ctx, compute_ctx, src0, node);
  9797. break;
  9798. case GGML_OP_REPEAT_BACK:
  9799. ggml_vk_repeat_back(ctx, compute_ctx, src0, node);
  9800. break;
  9801. case GGML_OP_ACC:
  9802. ggml_vk_acc(ctx, compute_ctx, src0, src1, node);
  9803. break;
  9804. case GGML_OP_GET_ROWS:
  9805. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node);
  9806. break;
  9807. case GGML_OP_ADD:
  9808. if (ctx->num_additional_fused_ops) {
  9809. ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx);
  9810. } else {
  9811. ggml_vk_add(ctx, compute_ctx, src0, src1, node);
  9812. }
  9813. break;
  9814. case GGML_OP_SUB:
  9815. ggml_vk_sub(ctx, compute_ctx, src0, src1, node);
  9816. break;
  9817. case GGML_OP_MUL:
  9818. ggml_vk_mul(ctx, compute_ctx, src0, src1, node);
  9819. break;
  9820. case GGML_OP_DIV:
  9821. ggml_vk_div(ctx, compute_ctx, src0, src1, node);
  9822. break;
  9823. case GGML_OP_ADD_ID:
  9824. ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node);
  9825. break;
  9826. case GGML_OP_CONCAT:
  9827. ggml_vk_concat(ctx, compute_ctx, src0, src1, node);
  9828. break;
  9829. case GGML_OP_UPSCALE:
  9830. ggml_vk_upscale(ctx, compute_ctx, src0, node);
  9831. break;
  9832. case GGML_OP_SCALE:
  9833. ggml_vk_scale(ctx, compute_ctx, src0, node);
  9834. break;
  9835. case GGML_OP_SQR:
  9836. ggml_vk_sqr(ctx, compute_ctx, src0, node);
  9837. break;
  9838. case GGML_OP_SQRT:
  9839. ggml_vk_sqrt(ctx, compute_ctx, src0, node);
  9840. break;
  9841. case GGML_OP_SIN:
  9842. ggml_vk_sin(ctx, compute_ctx, src0, node);
  9843. break;
  9844. case GGML_OP_COS:
  9845. ggml_vk_cos(ctx, compute_ctx, src0, node);
  9846. break;
  9847. case GGML_OP_LOG:
  9848. ggml_vk_log(ctx, compute_ctx, src0, node);
  9849. break;
  9850. case GGML_OP_CLAMP:
  9851. ggml_vk_clamp(ctx, compute_ctx, src0, node);
  9852. break;
  9853. case GGML_OP_PAD:
  9854. ggml_vk_pad(ctx, compute_ctx, src0, node);
  9855. break;
  9856. case GGML_OP_ROLL:
  9857. ggml_vk_roll(ctx, compute_ctx, src0, node);
  9858. break;
  9859. case GGML_OP_CPY:
  9860. case GGML_OP_CONT:
  9861. case GGML_OP_DUP:
  9862. ggml_vk_cpy(ctx, compute_ctx, src0, node);
  9863. break;
  9864. case GGML_OP_SET_ROWS:
  9865. ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node);
  9866. break;
  9867. case GGML_OP_SILU_BACK:
  9868. ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node);
  9869. break;
  9870. case GGML_OP_NORM:
  9871. ggml_vk_norm(ctx, compute_ctx, src0, node);
  9872. break;
  9873. case GGML_OP_GROUP_NORM:
  9874. ggml_vk_group_norm(ctx, compute_ctx, src0, node);
  9875. break;
  9876. case GGML_OP_RMS_NORM:
  9877. ggml_vk_rms_norm(ctx, compute_ctx, cgraph, node_idx, (float *)node->op_params);
  9878. break;
  9879. case GGML_OP_RMS_NORM_BACK:
  9880. ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node);
  9881. break;
  9882. case GGML_OP_L2_NORM:
  9883. ggml_vk_l2_norm(ctx, compute_ctx, src0, node);
  9884. break;
  9885. case GGML_OP_UNARY:
  9886. switch (ggml_get_unary_op(node)) {
  9887. case GGML_UNARY_OP_EXP:
  9888. case GGML_UNARY_OP_SILU:
  9889. case GGML_UNARY_OP_GELU:
  9890. case GGML_UNARY_OP_GELU_ERF:
  9891. case GGML_UNARY_OP_GELU_QUICK:
  9892. case GGML_UNARY_OP_RELU:
  9893. case GGML_UNARY_OP_NEG:
  9894. case GGML_UNARY_OP_TANH:
  9895. case GGML_UNARY_OP_SIGMOID:
  9896. case GGML_UNARY_OP_HARDSIGMOID:
  9897. case GGML_UNARY_OP_HARDSWISH:
  9898. case GGML_UNARY_OP_ABS:
  9899. ggml_vk_unary(ctx, compute_ctx, src0, node);
  9900. break;
  9901. default:
  9902. return false;
  9903. }
  9904. break;
  9905. case GGML_OP_GLU:
  9906. switch (ggml_get_glu_op(node)) {
  9907. case GGML_GLU_OP_GEGLU:
  9908. case GGML_GLU_OP_REGLU:
  9909. case GGML_GLU_OP_SWIGLU:
  9910. case GGML_GLU_OP_SWIGLU_OAI:
  9911. case GGML_GLU_OP_GEGLU_ERF:
  9912. case GGML_GLU_OP_GEGLU_QUICK:
  9913. ggml_vk_glu(ctx, compute_ctx, src0, src1, node);
  9914. break;
  9915. default:
  9916. return false;
  9917. }
  9918. break;
  9919. case GGML_OP_DIAG_MASK_INF:
  9920. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node);
  9921. break;
  9922. case GGML_OP_SOFT_MAX:
  9923. if (ctx->num_additional_fused_ops) {
  9924. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  9925. } else {
  9926. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node);
  9927. }
  9928. break;
  9929. case GGML_OP_SOFT_MAX_BACK:
  9930. ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node);
  9931. break;
  9932. case GGML_OP_ROPE:
  9933. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, false);
  9934. break;
  9935. case GGML_OP_ROPE_BACK:
  9936. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, true);
  9937. break;
  9938. case GGML_OP_ARGSORT:
  9939. if (ctx->num_additional_fused_ops) {
  9940. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  9941. } else {
  9942. ggml_vk_argsort(ctx, compute_ctx, src0, node);
  9943. }
  9944. break;
  9945. case GGML_OP_SUM:
  9946. ggml_vk_sum(ctx, compute_ctx, src0, node);
  9947. break;
  9948. case GGML_OP_SUM_ROWS:
  9949. ggml_vk_sum_rows(ctx, compute_ctx, src0, node);
  9950. break;
  9951. case GGML_OP_MEAN:
  9952. ggml_vk_mean(ctx, compute_ctx, src0, node);
  9953. break;
  9954. case GGML_OP_ARGMAX:
  9955. ggml_vk_argmax(ctx, compute_ctx, src0, node);
  9956. break;
  9957. case GGML_OP_COUNT_EQUAL:
  9958. ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node);
  9959. break;
  9960. case GGML_OP_IM2COL:
  9961. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node);
  9962. break;
  9963. case GGML_OP_IM2COL_3D:
  9964. ggml_vk_im2col_3d(ctx, compute_ctx, src0, src1, node);
  9965. break;
  9966. case GGML_OP_TIMESTEP_EMBEDDING:
  9967. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node);
  9968. break;
  9969. case GGML_OP_CONV_TRANSPOSE_1D:
  9970. ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node);
  9971. break;
  9972. case GGML_OP_POOL_2D:
  9973. ggml_vk_pool_2d(ctx, compute_ctx, src0, node);
  9974. break;
  9975. case GGML_OP_CONV_2D:
  9976. ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node);
  9977. break;
  9978. case GGML_OP_CONV_TRANSPOSE_2D:
  9979. ggml_vk_conv_transpose_2d(ctx, compute_ctx, src0, src1, node);
  9980. break;
  9981. case GGML_OP_CONV_2D_DW:
  9982. ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node);
  9983. break;
  9984. case GGML_OP_LEAKY_RELU:
  9985. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node);
  9986. break;
  9987. case GGML_OP_MUL_MAT:
  9988. ggml_vk_mul_mat(ctx, compute_ctx, cgraph, node_idx);
  9989. break;
  9990. case GGML_OP_MUL_MAT_ID:
  9991. ggml_vk_mul_mat_id(ctx, compute_ctx, cgraph, node_idx);
  9992. break;
  9993. case GGML_OP_FLASH_ATTN_EXT:
  9994. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node);
  9995. break;
  9996. case GGML_OP_RWKV_WKV6:
  9997. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node);
  9998. break;
  9999. case GGML_OP_RWKV_WKV7:
  10000. ggml_vk_rwkv_wkv7(ctx, compute_ctx, node);
  10001. break;
  10002. case GGML_OP_SSM_SCAN:
  10003. ggml_vk_ssm_scan(ctx, compute_ctx, node);
  10004. break;
  10005. case GGML_OP_SSM_CONV:
  10006. ggml_vk_ssm_conv(ctx, compute_ctx, node);
  10007. break;
  10008. case GGML_OP_OPT_STEP_ADAMW:
  10009. ggml_vk_opt_step_adamw(ctx, compute_ctx, node);
  10010. break;
  10011. case GGML_OP_OPT_STEP_SGD:
  10012. ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node);
  10013. break;
  10014. default:
  10015. return false;
  10016. }
  10017. ctx->tensor_ctxs[node_idx] = compute_ctx;
  10018. #if defined(GGML_VULKAN_CHECK_RESULTS)
  10019. // Force context reset on each node so that each tensor ends up in its own context
  10020. // and can be run and compared to its CPU equivalent separately
  10021. last_node = true;
  10022. #endif
  10023. if (submit || last_node) {
  10024. ggml_vk_ctx_end(compute_ctx);
  10025. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  10026. if (last_node) {
  10027. compute_ctx->exit_tensor_idx = node_idx_begin;
  10028. }
  10029. else {
  10030. compute_ctx->exit_tensor_idx = -1;
  10031. }
  10032. ctx->compute_ctx.reset();
  10033. bool ok = ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, almost_ready);
  10034. if (!ok) {
  10035. if (node->op == GGML_OP_UNARY) {
  10036. 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;
  10037. } else if (node->op == GGML_OP_GLU) {
  10038. 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;
  10039. } else {
  10040. std::cerr << __func__ << ": error: op not supported " << node->name << " (" << ggml_op_name(node->op) << ")" << std::endl;
  10041. }
  10042. }
  10043. }
  10044. return true;
  10045. }
  10046. static bool ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, ggml_tensor * tensor, int tensor_idx, bool almost_ready = false) {
  10047. GGML_UNUSED(cgraph);
  10048. ggml_backend_buffer * buf = nullptr;
  10049. switch (tensor->op) {
  10050. case GGML_OP_ADD:
  10051. case GGML_OP_ACC:
  10052. case GGML_OP_GET_ROWS:
  10053. case GGML_OP_SUB:
  10054. case GGML_OP_MUL:
  10055. case GGML_OP_DIV:
  10056. case GGML_OP_ADD_ID:
  10057. case GGML_OP_CONCAT:
  10058. case GGML_OP_UPSCALE:
  10059. case GGML_OP_SCALE:
  10060. case GGML_OP_SQR:
  10061. case GGML_OP_SQRT:
  10062. case GGML_OP_SIN:
  10063. case GGML_OP_COS:
  10064. case GGML_OP_LOG:
  10065. case GGML_OP_CLAMP:
  10066. case GGML_OP_PAD:
  10067. case GGML_OP_ROLL:
  10068. case GGML_OP_CPY:
  10069. case GGML_OP_SET_ROWS:
  10070. case GGML_OP_CONT:
  10071. case GGML_OP_DUP:
  10072. case GGML_OP_SILU_BACK:
  10073. case GGML_OP_NORM:
  10074. case GGML_OP_GROUP_NORM:
  10075. case GGML_OP_RMS_NORM:
  10076. case GGML_OP_RMS_NORM_BACK:
  10077. case GGML_OP_L2_NORM:
  10078. case GGML_OP_DIAG_MASK_INF:
  10079. case GGML_OP_SOFT_MAX:
  10080. case GGML_OP_SOFT_MAX_BACK:
  10081. case GGML_OP_ROPE:
  10082. case GGML_OP_ROPE_BACK:
  10083. case GGML_OP_RESHAPE:
  10084. case GGML_OP_VIEW:
  10085. case GGML_OP_PERMUTE:
  10086. case GGML_OP_TRANSPOSE:
  10087. case GGML_OP_NONE:
  10088. case GGML_OP_ARGSORT:
  10089. case GGML_OP_SUM:
  10090. case GGML_OP_SUM_ROWS:
  10091. case GGML_OP_MEAN:
  10092. case GGML_OP_ARGMAX:
  10093. case GGML_OP_COUNT_EQUAL:
  10094. case GGML_OP_IM2COL:
  10095. case GGML_OP_IM2COL_3D:
  10096. case GGML_OP_TIMESTEP_EMBEDDING:
  10097. case GGML_OP_CONV_TRANSPOSE_1D:
  10098. case GGML_OP_POOL_2D:
  10099. case GGML_OP_CONV_2D:
  10100. case GGML_OP_CONV_TRANSPOSE_2D:
  10101. case GGML_OP_CONV_2D_DW:
  10102. case GGML_OP_RWKV_WKV6:
  10103. case GGML_OP_RWKV_WKV7:
  10104. case GGML_OP_SSM_SCAN:
  10105. case GGML_OP_SSM_CONV:
  10106. case GGML_OP_LEAKY_RELU:
  10107. case GGML_OP_REPEAT:
  10108. case GGML_OP_REPEAT_BACK:
  10109. case GGML_OP_OPT_STEP_ADAMW:
  10110. case GGML_OP_OPT_STEP_SGD:
  10111. buf = tensor->buffer;
  10112. break;
  10113. case GGML_OP_UNARY:
  10114. switch (ggml_get_unary_op(tensor)) {
  10115. case GGML_UNARY_OP_EXP:
  10116. case GGML_UNARY_OP_SILU:
  10117. case GGML_UNARY_OP_GELU:
  10118. case GGML_UNARY_OP_GELU_ERF:
  10119. case GGML_UNARY_OP_GELU_QUICK:
  10120. case GGML_UNARY_OP_RELU:
  10121. case GGML_UNARY_OP_NEG:
  10122. case GGML_UNARY_OP_TANH:
  10123. case GGML_UNARY_OP_SIGMOID:
  10124. case GGML_UNARY_OP_HARDSIGMOID:
  10125. case GGML_UNARY_OP_HARDSWISH:
  10126. case GGML_UNARY_OP_ABS:
  10127. buf = tensor->buffer;
  10128. break;
  10129. default:
  10130. return false;
  10131. }
  10132. break;
  10133. case GGML_OP_GLU:
  10134. switch (ggml_get_glu_op(tensor)) {
  10135. case GGML_GLU_OP_GEGLU:
  10136. case GGML_GLU_OP_REGLU:
  10137. case GGML_GLU_OP_SWIGLU:
  10138. case GGML_GLU_OP_SWIGLU_OAI:
  10139. case GGML_GLU_OP_GEGLU_ERF:
  10140. case GGML_GLU_OP_GEGLU_QUICK:
  10141. buf = tensor->buffer;
  10142. break;
  10143. default:
  10144. return false;
  10145. }
  10146. break;
  10147. case GGML_OP_MUL_MAT:
  10148. case GGML_OP_MUL_MAT_ID:
  10149. case GGML_OP_FLASH_ATTN_EXT:
  10150. buf = tensor->buffer;
  10151. break;
  10152. default:
  10153. return false;
  10154. }
  10155. if (buf == nullptr) {
  10156. return false;
  10157. }
  10158. 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 << ")");
  10159. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  10160. // Only run if ctx hasn't been submitted yet
  10161. if (!subctx->seqs.empty()) {
  10162. #ifdef GGML_VULKAN_CHECK_RESULTS
  10163. ggml_vk_check_results_0(ctx, cgraph, tensor_idx);
  10164. #endif
  10165. // Do staging buffer copies
  10166. for (auto& cpy : subctx->in_memcpys) {
  10167. memcpy(cpy.dst, cpy.src, cpy.n);
  10168. }
  10169. for (auto& mset : subctx->memsets) {
  10170. memset(mset.dst, mset.val, mset.n);
  10171. }
  10172. if (almost_ready && !ctx->almost_ready_fence_pending) {
  10173. ggml_vk_submit(subctx, ctx->almost_ready_fence);
  10174. ctx->almost_ready_fence_pending = true;
  10175. } else {
  10176. ggml_vk_submit(subctx, {});
  10177. }
  10178. ctx->submit_pending = true;
  10179. #ifdef GGML_VULKAN_CHECK_RESULTS
  10180. ggml_vk_synchronize(ctx);
  10181. ggml_vk_check_results_1(ctx, cgraph, tensor_idx);
  10182. #endif
  10183. }
  10184. if (tensor_idx == subctx->exit_tensor_idx) {
  10185. // Do staging buffer copies
  10186. for (auto& cpy : subctx->out_memcpys) {
  10187. memcpy(cpy.dst, cpy.src, cpy.n);
  10188. }
  10189. subctx->in_memcpys.clear();
  10190. subctx->out_memcpys.clear();
  10191. subctx->memsets.clear();
  10192. }
  10193. return true;
  10194. }
  10195. // Clean up after graph processing is done
  10196. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  10197. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  10198. ctx->prealloc_y_last_pipeline_used = {};
  10199. ctx->unsynced_nodes_written.clear();
  10200. ctx->unsynced_nodes_read.clear();
  10201. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  10202. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  10203. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  10204. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  10205. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  10206. }
  10207. ctx->gc.semaphores.clear();
  10208. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  10209. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  10210. }
  10211. ctx->gc.tl_semaphores.clear();
  10212. ctx->semaphore_idx = 0;
  10213. ctx->event_idx = 0;
  10214. for (auto& event : ctx->gc.events) {
  10215. ctx->device->device.resetEvent(event);
  10216. }
  10217. ctx->tensor_ctxs.clear();
  10218. ctx->gc.contexts.clear();
  10219. ctx->pipeline_descriptor_set_requirements = 0;
  10220. ctx->descriptor_set_idx = 0;
  10221. }
  10222. // Clean up on backend free
  10223. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  10224. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  10225. // discard any unsubmitted command buffers
  10226. ctx->transfer_ctx.reset();
  10227. // wait for any pending command buffers to finish
  10228. ggml_vk_synchronize(ctx);
  10229. ggml_vk_graph_cleanup(ctx);
  10230. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10231. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10232. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10233. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  10234. ggml_vk_destroy_buffer(ctx->sync_staging);
  10235. ctx->prealloc_y_last_pipeline_used = nullptr;
  10236. ctx->prealloc_size_x = 0;
  10237. ctx->prealloc_size_y = 0;
  10238. ctx->prealloc_size_split_k = 0;
  10239. for (auto& event : ctx->gc.events) {
  10240. ctx->device->device.destroyEvent(event);
  10241. }
  10242. ctx->gc.events.clear();
  10243. ctx->device->device.destroyFence(ctx->fence);
  10244. ctx->device->device.destroyFence(ctx->almost_ready_fence);
  10245. for (auto& pool : ctx->descriptor_pools) {
  10246. ctx->device->device.destroyDescriptorPool(pool);
  10247. }
  10248. ctx->descriptor_pools.clear();
  10249. ctx->descriptor_sets.clear();
  10250. ctx->compute_cmd_pool.destroy(ctx->device->device);
  10251. ctx->transfer_cmd_pool.destroy(ctx->device->device);
  10252. }
  10253. static int ggml_vk_get_device_count() {
  10254. ggml_vk_instance_init();
  10255. return vk_instance.device_indices.size();
  10256. }
  10257. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  10258. ggml_vk_instance_init();
  10259. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  10260. vk::PhysicalDeviceProperties props;
  10261. devices[device].getProperties(&props);
  10262. snprintf(description, description_size, "%s", props.deviceName.data());
  10263. }
  10264. // backend interface
  10265. #define UNUSED GGML_UNUSED
  10266. // device backend
  10267. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  10268. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  10269. }
  10270. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10271. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  10272. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10273. ggml_vk_destroy_buffer(ctx->dev_buffer);
  10274. delete ctx;
  10275. }
  10276. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  10277. return vk_ptr_base;
  10278. UNUSED(buffer);
  10279. }
  10280. static enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  10281. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  10282. if (tensor->view_src != nullptr) {
  10283. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  10284. }
  10285. return GGML_STATUS_SUCCESS;
  10286. }
  10287. 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) {
  10288. VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")");
  10289. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10290. vk_buffer buf = buf_ctx->dev_buffer;
  10291. uint32_t val32 = (uint32_t)value * 0x01010101;
  10292. ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size);
  10293. }
  10294. 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) {
  10295. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10296. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10297. vk_buffer buf = buf_ctx->dev_buffer;
  10298. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10299. }
  10300. 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) {
  10301. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10302. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10303. vk_buffer buf = buf_ctx->dev_buffer;
  10304. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10305. }
  10306. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  10307. if (ggml_backend_buffer_is_vk(src->buffer)) {
  10308. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10309. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10310. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10311. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10312. 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));
  10313. return true;
  10314. }
  10315. return false;
  10316. UNUSED(buffer);
  10317. }
  10318. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  10319. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10320. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  10321. }
  10322. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  10323. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  10324. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  10325. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  10326. /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor,
  10327. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  10328. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  10329. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  10330. /* .clear = */ ggml_backend_vk_buffer_clear,
  10331. /* .reset = */ NULL,
  10332. };
  10333. // vk buffer type
  10334. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10335. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  10336. return ctx->name.c_str();
  10337. }
  10338. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10339. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  10340. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10341. vk_buffer dev_buffer = nullptr;
  10342. try {
  10343. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  10344. } catch (const vk::SystemError& e) {
  10345. return nullptr;
  10346. }
  10347. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  10348. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  10349. }
  10350. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10351. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10352. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  10353. }
  10354. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10355. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10356. return ctx->device->suballocation_block_size;
  10357. }
  10358. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  10359. return ggml_nbytes(tensor);
  10360. UNUSED(buft);
  10361. }
  10362. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  10363. ggml_vk_instance_init();
  10364. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  10365. vk_device dev = ggml_vk_get_device(dev_num);
  10366. return &dev->buffer_type;
  10367. }
  10368. // host buffer type
  10369. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10370. return GGML_VK_NAME "_Host";
  10371. UNUSED(buft);
  10372. }
  10373. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  10374. return GGML_VK_NAME "_Host";
  10375. UNUSED(buffer);
  10376. }
  10377. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10378. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  10379. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  10380. }
  10381. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10382. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  10383. size += 32; // Behave like the CPU buffer type
  10384. void * ptr = nullptr;
  10385. try {
  10386. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  10387. } catch (vk::SystemError& e) {
  10388. GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory (%s)\n", e.what());
  10389. // fallback to cpu buffer
  10390. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  10391. }
  10392. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  10393. buffer->buft = buft;
  10394. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  10395. return buffer;
  10396. UNUSED(buft);
  10397. }
  10398. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10399. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  10400. UNUSED(buft);
  10401. }
  10402. static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10403. return vk_instance.devices[0]->suballocation_block_size;
  10404. UNUSED(buft);
  10405. }
  10406. // Should be changed to return device-specific host buffer type
  10407. // but that probably requires changes in llama.cpp
  10408. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  10409. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  10410. /* .iface = */ {
  10411. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  10412. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  10413. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  10414. /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size,
  10415. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  10416. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  10417. },
  10418. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  10419. /* .context = */ nullptr,
  10420. };
  10421. // Make sure device 0 is initialized
  10422. ggml_vk_instance_init();
  10423. ggml_vk_get_device(0);
  10424. return &ggml_backend_vk_buffer_type_host;
  10425. }
  10426. // backend
  10427. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  10428. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10429. return ctx->name.c_str();
  10430. }
  10431. static void ggml_backend_vk_free(ggml_backend_t backend) {
  10432. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10433. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  10434. ggml_vk_cleanup(ctx);
  10435. delete ctx;
  10436. delete backend;
  10437. }
  10438. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  10439. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10440. return &ctx->device->buffer_type;
  10441. }
  10442. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  10443. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  10444. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10445. 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");
  10446. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10447. vk_context transfer_ctx;
  10448. if (ctx->transfer_ctx.expired()) {
  10449. // Initialize new transfer context
  10450. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10451. ctx->transfer_ctx = transfer_ctx;
  10452. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10453. } else {
  10454. transfer_ctx = ctx->transfer_ctx.lock();
  10455. }
  10456. vk_buffer buf = buf_ctx->dev_buffer;
  10457. ggml_vk_buffer_write_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10458. }
  10459. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  10460. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  10461. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10462. 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");
  10463. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10464. vk_context transfer_ctx;
  10465. if (ctx->transfer_ctx.expired()) {
  10466. // Initialize new transfer context
  10467. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10468. ctx->transfer_ctx = transfer_ctx;
  10469. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10470. } else {
  10471. transfer_ctx = ctx->transfer_ctx.lock();
  10472. }
  10473. vk_buffer buf = buf_ctx->dev_buffer;
  10474. auto src_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset;
  10475. bool ret = ggml_vk_buffer_read_async(transfer_ctx, buf, src_offset, data, size);
  10476. // If that failed, copy synchronously through a staging buffer
  10477. if (!ret) {
  10478. ggml_vk_ensure_sync_staging_buffer(ctx, size);
  10479. ggml_vk_sync_buffers(nullptr, transfer_ctx);
  10480. vk::BufferCopy buffer_cpy;
  10481. buffer_cpy.srcOffset = src_offset;
  10482. buffer_cpy.dstOffset = 0;
  10483. buffer_cpy.size = size;
  10484. transfer_ctx->s->buffer.copyBuffer(buf->buffer, ctx->sync_staging->buffer, { buffer_cpy });
  10485. deferred_memcpy(data, ctx->sync_staging->ptr, size, &transfer_ctx->out_memcpys);
  10486. ggml_vk_synchronize(ctx);
  10487. }
  10488. }
  10489. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  10490. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  10491. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10492. 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)) {
  10493. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10494. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10495. vk_context transfer_ctx;
  10496. if (ctx->transfer_ctx.expired()) {
  10497. // Initialize new transfer context
  10498. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10499. ctx->transfer_ctx = transfer_ctx;
  10500. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10501. } else {
  10502. transfer_ctx = ctx->transfer_ctx.lock();
  10503. }
  10504. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10505. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10506. 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));
  10507. return true;
  10508. }
  10509. return false;
  10510. }
  10511. static void ggml_vk_synchronize(ggml_backend_vk_context * ctx) {
  10512. VK_LOG_DEBUG("ggml_vk_synchronize()");
  10513. bool do_transfer = !ctx->transfer_ctx.expired();
  10514. vk_context transfer_ctx;
  10515. if (do_transfer) {
  10516. transfer_ctx = ctx->transfer_ctx.lock();
  10517. ggml_vk_ctx_end(transfer_ctx);
  10518. for (auto& cpy : transfer_ctx->in_memcpys) {
  10519. memcpy(cpy.dst, cpy.src, cpy.n);
  10520. }
  10521. ggml_vk_submit(transfer_ctx, {});
  10522. ctx->submit_pending = true;
  10523. }
  10524. if (ctx->submit_pending) {
  10525. {
  10526. std::lock_guard<std::mutex> guard(queue_mutex);
  10527. ctx->device->compute_queue.queue.submit({}, ctx->fence);
  10528. }
  10529. ggml_vk_wait_for_fence(ctx);
  10530. ctx->submit_pending = false;
  10531. }
  10532. if (do_transfer) {
  10533. for (auto& cpy : transfer_ctx->out_memcpys) {
  10534. memcpy(cpy.dst, cpy.src, cpy.n);
  10535. }
  10536. ctx->transfer_ctx.reset();
  10537. }
  10538. }
  10539. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  10540. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  10541. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10542. ggml_vk_synchronize(ctx);
  10543. ggml_vk_graph_cleanup(ctx);
  10544. }
  10545. static bool ggml_vk_is_empty(ggml_tensor * node) {
  10546. 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;
  10547. }
  10548. 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) {
  10549. if (!ggml_can_fuse(cgraph, node_idx, ops)) {
  10550. return false;
  10551. }
  10552. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
  10553. // additional constraints specific to this fusion
  10554. const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
  10555. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10556. GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
  10557. GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
  10558. // rms_norm only supports f32
  10559. if (mul->src[0]->type != GGML_TYPE_F32 ||
  10560. mul->src[1]->type != GGML_TYPE_F32 ||
  10561. mul->type != GGML_TYPE_F32) {
  10562. return false;
  10563. }
  10564. // if rms_norm is the B operand, then we don't handle broadcast
  10565. if (rms_norm == mul->src[1] &&
  10566. !ggml_are_same_shape(mul->src[0], rms_norm)) {
  10567. return false;
  10568. }
  10569. // rms_norm shader assumes contiguous rows
  10570. if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
  10571. return false;
  10572. }
  10573. }
  10574. auto const &mm_add_ok = [&](const ggml_tensor *mul, const ggml_tensor *add) {
  10575. const ggml_tensor *bias = add->src[0] == mul ? add->src[1] : add->src[0];
  10576. // mat-vec only
  10577. if (ggml_nrows(mul) != 1) {
  10578. return false;
  10579. }
  10580. // shaders assume the types match
  10581. if (mul->type != bias->type) {
  10582. return false;
  10583. }
  10584. // shaders reuse the D shape for bias
  10585. if (!ggml_are_same_shape(mul, bias) ||
  10586. !ggml_are_same_stride(mul, bias)) {
  10587. return false;
  10588. }
  10589. // unaligned bias isn't handled
  10590. if (get_misalign_bytes(ctx, bias) != 0) {
  10591. return false;
  10592. }
  10593. return true;
  10594. };
  10595. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT && ops.begin()[1] == GGML_OP_ADD) {
  10596. // additional constraints specific to this fusion
  10597. const ggml_tensor *mul = cgraph->nodes[node_idx];
  10598. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  10599. if (!mm_add_ok(mul, add)) {
  10600. return false;
  10601. }
  10602. if (ops.size() == 3) {
  10603. if (ops.begin()[2] != GGML_OP_ADD) {
  10604. return false;
  10605. }
  10606. if (!mm_add_ok(add, cgraph->nodes[node_idx + 2])) {
  10607. return false;
  10608. }
  10609. }
  10610. }
  10611. auto const &mmid_mul_ok = [&](const ggml_tensor *mmid, const ggml_tensor *mul) {
  10612. const ggml_tensor *scale = mul->src[1];
  10613. if (mmid != mul->src[0]) {
  10614. return false;
  10615. }
  10616. // mat-vec only
  10617. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  10618. return false;
  10619. }
  10620. // shaders assume the types match
  10621. if (mmid->type != scale->type) {
  10622. return false;
  10623. }
  10624. // shaders assume the bias is contiguous
  10625. if (!ggml_is_contiguous(scale)) {
  10626. return false;
  10627. }
  10628. // unaligned bias isn't handled
  10629. if (get_misalign_bytes(ctx, scale) != 0) {
  10630. return false;
  10631. }
  10632. // shader only indexes by expert index
  10633. if (scale->ne[0] != 1 ||
  10634. scale->ne[1] != mul->ne[1] ||
  10635. scale->ne[2] != 1 ||
  10636. scale->ne[3] != 1) {
  10637. return false;
  10638. }
  10639. return true;
  10640. };
  10641. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_ADD_ID) {
  10642. // additional constraints specific to this fusion
  10643. const ggml_tensor *mul = cgraph->nodes[node_idx];
  10644. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  10645. const ggml_tensor *bias = add->src[1];
  10646. if (mul != add->src[0]) {
  10647. return false;
  10648. }
  10649. // mat-vec only
  10650. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  10651. return false;
  10652. }
  10653. // shaders assume the types match
  10654. if (mul->type != bias->type) {
  10655. return false;
  10656. }
  10657. // shaders assume the bias is contiguous
  10658. if (!ggml_is_contiguous(bias)) {
  10659. return false;
  10660. }
  10661. // the ID tensor must be the same for mul_mat_id and add_id
  10662. if (mul->src[2] != add->src[2]) {
  10663. return false;
  10664. }
  10665. // unaligned bias isn't handled
  10666. if (get_misalign_bytes(ctx, bias) != 0) {
  10667. return false;
  10668. }
  10669. if (ops.size() == 3) {
  10670. if (ops.begin()[2] != GGML_OP_MUL) {
  10671. return false;
  10672. }
  10673. const ggml_tensor *mul = cgraph->nodes[node_idx + 2];
  10674. return mmid_mul_ok(add, mul);
  10675. }
  10676. }
  10677. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_MUL) {
  10678. // additional constraints specific to this fusion
  10679. const ggml_tensor *mmid = cgraph->nodes[node_idx];
  10680. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10681. if (!mmid_mul_ok(mmid, mul)) {
  10682. return false;
  10683. }
  10684. }
  10685. return true;
  10686. }
  10687. static bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10688. int node_idx, topk_moe_mode mode) {
  10689. const ggml_tensor * softmax;
  10690. const ggml_tensor * weights;
  10691. switch (mode) {
  10692. case TOPK_MOE_EARLY_SOFTMAX_NORM:
  10693. softmax = cgraph->nodes[node_idx + 0];
  10694. weights = cgraph->nodes[node_idx + 9];
  10695. break;
  10696. case TOPK_MOE_EARLY_SOFTMAX:
  10697. softmax = cgraph->nodes[node_idx + 0];
  10698. weights = cgraph->nodes[node_idx + 4];
  10699. break;
  10700. case TOPK_MOE_LATE_SOFTMAX:
  10701. softmax = cgraph->nodes[node_idx + 4];
  10702. weights = cgraph->nodes[node_idx + 5];
  10703. break;
  10704. default:
  10705. return false;
  10706. }
  10707. const float * op_params = (const float *)softmax->op_params;
  10708. float scale = op_params[0];
  10709. float max_bias = op_params[1];
  10710. if (!ggml_is_contiguous(softmax->src[0]) || !ggml_is_contiguous(weights)) {
  10711. return false;
  10712. }
  10713. if (scale != 1.0f || max_bias != 0.0f) {
  10714. return false;
  10715. }
  10716. // don't fuse when masks or sinks are present
  10717. if (softmax->src[1] || softmax->src[2]) {
  10718. return false;
  10719. }
  10720. const int n_expert = softmax->ne[0];
  10721. // n_expert must be a power of 2
  10722. if (!is_pow2(n_expert) || n_expert > (1 << (num_topk_moe_pipelines-1))) {
  10723. return false;
  10724. }
  10725. if (!ctx->device->subgroup_arithmetic ||
  10726. !ctx->device->subgroup_shuffle ||
  10727. !ctx->device->subgroup_require_full_support ||
  10728. ctx->device->disable_fusion) {
  10729. return false;
  10730. }
  10731. return true;
  10732. }
  10733. static bool ggml_vk_can_fuse_rope_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10734. int node_idx) {
  10735. GGML_UNUSED(ctx);
  10736. const ggml_tensor *rope = cgraph->nodes[node_idx + 0];
  10737. const ggml_tensor *view = cgraph->nodes[node_idx + 1];
  10738. const ggml_tensor *set_rows = cgraph->nodes[node_idx + 2];
  10739. // ne3 not tested
  10740. if (rope->src[0]->ne[3] != 1) {
  10741. return false;
  10742. }
  10743. if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) {
  10744. return false;
  10745. }
  10746. if (set_rows->src[1]->type != GGML_TYPE_I64) {
  10747. return false;
  10748. }
  10749. // The view should flatten two dims of rope into one dim
  10750. if (!ggml_is_contiguous(view) ||
  10751. view->ne[0] != rope->ne[0] * rope->ne[1]) {
  10752. return false;
  10753. }
  10754. // Only norm/neox shaders have the fusion code
  10755. const int mode = ((const int32_t *) rope->op_params)[2];
  10756. if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX) {
  10757. return false;
  10758. }
  10759. return true;
  10760. }
  10761. // Check whether the tensors overlap in memory but are not equal.
  10762. // Fusions can potenitally overwrite src tensors in ways that are not prevented
  10763. // by ggml-alloc. If the fusion is entirely elementwise, then it's OK for them
  10764. // to overlap if they are exactly equal.
  10765. // XXX TODO this check is probably missing from several fusion optimizations.
  10766. static bool ggml_vk_tensors_overlap_but_not_equal(const ggml_tensor * a, const ggml_tensor * b) {
  10767. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)a->buffer->context;
  10768. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  10769. ggml_backend_vk_buffer_context * b_buf_ctx = (ggml_backend_vk_buffer_context *)b->buffer->context;
  10770. vk_buffer b_buf = b_buf_ctx->dev_buffer;
  10771. if (a_buf == b_buf) {
  10772. auto a_base = vk_tensor_offset(a) + a->view_offs;
  10773. auto a_size = ggml_nbytes(a);
  10774. auto b_base = vk_tensor_offset(b) + b->view_offs;
  10775. auto b_size = ggml_nbytes(b);
  10776. if (a_base == b_base && a_size == b_size) {
  10777. return false;
  10778. }
  10779. if ((b_base <= a_base && a_base < b_base + b_size) ||
  10780. (a_base <= b_base && b_base < a_base + a_size)) {
  10781. return true;
  10782. }
  10783. }
  10784. return false;
  10785. }
  10786. static bool ggml_vk_can_fuse_rms_norm_mul_rope(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10787. int node_idx) {
  10788. GGML_UNUSED(ctx);
  10789. const ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  10790. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10791. const ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  10792. const int mode = ((const int32_t *) rope->op_params)[2];
  10793. // noncontig tensors aren't tested, and don't seem common in practice
  10794. if (!ggml_is_contiguous(rms) ||
  10795. !ggml_is_contiguous(mul) ||
  10796. !ggml_is_contiguous(rope)) {
  10797. return false;
  10798. }
  10799. // only norm/neox are handled in the shader
  10800. if (mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_NORMAL) {
  10801. return false;
  10802. }
  10803. // shared memory size for passing data from mul->rope
  10804. if (mul->ne[0] > 1024) {
  10805. return false;
  10806. }
  10807. // must not overwrite srcs in a way that's not elementwise
  10808. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  10809. if (ggml_vk_tensors_overlap_but_not_equal(rms->src[0], rope) ||
  10810. ggml_vk_tensors_overlap_but_not_equal(other_src, rope)) {
  10811. return false;
  10812. }
  10813. // conditions for pipeline creation
  10814. if (!(ctx->device->float_controls_rte_fp16 &&
  10815. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= ctx->device->properties.limits.maxPushConstantsSize)) {
  10816. return false;
  10817. }
  10818. return true;
  10819. }
  10820. static uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) {
  10821. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  10822. if (first_node->op != GGML_OP_ADD) {
  10823. return 0;
  10824. }
  10825. if (!ctx->device->multi_add) {
  10826. return 0;
  10827. }
  10828. int32_t num_adds = 1;
  10829. while (node_idx + num_adds < cgraph->n_nodes &&
  10830. cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD &&
  10831. num_adds < MAX_FUSED_ADDS) {
  10832. num_adds++;
  10833. }
  10834. // The shader currently requires same shapes (but different strides are allowed),
  10835. // everything f32, and no misalignment
  10836. for (int32_t i = 0; i < num_adds; ++i) {
  10837. const ggml_tensor *next_node = cgraph->nodes[node_idx + i];
  10838. if (!ggml_are_same_shape(first_node, next_node->src[0]) ||
  10839. !ggml_are_same_shape(first_node, next_node->src[1]) ||
  10840. next_node->type != GGML_TYPE_F32 ||
  10841. next_node->src[0]->type != GGML_TYPE_F32 ||
  10842. next_node->src[1]->type != GGML_TYPE_F32 ||
  10843. get_misalign_bytes(ctx, next_node) ||
  10844. get_misalign_bytes(ctx, next_node->src[0]) ||
  10845. get_misalign_bytes(ctx, next_node->src[1])) {
  10846. num_adds = i;
  10847. }
  10848. }
  10849. // Verify we can fuse these
  10850. ggml_op adds[MAX_FUSED_ADDS];
  10851. for (int32_t i = 0; i < num_adds; ++i) {
  10852. adds[i] = GGML_OP_ADD;
  10853. }
  10854. // decrease num_adds if they can't all be fused
  10855. while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) {
  10856. num_adds--;
  10857. }
  10858. // a single add is not "fused", so just return zero
  10859. if (num_adds == 1) {
  10860. return 0;
  10861. }
  10862. return num_adds;
  10863. }
  10864. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  10865. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  10866. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10867. if (vk_instance.debug_utils_support) {
  10868. vk::DebugUtilsLabelEXT dul = {};
  10869. dul.pLabelName = "ggml_backend_vk_graph_compute";
  10870. dul.color = std::array<float,4>{1.0f, 1.0f, 1.0f, 1.0f};
  10871. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(ctx->device->compute_queue.queue, reinterpret_cast<VkDebugUtilsLabelEXT*>(&dul));
  10872. }
  10873. ctx->prealloc_size_add_rms_partials_offset = 0;
  10874. ctx->do_add_rms_partials = false;
  10875. ctx->do_add_rms_partials_offset_calculation = false;
  10876. int last_node = cgraph->n_nodes - 1;
  10877. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  10878. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  10879. last_node -= 1;
  10880. }
  10881. // Reserve tensor context space for all nodes
  10882. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  10883. bool first_node_in_batch = true; // true if next node will be first node in a batch
  10884. int submit_node_idx = 0; // index to first node in a batch
  10885. vk_context compute_ctx;
  10886. if (vk_perf_logger_enabled) {
  10887. // allocate/resize the query pool
  10888. if (ctx->device->num_queries < cgraph->n_nodes + 1) {
  10889. if (ctx->device->query_pool) {
  10890. ctx->device->device.destroyQueryPool(ctx->device->query_pool);
  10891. }
  10892. vk::QueryPoolCreateInfo query_create_info;
  10893. query_create_info.queryType = vk::QueryType::eTimestamp;
  10894. query_create_info.queryCount = cgraph->n_nodes + 100;
  10895. ctx->device->query_pool = ctx->device->device.createQueryPool(query_create_info);
  10896. ctx->device->num_queries = query_create_info.queryCount;
  10897. }
  10898. ctx->device->device.resetQueryPool(ctx->device->query_pool, 0, cgraph->n_nodes+1);
  10899. GGML_ASSERT(ctx->compute_ctx.expired());
  10900. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10901. ctx->compute_ctx = compute_ctx;
  10902. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10903. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, 0);
  10904. }
  10905. ctx->prealloc_y_last_pipeline_used = nullptr;
  10906. ctx->prealloc_y_last_tensor_used = nullptr;
  10907. if (ctx->prealloc_size_add_rms_partials) {
  10908. ggml_vk_preallocate_buffers(ctx, nullptr);
  10909. if (ctx->compute_ctx.expired()) {
  10910. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10911. ctx->compute_ctx = compute_ctx;
  10912. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10913. } else {
  10914. compute_ctx = ctx->compute_ctx.lock();
  10915. }
  10916. // initialize partial sums to zero.
  10917. ggml_vk_buffer_memset_async(compute_ctx, ctx->prealloc_add_rms_partials, 0, 0, ctx->prealloc_size_add_rms_partials);
  10918. ggml_vk_sync_buffers(ctx, compute_ctx);
  10919. }
  10920. // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution.
  10921. // Estimate the amount of matmul work by looking at the weight matrix size, and submit every 100MB
  10922. // (and scaled down based on model size, so smaller models submit earlier).
  10923. // Also submit at least every 100 nodes, in case there are workloads without as much matmul.
  10924. int nodes_per_submit = 100;
  10925. int submitted_nodes = 0;
  10926. int submit_count = 0;
  10927. uint64_t mul_mat_bytes = 0;
  10928. uint64_t total_mul_mat_bytes = 0;
  10929. uint64_t mul_mat_bytes_per_submit = std::min(uint64_t(100*1000*1000), ctx->last_total_mul_mat_bytes / 40u);
  10930. for (int i = 0; i < cgraph->n_nodes; i++) {
  10931. if (first_node_in_batch) {
  10932. submit_node_idx = i;
  10933. }
  10934. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  10935. auto bytes = ggml_nbytes(cgraph->nodes[i]->src[0]);
  10936. mul_mat_bytes += bytes;
  10937. total_mul_mat_bytes += bytes;
  10938. }
  10939. if (!ctx->device->disable_fusion) {
  10940. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  10941. if (num_adds) {
  10942. ctx->num_additional_fused_ops = num_adds - 1;
  10943. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_ADD })) {
  10944. ctx->num_additional_fused_ops = 2;
  10945. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD })) {
  10946. ctx->num_additional_fused_ops = 1;
  10947. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_MUL })) {
  10948. ctx->num_additional_fused_ops = 2;
  10949. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID })) {
  10950. ctx->num_additional_fused_ops = 1;
  10951. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_MUL })) {
  10952. ctx->num_additional_fused_ops = 1;
  10953. } 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 }) &&
  10954. ggml_check_edges(cgraph, i, rms_norm_mul_rope_view_set_rows_edges) &&
  10955. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i) &&
  10956. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i + 2)) {
  10957. ctx->num_additional_fused_ops = 4;
  10958. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE })&&
  10959. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i)) {
  10960. ctx->num_additional_fused_ops = 2;
  10961. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  10962. ctx->num_additional_fused_ops = 1;
  10963. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 2 }) &&
  10964. ggml_check_edges(cgraph, i, rope_view_set_rows_edges) &&
  10965. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i)) {
  10966. ctx->num_additional_fused_ops = 2;
  10967. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax_norm, { i + 3, i + 9 }) &&
  10968. ggml_check_edges(cgraph, i, topk_moe_early_softmax_norm_edges) &&
  10969. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX_NORM)) {
  10970. ctx->num_additional_fused_ops = topk_moe_early_softmax_norm.size() - 1;
  10971. // view of argsort writes to memory
  10972. ctx->fused_ops_write_mask |= 1 << 3;
  10973. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax, { i + 3, i + 4 }) &&
  10974. ggml_check_edges(cgraph, i, topk_moe_early_softmax_edges) &&
  10975. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX)) {
  10976. ctx->num_additional_fused_ops = topk_moe_early_softmax.size() - 1;
  10977. // view of argsort writes to memory
  10978. ctx->fused_ops_write_mask |= 1 << 3;
  10979. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_late_softmax, { i + 1, i + 5 }) &&
  10980. ggml_check_edges(cgraph, i, topk_moe_late_softmax_edges) &&
  10981. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_LATE_SOFTMAX)) {
  10982. ctx->num_additional_fused_ops = topk_moe_late_softmax.size() - 1;
  10983. // view of argsort writes to memory
  10984. ctx->fused_ops_write_mask |= 1 << 1;
  10985. }
  10986. }
  10987. ctx->fused_ops_write_mask |= 1 << ctx->num_additional_fused_ops;
  10988. // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining)
  10989. bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5;
  10990. bool submit = (submitted_nodes >= nodes_per_submit) ||
  10991. (mul_mat_bytes_per_submit != 0 && mul_mat_bytes >= mul_mat_bytes_per_submit) ||
  10992. (i + ctx->num_additional_fused_ops >= last_node) ||
  10993. (almost_ready && !ctx->almost_ready_fence_pending);
  10994. 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);
  10995. if (vk_perf_logger_enabled) {
  10996. if (ctx->compute_ctx.expired()) {
  10997. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10998. ctx->compute_ctx = compute_ctx;
  10999. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11000. } else {
  11001. compute_ctx = ctx->compute_ctx.lock();
  11002. }
  11003. // If there are fused ops, just write out timestamps for all nodes to keep the accounting simple
  11004. for (int j = 0; j < ctx->num_additional_fused_ops + 1; ++j) {
  11005. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, i+j+1);
  11006. }
  11007. }
  11008. if (enqueued) {
  11009. ++submitted_nodes;
  11010. #ifndef GGML_VULKAN_CHECK_RESULTS
  11011. if (first_node_in_batch) {
  11012. first_node_in_batch = false;
  11013. }
  11014. #endif
  11015. }
  11016. if (submit && enqueued) {
  11017. first_node_in_batch = true;
  11018. submitted_nodes = 0;
  11019. mul_mat_bytes = 0;
  11020. if (submit_count < 3) {
  11021. mul_mat_bytes_per_submit *= 2;
  11022. }
  11023. submit_count++;
  11024. }
  11025. i += ctx->num_additional_fused_ops;
  11026. ctx->num_additional_fused_ops = 0;
  11027. ctx->fused_ops_write_mask = 0;
  11028. }
  11029. ctx->prealloc_size_add_rms_partials = std::max(ctx->prealloc_size_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset);
  11030. ctx->last_total_mul_mat_bytes = total_mul_mat_bytes;
  11031. if (vk_perf_logger_enabled) {
  11032. // End the command buffer and submit/wait
  11033. GGML_ASSERT(!ctx->compute_ctx.expired());
  11034. compute_ctx = ctx->compute_ctx.lock();
  11035. ggml_vk_ctx_end(compute_ctx);
  11036. ggml_vk_submit(compute_ctx, ctx->device->fence);
  11037. VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences");
  11038. ctx->device->device.resetFences({ ctx->device->fence });
  11039. // Get the results and pass them to the logger
  11040. std::vector<uint64_t> timestamps(cgraph->n_nodes + 1);
  11041. 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");
  11042. for (int i = 0; i < cgraph->n_nodes; i++) {
  11043. if (!ggml_vk_is_empty(cgraph->nodes[i])) {
  11044. ctx->device->perf_logger->log_timing(cgraph->nodes[i], uint64_t((timestamps[i+1] - timestamps[i]) * ctx->device->properties.limits.timestampPeriod));
  11045. }
  11046. }
  11047. ctx->device->perf_logger->print_timings();
  11048. }
  11049. return GGML_STATUS_SUCCESS;
  11050. UNUSED(backend);
  11051. }
  11052. // Sort the graph for improved parallelism.
  11053. static void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph)
  11054. {
  11055. VK_LOG_DEBUG("ggml_vk_graph_optimize(" << graph->n_nodes << " nodes)");
  11056. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11057. if (ctx->device->disable_graph_optimize) {
  11058. return;
  11059. }
  11060. auto const &is_empty = [](ggml_tensor * node) -> bool {
  11061. 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;
  11062. };
  11063. auto const &is_src_of = [](const ggml_tensor *dst, const ggml_tensor *src) -> bool {
  11064. for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) {
  11065. if (dst->src[s] == src) {
  11066. return true;
  11067. }
  11068. }
  11069. // implicit dependency if they view the same tensor
  11070. const ggml_tensor *dst2 = dst->view_src ? dst->view_src : dst;
  11071. const ggml_tensor *src2 = src->view_src ? src->view_src : src;
  11072. if (dst2 == src2) {
  11073. return true;
  11074. }
  11075. return false;
  11076. };
  11077. // This function tries to reorder the graph to allow nodes to run in parallel.
  11078. // This helps with small batches, but for large batches its a slowdown, probably
  11079. // due to cache contention. So only reorder if the majority of nodes have few rows.
  11080. int num_small_nodes = 0;
  11081. int num_counted_nodes = 0;
  11082. for (int i = 0; i < graph->n_nodes; ++i) {
  11083. if (!is_empty(graph->nodes[i]) &&
  11084. graph->nodes[i]->op != GGML_OP_SET_ROWS) {
  11085. if (ggml_nrows(graph->nodes[i]) <= 8) {
  11086. num_small_nodes++;
  11087. }
  11088. num_counted_nodes++;
  11089. }
  11090. }
  11091. if (num_small_nodes < num_counted_nodes / 2) {
  11092. return;
  11093. }
  11094. std::vector<ggml_tensor *> new_order;
  11095. std::vector<bool> used(graph->n_nodes, false);
  11096. std::set<ggml_tensor *> used_node_set;
  11097. int first_unused = 0;
  11098. while (first_unused < graph->n_nodes) {
  11099. std::vector<int> current_set;
  11100. // Check for fusion patterns and avoid reordering them
  11101. auto const &match_pattern = [&](const std::initializer_list<ggml_op> &pattern, int start) -> bool {
  11102. if (start + (int)pattern.size() <= graph->n_nodes) {
  11103. bool is_pattern = true;
  11104. for (size_t j = 0; j < pattern.size(); ++j) {
  11105. if (graph->nodes[start + j]->op != pattern.begin()[j] || used[start + j]) {
  11106. is_pattern = false;
  11107. }
  11108. }
  11109. return is_pattern;
  11110. }
  11111. return false;
  11112. };
  11113. auto const &keep_pattern = [&](const std::initializer_list<ggml_op> &pattern) -> bool {
  11114. if (match_pattern(pattern, first_unused)) {
  11115. for (size_t j = 0; j < pattern.size(); ++j) {
  11116. new_order.push_back(graph->nodes[first_unused + j]);
  11117. used_node_set.insert(graph->nodes[first_unused + j]);
  11118. used[first_unused + j] = true;
  11119. }
  11120. while (first_unused < graph->n_nodes && used[first_unused]) {
  11121. first_unused++;
  11122. }
  11123. return true;
  11124. }
  11125. return false;
  11126. };
  11127. if (keep_pattern(topk_moe_early_softmax_norm)) {
  11128. continue;
  11129. }
  11130. if (keep_pattern(topk_moe_early_softmax)) {
  11131. continue;
  11132. }
  11133. if (keep_pattern(topk_moe_late_softmax)) {
  11134. continue;
  11135. }
  11136. // First, grab the next unused node.
  11137. current_set.push_back(first_unused);
  11138. // Loop through the next N nodes. Grab any that don't depend on other nodes that
  11139. // haven't already been run. Nodes that have already been run have used[i] set
  11140. // to true. Allow nodes that depend on the previous node if it's a fusion pattern
  11141. // that we support (e.g. RMS_NORM + MUL).
  11142. // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes.
  11143. // The goal is to not interleave real and view nodes in a way that breaks fusion.
  11144. const int NUM_TO_CHECK = 20;
  11145. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11146. if (used[j]) {
  11147. continue;
  11148. }
  11149. if (is_empty(graph->nodes[j])) {
  11150. continue;
  11151. }
  11152. // Don't pull forward nodes from fusion patterns
  11153. if (match_pattern(topk_moe_early_softmax_norm, j) ||
  11154. match_pattern(topk_moe_early_softmax, j) ||
  11155. match_pattern(topk_moe_late_softmax, j)) {
  11156. continue;
  11157. }
  11158. bool ok = true;
  11159. for (int c = first_unused; c < j; ++c) {
  11160. if (!used[c] &&
  11161. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11162. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL) &&
  11163. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT && graph->nodes[j]->op == GGML_OP_ADD) &&
  11164. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_ADD_ID) &&
  11165. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_MUL)) {
  11166. ok = false;
  11167. break;
  11168. }
  11169. }
  11170. if (ok) {
  11171. current_set.push_back(j);
  11172. int rope_idx = j;
  11173. // When we've found RMS_NORM + MUL, try to find a ROPE that uses it
  11174. if (j > 0 &&
  11175. graph->nodes[j]->op == GGML_OP_MUL &&
  11176. graph->nodes[j-1]->op == GGML_OP_RMS_NORM) {
  11177. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11178. if (graph->nodes[k]->op == GGML_OP_ROPE &&
  11179. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11180. // Check that other srcs are already valid
  11181. graph->nodes[k]->src[1]->op == GGML_OP_NONE &&
  11182. (graph->nodes[k]->src[2] == nullptr || graph->nodes[k]->src[2]->op == GGML_OP_NONE)) {
  11183. rope_idx = k;
  11184. current_set.push_back(rope_idx);
  11185. used[rope_idx] = true;
  11186. break;
  11187. }
  11188. }
  11189. }
  11190. // Look for ROPE + VIEW + SET_ROWS and make them consecutive
  11191. if (graph->nodes[rope_idx]->op == GGML_OP_ROPE) {
  11192. int view_idx = -1;
  11193. int set_rows_idx = -1;
  11194. for (int k = rope_idx+1; k < std::min(rope_idx + 10, graph->n_nodes); ++k) {
  11195. if (view_idx == -1 &&
  11196. graph->nodes[k]->op == GGML_OP_VIEW &&
  11197. graph->nodes[k]->src[0] == graph->nodes[rope_idx]) {
  11198. view_idx = k;
  11199. continue;
  11200. }
  11201. if (view_idx != -1 &&
  11202. set_rows_idx == -1 &&
  11203. graph->nodes[k]->op == GGML_OP_SET_ROWS &&
  11204. graph->nodes[k]->src[0] == graph->nodes[view_idx]) {
  11205. set_rows_idx = k;
  11206. break;
  11207. }
  11208. }
  11209. if (set_rows_idx != -1) {
  11210. current_set.push_back(view_idx);
  11211. current_set.push_back(set_rows_idx);
  11212. used[view_idx] = true;
  11213. used[set_rows_idx] = true;
  11214. }
  11215. }
  11216. // Look for MUL_MAT_ID + ADD_ID + MUL
  11217. if (j > 0 &&
  11218. graph->nodes[j]->op == GGML_OP_ADD_ID &&
  11219. graph->nodes[j-1]->op == GGML_OP_MUL_MAT_ID) {
  11220. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11221. if (graph->nodes[k]->op == GGML_OP_MUL &&
  11222. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11223. // src1 must either be weights or already processed
  11224. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  11225. current_set.push_back(k);
  11226. used[k] = true;
  11227. break;
  11228. }
  11229. }
  11230. }
  11231. // Look for MUL_MAT + ADD + ADD
  11232. if (j > 0 &&
  11233. graph->nodes[j]->op == GGML_OP_ADD &&
  11234. graph->nodes[j-1]->op == GGML_OP_MUL_MAT) {
  11235. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11236. if (graph->nodes[k]->op == GGML_OP_ADD &&
  11237. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11238. // src1 must either be weights or already processed
  11239. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  11240. current_set.push_back(k);
  11241. used[k] = true;
  11242. break;
  11243. }
  11244. }
  11245. }
  11246. }
  11247. }
  11248. // Second pass grabs view nodes.
  11249. // Skip this if it would break a fusion optimization (don't split up add->rms_norm or add->add).
  11250. if (graph->nodes[current_set.back()]->op != GGML_OP_ADD) {
  11251. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11252. if (used[j]) {
  11253. continue;
  11254. }
  11255. if (!is_empty(graph->nodes[j])) {
  11256. continue;
  11257. }
  11258. bool ok = true;
  11259. for (int c = first_unused; c < j; ++c) {
  11260. bool c_in_current_set = std::find(current_set.begin(), current_set.end(), c) != current_set.end();
  11261. // skip views whose srcs haven't been processed.
  11262. if (!used[c] &&
  11263. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11264. !c_in_current_set) {
  11265. ok = false;
  11266. break;
  11267. }
  11268. }
  11269. if (ok) {
  11270. current_set.push_back(j);
  11271. }
  11272. }
  11273. }
  11274. // Push the current set into new_order
  11275. for (auto c : current_set) {
  11276. new_order.push_back(graph->nodes[c]);
  11277. used_node_set.insert(graph->nodes[c]);
  11278. used[c] = true;
  11279. }
  11280. while (first_unused < graph->n_nodes && used[first_unused]) {
  11281. first_unused++;
  11282. }
  11283. }
  11284. // Replace the graph with the new order.
  11285. for (int i = 0; i < graph->n_nodes; ++i) {
  11286. graph->nodes[i] = new_order[i];
  11287. }
  11288. }
  11289. // TODO: enable async and synchronize
  11290. static ggml_backend_i ggml_backend_vk_interface = {
  11291. /* .get_name = */ ggml_backend_vk_name,
  11292. /* .free = */ ggml_backend_vk_free,
  11293. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  11294. /* .get_tensor_async = */ ggml_backend_vk_get_tensor_async,
  11295. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  11296. /* .synchronize = */ ggml_backend_vk_synchronize,
  11297. /* .graph_plan_create = */ NULL,
  11298. /* .graph_plan_free = */ NULL,
  11299. /* .graph_plan_update = */ NULL,
  11300. /* .graph_plan_compute = */ NULL,
  11301. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  11302. /* .event_record = */ NULL,
  11303. /* .event_wait = */ NULL,
  11304. /* .graph_optimize = */ ggml_vk_graph_optimize,
  11305. };
  11306. static ggml_guid_t ggml_backend_vk_guid() {
  11307. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  11308. return &guid;
  11309. }
  11310. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  11311. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  11312. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  11313. ggml_vk_init(ctx, dev_num);
  11314. ggml_backend_t vk_backend = new ggml_backend {
  11315. /* .guid = */ ggml_backend_vk_guid(),
  11316. /* .iface = */ ggml_backend_vk_interface,
  11317. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  11318. /* .context = */ ctx,
  11319. };
  11320. return vk_backend;
  11321. }
  11322. bool ggml_backend_is_vk(ggml_backend_t backend) {
  11323. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  11324. }
  11325. int ggml_backend_vk_get_device_count() {
  11326. return ggml_vk_get_device_count();
  11327. }
  11328. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  11329. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11330. int dev_idx = vk_instance.device_indices[device];
  11331. ggml_vk_get_device_description(dev_idx, description, description_size);
  11332. }
  11333. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  11334. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11335. GGML_ASSERT(device < (int) vk_instance.device_supports_membudget.size());
  11336. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  11337. vk::PhysicalDeviceMemoryBudgetPropertiesEXT budgetprops;
  11338. vk::PhysicalDeviceMemoryProperties2 memprops = {};
  11339. const bool membudget_supported = vk_instance.device_supports_membudget[device];
  11340. const bool is_integrated_gpu = vkdev.getProperties().deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  11341. if (membudget_supported) {
  11342. memprops.pNext = &budgetprops;
  11343. }
  11344. vkdev.getMemoryProperties2(&memprops);
  11345. *total = 0;
  11346. *free = 0;
  11347. for (uint32_t i = 0; i < memprops.memoryProperties.memoryHeapCount; ++i) {
  11348. const vk::MemoryHeap & heap = memprops.memoryProperties.memoryHeaps[i];
  11349. if (is_integrated_gpu || (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal)) {
  11350. *total += heap.size;
  11351. if (membudget_supported && i < budgetprops.heapUsage.size()) {
  11352. *free += budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
  11353. } else {
  11354. *free += heap.size;
  11355. }
  11356. }
  11357. }
  11358. }
  11359. static vk::PhysicalDeviceType ggml_backend_vk_get_device_type(int device_idx) {
  11360. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11361. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11362. vk::PhysicalDeviceProperties2 props = {};
  11363. device.getProperties2(&props);
  11364. return props.properties.deviceType;
  11365. }
  11366. static std::string ggml_backend_vk_get_device_pci_id(int device_idx) {
  11367. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11368. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11369. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  11370. bool ext_support = false;
  11371. for (const auto& properties : ext_props) {
  11372. if (strcmp("VK_EXT_pci_bus_info", properties.extensionName) == 0) {
  11373. ext_support = true;
  11374. break;
  11375. }
  11376. }
  11377. if (!ext_support) {
  11378. return "";
  11379. }
  11380. vk::PhysicalDeviceProperties2 props = {};
  11381. vk::PhysicalDevicePCIBusInfoPropertiesEXT pci_bus_info = {};
  11382. props.pNext = &pci_bus_info;
  11383. device.getProperties2(&props);
  11384. const uint32_t pci_domain = pci_bus_info.pciDomain;
  11385. const uint32_t pci_bus = pci_bus_info.pciBus;
  11386. const uint32_t pci_device = pci_bus_info.pciDevice;
  11387. const uint8_t pci_function = (uint8_t) pci_bus_info.pciFunction; // pci function is between 0 and 7, prevent printf overflow warning
  11388. char pci_bus_id[16] = {};
  11389. snprintf(pci_bus_id, sizeof(pci_bus_id), "%04x:%02x:%02x.%x", pci_domain, pci_bus, pci_device, pci_function);
  11390. return std::string(pci_bus_id);
  11391. }
  11392. //////////////////////////
  11393. struct ggml_backend_vk_device_context {
  11394. size_t device;
  11395. std::string name;
  11396. std::string description;
  11397. bool is_integrated_gpu;
  11398. std::string pci_bus_id;
  11399. };
  11400. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  11401. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11402. return ctx->name.c_str();
  11403. }
  11404. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  11405. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11406. return ctx->description.c_str();
  11407. }
  11408. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  11409. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  11410. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  11411. }
  11412. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  11413. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11414. return ggml_backend_vk_buffer_type(ctx->device);
  11415. }
  11416. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  11417. UNUSED(dev);
  11418. return ggml_backend_vk_host_buffer_type();
  11419. }
  11420. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  11421. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11422. return ctx->is_integrated_gpu ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
  11423. }
  11424. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  11425. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11426. props->name = ggml_backend_vk_device_get_name(dev);
  11427. props->description = ggml_backend_vk_device_get_description(dev);
  11428. props->type = ggml_backend_vk_device_get_type(dev);
  11429. props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str();
  11430. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  11431. props->caps = {
  11432. /* .async = */ false,
  11433. /* .host_buffer = */ true,
  11434. /* .buffer_from_host_ptr = */ false,
  11435. /* .events = */ false,
  11436. };
  11437. }
  11438. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  11439. UNUSED(params);
  11440. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11441. return ggml_backend_vk_init(ctx->device);
  11442. }
  11443. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  11444. switch (op->op) {
  11445. case GGML_OP_UNARY:
  11446. switch (ggml_get_unary_op(op)) {
  11447. case GGML_UNARY_OP_EXP:
  11448. case GGML_UNARY_OP_GELU:
  11449. case GGML_UNARY_OP_GELU_ERF:
  11450. case GGML_UNARY_OP_GELU_QUICK:
  11451. case GGML_UNARY_OP_SILU:
  11452. case GGML_UNARY_OP_RELU:
  11453. case GGML_UNARY_OP_NEG:
  11454. case GGML_UNARY_OP_TANH:
  11455. case GGML_UNARY_OP_SIGMOID:
  11456. case GGML_UNARY_OP_HARDSIGMOID:
  11457. case GGML_UNARY_OP_HARDSWISH:
  11458. case GGML_UNARY_OP_ABS:
  11459. return ggml_is_contiguous(op->src[0]) &&
  11460. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11461. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11462. (op->src[0]->type == op->type);
  11463. default:
  11464. return false;
  11465. }
  11466. case GGML_OP_GLU:
  11467. switch (ggml_get_glu_op(op)) {
  11468. case GGML_GLU_OP_GEGLU:
  11469. case GGML_GLU_OP_REGLU:
  11470. case GGML_GLU_OP_SWIGLU:
  11471. case GGML_GLU_OP_SWIGLU_OAI:
  11472. case GGML_GLU_OP_GEGLU_ERF:
  11473. case GGML_GLU_OP_GEGLU_QUICK:
  11474. return ggml_is_contiguous(op->src[0]) &&
  11475. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11476. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11477. (op->src[0]->type == op->type);
  11478. default:
  11479. return false;
  11480. }
  11481. case GGML_OP_MUL_MAT:
  11482. case GGML_OP_MUL_MAT_ID:
  11483. {
  11484. ggml_type src0_type = op->src[0]->type;
  11485. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11486. const vk_device& device = ggml_vk_get_device(ctx->device);
  11487. if (op->op == GGML_OP_MUL_MAT_ID) {
  11488. if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) {
  11489. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  11490. return false;
  11491. }
  11492. }
  11493. switch (src0_type) {
  11494. case GGML_TYPE_F32:
  11495. case GGML_TYPE_F16:
  11496. case GGML_TYPE_BF16:
  11497. case GGML_TYPE_Q4_0:
  11498. case GGML_TYPE_Q4_1:
  11499. case GGML_TYPE_Q5_0:
  11500. case GGML_TYPE_Q5_1:
  11501. case GGML_TYPE_Q8_0:
  11502. case GGML_TYPE_Q2_K:
  11503. case GGML_TYPE_Q3_K:
  11504. case GGML_TYPE_Q4_K:
  11505. case GGML_TYPE_Q5_K:
  11506. case GGML_TYPE_Q6_K:
  11507. case GGML_TYPE_IQ1_S:
  11508. case GGML_TYPE_IQ1_M:
  11509. case GGML_TYPE_IQ2_XXS:
  11510. case GGML_TYPE_IQ2_XS:
  11511. case GGML_TYPE_IQ2_S:
  11512. case GGML_TYPE_IQ3_XXS:
  11513. case GGML_TYPE_IQ3_S:
  11514. case GGML_TYPE_IQ4_XS:
  11515. case GGML_TYPE_IQ4_NL:
  11516. case GGML_TYPE_MXFP4:
  11517. break;
  11518. default:
  11519. return false;
  11520. }
  11521. struct ggml_tensor * a;
  11522. struct ggml_tensor * b;
  11523. if (op->op == GGML_OP_MUL_MAT) {
  11524. a = op->src[0];
  11525. b = op->src[1];
  11526. } else {
  11527. a = op->src[2];
  11528. b = op->src[1];
  11529. }
  11530. if (a->ne[3] != b->ne[3]) {
  11531. return false;
  11532. }
  11533. 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) ||
  11534. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  11535. return false;
  11536. }
  11537. if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) {
  11538. // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader.
  11539. // So don't support this combination for now.
  11540. return false;
  11541. }
  11542. return true;
  11543. }
  11544. case GGML_OP_FLASH_ATTN_EXT:
  11545. {
  11546. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11547. auto device = ggml_vk_get_device(ctx->device);
  11548. bool coopmat2 = device->coopmat2;
  11549. uint32_t HSK = op->src[1]->ne[0];
  11550. uint32_t HSV = op->src[2]->ne[0];
  11551. if ((HSK % 8) != 0 || (HSV % 8) != 0) {
  11552. return false;
  11553. }
  11554. if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) {
  11555. return false;
  11556. }
  11557. if (op->src[0]->type != GGML_TYPE_F32) {
  11558. return false;
  11559. }
  11560. if (op->type != GGML_TYPE_F32) {
  11561. return false;
  11562. }
  11563. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  11564. return false;
  11565. }
  11566. // It's straightforward to support different K/V dequant, but would
  11567. // significantly increase the number of pipelines
  11568. if (op->src[1]->type != op->src[2]->type) {
  11569. return false;
  11570. }
  11571. switch (op->src[1]->type) {
  11572. case GGML_TYPE_F16:
  11573. case GGML_TYPE_F32:
  11574. case GGML_TYPE_Q4_0:
  11575. case GGML_TYPE_Q8_0:
  11576. // supported in scalar and coopmat2 paths
  11577. break;
  11578. case GGML_TYPE_Q4_1:
  11579. case GGML_TYPE_Q5_0:
  11580. case GGML_TYPE_Q5_1:
  11581. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  11582. //case GGML_TYPE_Q2_K:
  11583. //case GGML_TYPE_Q3_K:
  11584. //case GGML_TYPE_Q4_K:
  11585. //case GGML_TYPE_Q5_K:
  11586. //case GGML_TYPE_Q6_K:
  11587. //case GGML_TYPE_IQ1_S:
  11588. //case GGML_TYPE_IQ1_M:
  11589. //case GGML_TYPE_IQ2_XXS:
  11590. //case GGML_TYPE_IQ2_XS:
  11591. //case GGML_TYPE_IQ2_S:
  11592. //case GGML_TYPE_IQ3_XXS:
  11593. //case GGML_TYPE_IQ3_S:
  11594. //case GGML_TYPE_IQ4_XS:
  11595. case GGML_TYPE_IQ4_NL:
  11596. // currently supported only in coopmat2 path
  11597. if (!coopmat2) {
  11598. return false;
  11599. }
  11600. break;
  11601. default:
  11602. return false;
  11603. }
  11604. if (!coopmat2 && !(device->subgroup_shuffle && device->subgroup_vote)) {
  11605. // scalar/coopmat1 FA uses subgroupShuffle/subgroupAll
  11606. return false;
  11607. }
  11608. return true;
  11609. }
  11610. case GGML_OP_GET_ROWS:
  11611. {
  11612. switch (op->src[0]->type) {
  11613. case GGML_TYPE_F32:
  11614. case GGML_TYPE_F16:
  11615. case GGML_TYPE_BF16:
  11616. case GGML_TYPE_Q4_0:
  11617. case GGML_TYPE_Q4_1:
  11618. case GGML_TYPE_Q5_0:
  11619. case GGML_TYPE_Q5_1:
  11620. case GGML_TYPE_Q8_0:
  11621. case GGML_TYPE_Q2_K:
  11622. case GGML_TYPE_Q3_K:
  11623. case GGML_TYPE_Q4_K:
  11624. case GGML_TYPE_Q5_K:
  11625. case GGML_TYPE_Q6_K:
  11626. case GGML_TYPE_IQ1_S:
  11627. case GGML_TYPE_IQ1_M:
  11628. case GGML_TYPE_IQ2_XXS:
  11629. case GGML_TYPE_IQ2_XS:
  11630. case GGML_TYPE_IQ2_S:
  11631. case GGML_TYPE_IQ3_XXS:
  11632. case GGML_TYPE_IQ3_S:
  11633. case GGML_TYPE_IQ4_XS:
  11634. case GGML_TYPE_IQ4_NL:
  11635. case GGML_TYPE_MXFP4:
  11636. return true;
  11637. default:
  11638. return false;
  11639. }
  11640. }
  11641. case GGML_OP_SET_ROWS:
  11642. {
  11643. switch (op->type) {
  11644. case GGML_TYPE_F32:
  11645. case GGML_TYPE_F16:
  11646. case GGML_TYPE_BF16:
  11647. case GGML_TYPE_Q4_0:
  11648. case GGML_TYPE_Q4_1:
  11649. case GGML_TYPE_Q5_0:
  11650. case GGML_TYPE_Q5_1:
  11651. case GGML_TYPE_Q8_0:
  11652. case GGML_TYPE_IQ4_NL:
  11653. return true;
  11654. default:
  11655. return false;
  11656. }
  11657. }
  11658. case GGML_OP_CONT:
  11659. case GGML_OP_CPY:
  11660. case GGML_OP_DUP:
  11661. {
  11662. ggml_type src0_type = op->src[0]->type;
  11663. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  11664. if (src0_type == GGML_TYPE_F32) {
  11665. switch (src1_type) {
  11666. case GGML_TYPE_F32:
  11667. case GGML_TYPE_F16:
  11668. case GGML_TYPE_BF16:
  11669. case GGML_TYPE_Q4_0:
  11670. case GGML_TYPE_Q4_1:
  11671. case GGML_TYPE_Q5_0:
  11672. case GGML_TYPE_Q5_1:
  11673. case GGML_TYPE_Q8_0:
  11674. case GGML_TYPE_IQ4_NL:
  11675. return true;
  11676. default:
  11677. break;
  11678. }
  11679. }
  11680. if (src1_type == GGML_TYPE_F32) {
  11681. switch (src0_type) {
  11682. case GGML_TYPE_F16:
  11683. case GGML_TYPE_Q4_0:
  11684. case GGML_TYPE_Q4_1:
  11685. case GGML_TYPE_Q5_0:
  11686. case GGML_TYPE_Q5_1:
  11687. case GGML_TYPE_Q8_0:
  11688. case GGML_TYPE_IQ4_NL:
  11689. return true;
  11690. default:
  11691. break;
  11692. }
  11693. }
  11694. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  11695. return true;
  11696. }
  11697. if (
  11698. (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) ||
  11699. (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32)
  11700. ) {
  11701. return true;
  11702. }
  11703. // We can handle copying from a type to the same type if it's
  11704. // contiguous (memcpy). We use f16 or f32 shaders to do the copy,
  11705. // so the type/block size must be a multiple of 4.
  11706. if (src0_type == src1_type &&
  11707. ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op) &&
  11708. (ggml_type_size(src0_type) % 2) == 0) {
  11709. return true;
  11710. }
  11711. return false;
  11712. }
  11713. case GGML_OP_REPEAT:
  11714. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  11715. case GGML_OP_REPEAT_BACK:
  11716. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32;
  11717. case GGML_OP_ROPE:
  11718. case GGML_OP_ROPE_BACK:
  11719. case GGML_OP_NONE:
  11720. case GGML_OP_RESHAPE:
  11721. case GGML_OP_VIEW:
  11722. case GGML_OP_PERMUTE:
  11723. case GGML_OP_TRANSPOSE:
  11724. case GGML_OP_RMS_NORM:
  11725. return true;
  11726. case GGML_OP_NORM:
  11727. case GGML_OP_GROUP_NORM:
  11728. case GGML_OP_L2_NORM:
  11729. return ggml_is_contiguous(op->src[0]);
  11730. case GGML_OP_ADD:
  11731. case GGML_OP_SUB:
  11732. case GGML_OP_MUL:
  11733. case GGML_OP_DIV:
  11734. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11735. (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
  11736. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  11737. case GGML_OP_ADD_ID:
  11738. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 &&
  11739. op->type == GGML_TYPE_F32;
  11740. case GGML_OP_SILU_BACK:
  11741. case GGML_OP_RMS_NORM_BACK:
  11742. case GGML_OP_SQR:
  11743. case GGML_OP_SQRT:
  11744. case GGML_OP_SIN:
  11745. case GGML_OP_COS:
  11746. case GGML_OP_CLAMP:
  11747. case GGML_OP_LEAKY_RELU:
  11748. case GGML_OP_OPT_STEP_ADAMW:
  11749. case GGML_OP_OPT_STEP_SGD:
  11750. return op->src[0]->type == GGML_TYPE_F32;
  11751. case GGML_OP_LOG:
  11752. return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16;
  11753. case GGML_OP_ARGSORT:
  11754. return op->ne[0] <= max_argsort_cols;
  11755. case GGML_OP_UPSCALE:
  11756. case GGML_OP_ACC:
  11757. case GGML_OP_CONCAT:
  11758. case GGML_OP_SCALE:
  11759. case GGML_OP_PAD:
  11760. case GGML_OP_ROLL:
  11761. case GGML_OP_DIAG_MASK_INF:
  11762. case GGML_OP_SOFT_MAX:
  11763. case GGML_OP_SOFT_MAX_BACK:
  11764. return true;
  11765. case GGML_OP_SUM:
  11766. case GGML_OP_SUM_ROWS:
  11767. case GGML_OP_MEAN:
  11768. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  11769. case GGML_OP_ARGMAX:
  11770. case GGML_OP_COUNT_EQUAL:
  11771. case GGML_OP_IM2COL:
  11772. case GGML_OP_IM2COL_3D:
  11773. case GGML_OP_TIMESTEP_EMBEDDING:
  11774. case GGML_OP_CONV_2D_DW:
  11775. case GGML_OP_POOL_2D:
  11776. case GGML_OP_RWKV_WKV6:
  11777. case GGML_OP_RWKV_WKV7:
  11778. return true;
  11779. case GGML_OP_SSM_SCAN:
  11780. {
  11781. for (int i = 0; i < 6; i++) {
  11782. if (op->src[i] && ggml_is_quantized(op->src[i]->type)) {
  11783. return false;
  11784. }
  11785. }
  11786. if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) {
  11787. return false;
  11788. }
  11789. if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
  11790. return false;
  11791. }
  11792. const uint32_t d_state = op->src[0]->ne[0];
  11793. const uint32_t head_dim = op->src[0]->ne[1];
  11794. bool is_mamba2 = (op->src[3] && op->src[3]->nb[1] == sizeof(float));
  11795. if (!is_mamba2) {
  11796. return false;
  11797. }
  11798. if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
  11799. return false;
  11800. }
  11801. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11802. const vk_device& device = ggml_vk_get_device(ctx->device);
  11803. const uint32_t SPLIT_H = 16;
  11804. size_t stateC_size = SPLIT_H * d_state * sizeof(float);
  11805. if (stateC_size > device->properties.limits.maxComputeSharedMemorySize) {
  11806. return false;
  11807. }
  11808. return true;
  11809. }
  11810. case GGML_OP_SSM_CONV:
  11811. return true;
  11812. case GGML_OP_CONV_TRANSPOSE_1D:
  11813. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  11814. case GGML_OP_CONV_2D:
  11815. case GGML_OP_CONV_TRANSPOSE_2D:
  11816. {
  11817. // Op is disabled for Apple because it segfaults at pipeline create time on MoltenVK
  11818. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11819. const vk_device& device = ggml_vk_get_device(ctx->device);
  11820. if (op->op == GGML_OP_CONV_TRANSPOSE_2D &&
  11821. device->properties.limits.maxPushConstantsSize < sizeof(vk_op_conv_transpose_2d_push_constants)) {
  11822. return false;
  11823. }
  11824. // Channel-contiguous format is not supported yet.
  11825. return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11826. op->src[1]->type == GGML_TYPE_F32 &&
  11827. op->type == GGML_TYPE_F32 &&
  11828. ggml_is_contiguous(op->src[0]) &&
  11829. ggml_is_contiguous(op->src[1]) &&
  11830. ggml_is_contiguous(op));
  11831. }
  11832. default:
  11833. return false;
  11834. }
  11835. UNUSED(dev);
  11836. }
  11837. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  11838. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  11839. return false;
  11840. }
  11841. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11842. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  11843. return buft_ctx->device->idx == ctx->device;
  11844. }
  11845. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  11846. const int min_batch_size = 32;
  11847. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  11848. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  11849. UNUSED(dev);
  11850. }
  11851. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  11852. /* .get_name = */ ggml_backend_vk_device_get_name,
  11853. /* .get_description = */ ggml_backend_vk_device_get_description,
  11854. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  11855. /* .get_type = */ ggml_backend_vk_device_get_type,
  11856. /* .get_props = */ ggml_backend_vk_device_get_props,
  11857. /* .init_backend = */ ggml_backend_vk_device_init,
  11858. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  11859. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  11860. /* .buffer_from_host_ptr = */ NULL,
  11861. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  11862. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  11863. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  11864. /* .event_new = */ NULL,
  11865. /* .event_free = */ NULL,
  11866. /* .event_synchronize = */ NULL,
  11867. };
  11868. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  11869. UNUSED(reg);
  11870. return GGML_VK_NAME;
  11871. }
  11872. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  11873. UNUSED(reg);
  11874. return ggml_backend_vk_get_device_count();
  11875. }
  11876. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  11877. static std::vector<ggml_backend_dev_t> devices;
  11878. static bool initialized = false;
  11879. {
  11880. static std::mutex mutex;
  11881. std::lock_guard<std::mutex> lock(mutex);
  11882. if (!initialized) {
  11883. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  11884. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  11885. char desc[256];
  11886. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  11887. ctx->device = i;
  11888. ctx->name = GGML_VK_NAME + std::to_string(i);
  11889. ctx->description = desc;
  11890. ctx->is_integrated_gpu = ggml_backend_vk_get_device_type(i) == vk::PhysicalDeviceType::eIntegratedGpu;
  11891. ctx->pci_bus_id = ggml_backend_vk_get_device_pci_id(i);
  11892. devices.push_back(new ggml_backend_device {
  11893. /* .iface = */ ggml_backend_vk_device_i,
  11894. /* .reg = */ reg,
  11895. /* .context = */ ctx,
  11896. });
  11897. }
  11898. initialized = true;
  11899. }
  11900. }
  11901. GGML_ASSERT(device < devices.size());
  11902. return devices[device];
  11903. }
  11904. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  11905. /* .get_name = */ ggml_backend_vk_reg_get_name,
  11906. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  11907. /* .get_device = */ ggml_backend_vk_reg_get_device,
  11908. /* .get_proc_address = */ NULL,
  11909. };
  11910. ggml_backend_reg_t ggml_backend_vk_reg() {
  11911. static ggml_backend_reg reg = {
  11912. /* .api_version = */ GGML_BACKEND_API_VERSION,
  11913. /* .iface = */ ggml_backend_vk_reg_i,
  11914. /* .context = */ nullptr,
  11915. };
  11916. try {
  11917. ggml_vk_instance_init();
  11918. return &reg;
  11919. } catch (const vk::SystemError& e) {
  11920. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what());
  11921. return nullptr;
  11922. } catch (const std::exception &e) {
  11923. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: " << e.what());
  11924. return nullptr;
  11925. } catch (...) {
  11926. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: unknown exception during Vulkan init");
  11927. return nullptr;
  11928. }
  11929. }
  11930. // Extension availability
  11931. static bool ggml_vk_instance_validation_ext_available() {
  11932. #ifdef GGML_VULKAN_VALIDATE
  11933. // Check if validation layer provides the extension
  11934. const std::string layer_name = "VK_LAYER_KHRONOS_validation";
  11935. for (const auto& layer : vk::enumerateInstanceLayerProperties()) {
  11936. if (layer_name == layer.layerName.data()) {
  11937. for (const auto& ext : vk::enumerateInstanceExtensionProperties(layer_name)) {
  11938. if (strcmp("VK_EXT_validation_features", ext.extensionName.data()) == 0) {
  11939. return true;
  11940. }
  11941. }
  11942. }
  11943. }
  11944. std::cerr << "ggml_vulkan: WARNING: Validation layer or layer extension VK_EXT_validation_features not found." << std::endl;
  11945. #endif
  11946. return false;
  11947. }
  11948. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  11949. #ifdef __APPLE__
  11950. // Check for portability enumeration extension for MoltenVK support
  11951. for (const auto& properties : instance_extensions) {
  11952. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  11953. return true;
  11954. }
  11955. }
  11956. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  11957. #endif
  11958. return false;
  11959. UNUSED(instance_extensions);
  11960. }
  11961. // Extension availability
  11962. static bool ggml_vk_instance_debug_utils_ext_available(
  11963. const std::vector<vk::ExtensionProperties> & instance_extensions) {
  11964. // Check for portability enumeration extension for MoltenVK support
  11965. for (const auto & properties : instance_extensions) {
  11966. if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) {
  11967. return true;
  11968. }
  11969. }
  11970. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl;
  11971. return false;
  11972. UNUSED(instance_extensions);
  11973. }
  11974. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev) {
  11975. VkPhysicalDeviceFeatures2 device_features2;
  11976. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  11977. VkPhysicalDeviceVulkan11Features vk11_features;
  11978. vk11_features.pNext = nullptr;
  11979. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  11980. device_features2.pNext = &vk11_features;
  11981. vkGetPhysicalDeviceFeatures2(vkdev, &device_features2);
  11982. return vk11_features.storageBuffer16BitAccess;
  11983. }
  11984. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) {
  11985. switch (props.vendorID) {
  11986. case VK_VENDOR_ID_INTEL:
  11987. // Only allowing Xe2 GPU at the moment since Xe2 GPU can gain significant performance boost,
  11988. // while some older hardware (ex. Arc A770) has performance regressions
  11989. return arch == vk_device_architecture::INTEL_XE2;
  11990. case VK_VENDOR_ID_AMD:
  11991. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  11992. // Workaround for AMD proprietary driver reporting support on all GPUs
  11993. return arch == vk_device_architecture::AMD_RDNA3;
  11994. }
  11995. return true;
  11996. default:
  11997. return true;
  11998. }
  11999. }
  12000. // checks
  12001. #ifdef GGML_VULKAN_CHECK_RESULTS
  12002. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  12003. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  12004. return;
  12005. }
  12006. for (int j = 0; j < level; j++) {
  12007. std::cerr << " ";
  12008. }
  12009. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  12010. done.push_back(tensor);
  12011. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12012. if (tensor->src[i] != nullptr) {
  12013. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  12014. }
  12015. }
  12016. }
  12017. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  12018. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  12019. return;
  12020. }
  12021. i0 = std::max(i0, 5);
  12022. i1 = std::max(i1, 5);
  12023. i2 = std::max(i2, 0);
  12024. i3 = std::max(i3, 0);
  12025. fprintf(stderr, " ");
  12026. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12027. fprintf(stderr, "%7d ", idx1);
  12028. }
  12029. fprintf(stderr, "\n");
  12030. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  12031. fprintf(stderr, "%7d: ", idx0);
  12032. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12033. 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]) {
  12034. float val;
  12035. if (tensor->type == GGML_TYPE_F32) {
  12036. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12037. } else if (tensor->type == GGML_TYPE_F16) {
  12038. 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]));
  12039. } else if (tensor->type == GGML_TYPE_I32) {
  12040. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12041. } else {
  12042. GGML_ABORT("fatal error");
  12043. }
  12044. fprintf(stderr, "% 7.2f ", val);
  12045. } else {
  12046. fprintf(stderr, " ");
  12047. }
  12048. }
  12049. fprintf(stderr, "\n");
  12050. }
  12051. }
  12052. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  12053. void * tensor_data = tensor->data;
  12054. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  12055. if (is_gpu) {
  12056. const size_t tensor_size = ggml_nbytes(tensor);
  12057. tensor_data = malloc(tensor_size);
  12058. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12059. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  12060. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  12061. }
  12062. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  12063. 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;
  12064. if (tensor->src[0] != nullptr) {
  12065. 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;
  12066. }
  12067. if (tensor->src[1] != nullptr) {
  12068. 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;
  12069. }
  12070. std::cerr << std::endl << "Result:" << std::endl;
  12071. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  12072. std::cerr << std::endl;
  12073. std::vector<const ggml_tensor *> done;
  12074. ggml_vk_print_graph_origin(tensor, done);
  12075. if (is_gpu) {
  12076. free(tensor_data);
  12077. }
  12078. }
  12079. void * comp_result;
  12080. size_t comp_size;
  12081. size_t comp_nb[GGML_MAX_DIMS];
  12082. size_t check_counter = 0;
  12083. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12084. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  12085. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12086. return;
  12087. }
  12088. check_counter++;
  12089. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12090. return;
  12091. }
  12092. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  12093. struct ggml_init_params iparams = {
  12094. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  12095. /*.mem_buffer =*/ NULL,
  12096. /*.no_alloc =*/ false,
  12097. };
  12098. struct ggml_context * ggml_ctx = ggml_init(iparams);
  12099. std::array<struct ggml_tensor *, GGML_MAX_SRC> src_clone = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  12100. const char * srci_name[GGML_MAX_SRC] = {"src0", "src1", "src2", "src3", "src4", "src5", "src6", "src7", "src8", "src9"};
  12101. std::map<ggml_tensor *, ggml_tensor *> cloned_tensors;
  12102. std::vector<void *> cloned_mallocs;
  12103. struct ggml_tensor * tensor_clone = nullptr;
  12104. for (int f = 0; f < ctx->num_additional_fused_ops + 1; ++f) {
  12105. tensor = cgraph->nodes[tensor_idx + f];
  12106. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12107. ggml_tensor * srci = tensor->src[i];
  12108. if (srci == nullptr) {
  12109. continue;
  12110. }
  12111. // If a src tensor has been cloned, use that one
  12112. auto it = cloned_tensors.find(srci);
  12113. if (it != cloned_tensors.end()) {
  12114. src_clone[i] = it->second;
  12115. continue;
  12116. }
  12117. ggml_tensor * srci_clone = ggml_dup_tensor(ggml_ctx, srci);
  12118. size_t srci_size = ggml_nbytes(srci);
  12119. src_clone[i] = srci_clone;
  12120. void *src_buffer = malloc(srci_size);
  12121. cloned_mallocs.push_back(src_buffer);
  12122. srci_clone->data = src_buffer;
  12123. if (ggml_backend_buffer_is_host(srci->buffer)) {
  12124. memcpy(srci_clone->data, srci->data, srci_size);
  12125. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12126. } else if (ggml_backend_buffer_is_vk(srci->buffer)) {
  12127. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)srci->buffer->context;
  12128. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12129. uint64_t offset = vk_tensor_offset(srci) + srci->view_offs;
  12130. if (!ggml_is_contiguous(srci) && ggml_vk_dim01_contiguous(srci)) {
  12131. for (int i3 = 0; i3 < srci->ne[3]; i3++) {
  12132. for (int i2 = 0; i2 < srci->ne[2]; i2++) {
  12133. const int idx = i3*srci->ne[2] + i2;
  12134. 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]);
  12135. }
  12136. }
  12137. srci_clone->nb[0] = srci->nb[0];
  12138. srci_clone->nb[1] = srci->nb[1];
  12139. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  12140. srci_clone->nb[i] = srci_clone->nb[i - 1]*srci_clone->ne[i - 1];
  12141. }
  12142. } else {
  12143. if (offset + srci_size >= buffer_gpu->size) {
  12144. srci_size = buffer_gpu->size - offset;
  12145. }
  12146. ggml_vk_buffer_read(buffer_gpu, offset, srci_clone->data, srci_size);
  12147. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12148. }
  12149. } else {
  12150. GGML_ABORT("fatal error");
  12151. }
  12152. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12153. ggml_vk_print_tensor(srci, srci_name[i]);
  12154. }
  12155. }
  12156. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  12157. const float * params = (const float *)tensor->op_params;
  12158. 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]);
  12159. if (src_clone[4]) {
  12160. ggml_flash_attn_ext_add_sinks(tensor_clone, src_clone[4]);
  12161. }
  12162. } else if (tensor->op == GGML_OP_MUL_MAT) {
  12163. tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
  12164. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  12165. tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12166. } else if (tensor->op == GGML_OP_SUB) {
  12167. tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
  12168. } else if (tensor->op == GGML_OP_MUL) {
  12169. tensor_clone = ggml_mul(ggml_ctx, src_clone[0], src_clone[1]);
  12170. } else if (tensor->op == GGML_OP_DIV) {
  12171. tensor_clone = ggml_div(ggml_ctx, src_clone[0], src_clone[1]);
  12172. } else if (tensor->op == GGML_OP_CONCAT) {
  12173. tensor_clone = ggml_concat(ggml_ctx, src_clone[0], src_clone[1], *(int *)tensor->op_params);
  12174. } else if (tensor->op == GGML_OP_UPSCALE) {
  12175. 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]);
  12176. } else if (tensor->op == GGML_OP_SCALE) {
  12177. const float * params = (const float *)tensor->op_params;
  12178. tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]);
  12179. } else if (tensor->op == GGML_OP_SQR) {
  12180. tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]);
  12181. } else if (tensor->op == GGML_OP_SQRT) {
  12182. tensor_clone = ggml_sqrt(ggml_ctx, src_clone[0]);
  12183. } else if (tensor->op == GGML_OP_SIN) {
  12184. tensor_clone = ggml_sin(ggml_ctx, src_clone[0]);
  12185. } else if (tensor->op == GGML_OP_COS) {
  12186. tensor_clone = ggml_cos(ggml_ctx, src_clone[0]);
  12187. } else if (tensor->op == GGML_OP_LOG) {
  12188. tensor_clone = ggml_log(ggml_ctx, src_clone[0]);
  12189. } else if (tensor->op == GGML_OP_CLAMP) {
  12190. const float * params = (const float *)tensor->op_params;
  12191. tensor_clone = ggml_clamp(ggml_ctx, src_clone[0], params[0], params[1]);
  12192. } else if (tensor->op == GGML_OP_PAD) {
  12193. 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],
  12194. tensor->op_params[4], tensor->op_params[5], tensor->op_params[6], tensor->op_params[7]);
  12195. } else if (tensor->op == GGML_OP_REPEAT) {
  12196. tensor_clone = ggml_repeat(ggml_ctx, src_clone[0], tensor);
  12197. } else if (tensor->op == GGML_OP_REPEAT_BACK) {
  12198. tensor_clone = ggml_repeat_back(ggml_ctx, src_clone[0], tensor);
  12199. } else if (tensor->op == GGML_OP_ADD) {
  12200. tensor_clone = ggml_add(ggml_ctx, src_clone[0], src_clone[1]);
  12201. } else if (tensor->op == GGML_OP_ACC) {
  12202. 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]);
  12203. } else if (tensor->op == GGML_OP_NORM) {
  12204. tensor_clone = ggml_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12205. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  12206. const float * float_params = (const float *)tensor->op_params;
  12207. tensor_clone = ggml_group_norm(ggml_ctx, src_clone[0], tensor->op_params[0], float_params[1]);
  12208. } else if (tensor->op == GGML_OP_RMS_NORM) {
  12209. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12210. } else if (tensor->op == GGML_OP_RMS_NORM_BACK) {
  12211. const float eps = ((float *) tensor->op_params)[0];
  12212. tensor_clone = ggml_rms_norm_back(ggml_ctx, src_clone[0], src_clone[1], eps);
  12213. } else if (tensor->op == GGML_OP_SILU_BACK) {
  12214. tensor_clone = ggml_silu_back(ggml_ctx, src_clone[0], src_clone[1]);
  12215. } else if (tensor->op == GGML_OP_L2_NORM) {
  12216. const float eps = ((float *) tensor->op_params)[0];
  12217. tensor_clone = ggml_l2_norm(ggml_ctx, src_clone[0], eps);
  12218. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  12219. if (tensor->src[1] != nullptr) {
  12220. const float * params = (const float *)tensor->op_params;
  12221. tensor_clone = ggml_soft_max_ext(ggml_ctx, src_clone[0], src_clone[1], params[0], params[1]);
  12222. } else {
  12223. tensor_clone = ggml_soft_max(ggml_ctx, src_clone[0]);
  12224. }
  12225. } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) {
  12226. 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]);
  12227. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  12228. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]);
  12229. } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) {
  12230. const int n_dims = ((int32_t *) tensor->op_params)[1];
  12231. const int mode = ((int32_t *) tensor->op_params)[2];
  12232. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  12233. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  12234. const float freq_base = ((float *) tensor->op_params)[5];
  12235. const float freq_scale = ((float *) tensor->op_params)[6];
  12236. const float ext_factor = ((float *) tensor->op_params)[7];
  12237. const float attn_factor = ((float *) tensor->op_params)[8];
  12238. const float beta_fast = ((float *) tensor->op_params)[9];
  12239. const float beta_slow = ((float *) tensor->op_params)[10];
  12240. if (mode & GGML_ROPE_TYPE_MROPE) {
  12241. int32_t *sections = ((int32_t *) tensor->op_params) + 11;
  12242. if (tensor->op == GGML_OP_ROPE) {
  12243. 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);
  12244. } else {
  12245. 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);
  12246. }
  12247. } else {
  12248. if (tensor->op == GGML_OP_ROPE) {
  12249. 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);
  12250. } else {
  12251. 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);
  12252. }
  12253. }
  12254. } else if (tensor->op == GGML_OP_UNARY) {
  12255. switch (ggml_get_unary_op(tensor)) {
  12256. case GGML_UNARY_OP_EXP:
  12257. tensor_clone = ggml_exp(ggml_ctx, src_clone[0]);
  12258. break;
  12259. case GGML_UNARY_OP_SILU:
  12260. tensor_clone = ggml_silu(ggml_ctx, src_clone[0]);
  12261. break;
  12262. case GGML_UNARY_OP_GELU:
  12263. tensor_clone = ggml_gelu(ggml_ctx, src_clone[0]);
  12264. break;
  12265. case GGML_UNARY_OP_GELU_ERF:
  12266. tensor_clone = ggml_gelu_erf(ggml_ctx, src_clone[0]);
  12267. break;
  12268. case GGML_UNARY_OP_GELU_QUICK:
  12269. tensor_clone = ggml_gelu_quick(ggml_ctx, src_clone[0]);
  12270. break;
  12271. case GGML_UNARY_OP_RELU:
  12272. tensor_clone = ggml_relu(ggml_ctx, src_clone[0]);
  12273. break;
  12274. case GGML_UNARY_OP_NEG:
  12275. tensor_clone = ggml_neg(ggml_ctx, src_clone[0]);
  12276. break;
  12277. case GGML_UNARY_OP_TANH:
  12278. tensor_clone = ggml_tanh(ggml_ctx, src_clone[0]);
  12279. break;
  12280. case GGML_UNARY_OP_SIGMOID:
  12281. tensor_clone = ggml_sigmoid(ggml_ctx, src_clone[0]);
  12282. break;
  12283. case GGML_UNARY_OP_HARDSIGMOID:
  12284. tensor_clone = ggml_hardsigmoid(ggml_ctx, src_clone[0]);
  12285. break;
  12286. case GGML_UNARY_OP_HARDSWISH:
  12287. tensor_clone = ggml_hardswish(ggml_ctx, src_clone[0]);
  12288. break;
  12289. case GGML_UNARY_OP_ABS:
  12290. tensor_clone = ggml_abs(ggml_ctx, src_clone[0]);
  12291. break;
  12292. default:
  12293. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12294. GGML_ABORT("fatal error");
  12295. }
  12296. } else if (tensor->op == GGML_OP_GLU) {
  12297. if (src_clone[1] == nullptr) {
  12298. tensor_clone = ggml_glu(ggml_ctx, src_clone[0], (ggml_glu_op) tensor->op_params[0], tensor->op_params[1]);
  12299. } else {
  12300. tensor_clone = ggml_glu_split(ggml_ctx, src_clone[0], src_clone[1], (ggml_glu_op) tensor->op_params[0]);
  12301. }
  12302. ggml_set_op_params_i32(tensor_clone, 2, ggml_get_op_params_i32(tensor, 2));
  12303. ggml_set_op_params_i32(tensor_clone, 3, ggml_get_op_params_i32(tensor, 3));
  12304. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  12305. if (tensor->src[1] == nullptr) {
  12306. tensor_clone = ggml_dup(ggml_ctx, src_clone[0]);
  12307. tensor_clone->type = tensor->type;
  12308. } else {
  12309. tensor_clone = ggml_cpy(ggml_ctx, src_clone[0], src_clone[1]);
  12310. }
  12311. } else if (tensor->op == GGML_OP_CONT) {
  12312. tensor_clone = ggml_cont_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12313. } else if (tensor->op == GGML_OP_RESHAPE) {
  12314. tensor_clone = ggml_reshape_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12315. } else if (tensor->op == GGML_OP_VIEW) {
  12316. 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]);
  12317. } else if (tensor->op == GGML_OP_PERMUTE) {
  12318. int32_t * params = (int32_t *)tensor->op_params;
  12319. tensor_clone = ggml_permute(ggml_ctx, src_clone[0], params[0], params[1], params[2], params[3]);
  12320. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  12321. tensor_clone = ggml_transpose(ggml_ctx, src_clone[0]);
  12322. } else if (tensor->op == GGML_OP_GET_ROWS) {
  12323. tensor_clone = ggml_get_rows(ggml_ctx, src_clone[0], src_clone[1]);
  12324. } else if (tensor->op == GGML_OP_ARGSORT) {
  12325. tensor_clone = ggml_argsort(ggml_ctx, src_clone[0], (ggml_sort_order) *(int *)tensor->op_params);
  12326. } else if (tensor->op == GGML_OP_SUM) {
  12327. tensor_clone = ggml_sum(ggml_ctx, src_clone[0]);
  12328. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  12329. tensor_clone = ggml_sum_rows(ggml_ctx, src_clone[0]);
  12330. } else if (tensor->op == GGML_OP_MEAN) {
  12331. tensor_clone = ggml_mean(ggml_ctx, src_clone[0]);
  12332. } else if (tensor->op == GGML_OP_ARGMAX) {
  12333. tensor_clone = ggml_argmax(ggml_ctx, src_clone[0]);
  12334. } else if (tensor->op == GGML_OP_COUNT_EQUAL) {
  12335. tensor_clone = ggml_count_equal(ggml_ctx, src_clone[0], src_clone[1]);
  12336. } else if (tensor->op == GGML_OP_IM2COL) {
  12337. const int32_t s0 = tensor->op_params[0];
  12338. const int32_t s1 = tensor->op_params[1];
  12339. const int32_t p0 = tensor->op_params[2];
  12340. const int32_t p1 = tensor->op_params[3];
  12341. const int32_t d0 = tensor->op_params[4];
  12342. const int32_t d1 = tensor->op_params[5];
  12343. const bool is_2D = tensor->op_params[6] == 1;
  12344. tensor_clone = ggml_im2col(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  12345. } else if (tensor->op == GGML_OP_IM2COL_3D) {
  12346. const int32_t s0 = tensor->op_params[0];
  12347. const int32_t s1 = tensor->op_params[1];
  12348. const int32_t s2 = tensor->op_params[2];
  12349. const int32_t p0 = tensor->op_params[3];
  12350. const int32_t p1 = tensor->op_params[4];
  12351. const int32_t p2 = tensor->op_params[5];
  12352. const int32_t d0 = tensor->op_params[6];
  12353. const int32_t d1 = tensor->op_params[7];
  12354. const int32_t d2 = tensor->op_params[8];
  12355. const int32_t IC = tensor->op_params[9];
  12356. 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);
  12357. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  12358. const int32_t dim = tensor->op_params[0];
  12359. const int32_t max_period = tensor->op_params[1];
  12360. tensor_clone = ggml_timestep_embedding(ggml_ctx, src_clone[0], dim, max_period);
  12361. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_1D){
  12362. const int32_t s0 = tensor->op_params[0];
  12363. const int32_t p0 = tensor->op_params[1];
  12364. const int32_t d0 = tensor->op_params[2];
  12365. tensor_clone = ggml_conv_transpose_1d(ggml_ctx, src_clone[0], src_clone[1], s0, p0, d0);
  12366. } else if (tensor->op == GGML_OP_POOL_2D) {
  12367. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  12368. const int32_t k0 = tensor->op_params[1];
  12369. const int32_t k1 = tensor->op_params[2];
  12370. const int32_t s0 = tensor->op_params[3];
  12371. const int32_t s1 = tensor->op_params[4];
  12372. const int32_t p0 = tensor->op_params[5];
  12373. const int32_t p1 = tensor->op_params[6];
  12374. tensor_clone = ggml_pool_2d(ggml_ctx, src_clone[0], op, k0, k1, s0, s1, p0, p1);
  12375. } else if (tensor->op == GGML_OP_CONV_2D) {
  12376. const int32_t s0 = tensor->op_params[0];
  12377. const int32_t s1 = tensor->op_params[1];
  12378. const int32_t p0 = tensor->op_params[2];
  12379. const int32_t p1 = tensor->op_params[3];
  12380. const int32_t d0 = tensor->op_params[4];
  12381. const int32_t d1 = tensor->op_params[5];
  12382. tensor_clone = ggml_conv_2d(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  12383. } else if (tensor->op == GGML_OP_CONV_2D_DW) {
  12384. const int32_t s0 = tensor->op_params[0];
  12385. const int32_t s1 = tensor->op_params[1];
  12386. const int32_t p0 = tensor->op_params[2];
  12387. const int32_t p1 = tensor->op_params[3];
  12388. const int32_t d0 = tensor->op_params[4];
  12389. const int32_t d1 = tensor->op_params[5];
  12390. tensor_clone = ggml_conv_2d_dw_direct(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  12391. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_2D) {
  12392. const int32_t s = tensor->op_params[0];
  12393. tensor_clone = ggml_conv_transpose_2d_p0(ggml_ctx, src_clone[0], src_clone[1], s);
  12394. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  12395. const float * op_params = (const float *)tensor->op_params;
  12396. tensor_clone = ggml_leaky_relu(ggml_ctx, src_clone[0], op_params[0], false);
  12397. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  12398. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, src_clone[0], src_clone[1],
  12399. src_clone[2], src_clone[3], src_clone[4], src_clone[5]);
  12400. } else if (tensor->op == GGML_OP_RWKV_WKV7) {
  12401. tensor_clone = ggml_rwkv_wkv7(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3],
  12402. src_clone[4], src_clone[5], src_clone[6]);
  12403. } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
  12404. src_clone[0]->flags = tensor->src[0]->flags;
  12405. tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
  12406. src_clone[2], src_clone[3], src_clone[4]);
  12407. } else if (tensor->op == GGML_OP_OPT_STEP_SGD) {
  12408. src_clone[0]->flags = tensor->src[0]->flags;
  12409. tensor_clone = ggml_opt_step_sgd(ggml_ctx, src_clone[0], src_clone[1],
  12410. src_clone[2]);
  12411. } else if (tensor->op == GGML_OP_ADD_ID) {
  12412. tensor_clone = ggml_add_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12413. } else if (tensor->op == GGML_OP_SSM_SCAN) {
  12414. tensor_clone = ggml_ssm_scan(ggml_ctx, src_clone[0], src_clone[1], src_clone[2],
  12415. src_clone[3], src_clone[4], src_clone[5], src_clone[6]);
  12416. } else if (tensor->op == GGML_OP_SSM_CONV) {
  12417. tensor_clone = ggml_ssm_conv(ggml_ctx, src_clone[0], src_clone[1]);
  12418. } else if (tensor->op == GGML_OP_ROLL) {
  12419. const int32_t s0 = tensor->op_params[0];
  12420. const int32_t s1 = tensor->op_params[1];
  12421. const int32_t s2 = tensor->op_params[2];
  12422. const int32_t s3 = tensor->op_params[3];
  12423. tensor_clone = ggml_roll(ggml_ctx, src_clone[0], s0, s1, s2, s3);
  12424. }
  12425. else {
  12426. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12427. GGML_ABORT("fatal error");
  12428. }
  12429. cloned_tensors[tensor] = tensor_clone;
  12430. }
  12431. ggml_cgraph * cgraph_cpu = ggml_new_graph(ggml_ctx);
  12432. ggml_build_forward_expand(cgraph_cpu, tensor_clone);
  12433. ggml_graph_compute_with_ctx(ggml_ctx, cgraph_cpu, 8);
  12434. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12435. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  12436. }
  12437. comp_size = ggml_nbytes(tensor_clone);
  12438. comp_result = malloc(comp_size);
  12439. memcpy(comp_result, tensor_clone->data, comp_size);
  12440. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12441. for (auto m : cloned_mallocs) {
  12442. free(m);
  12443. }
  12444. ggml_free(ggml_ctx);
  12445. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  12446. }
  12447. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12448. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  12449. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12450. return;
  12451. }
  12452. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12453. return;
  12454. }
  12455. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  12456. ggml_tensor * src0 = tensor->src[0];
  12457. ggml_tensor * src1 = tensor->src[1];
  12458. ggml_tensor * src2 = tensor->src[2];
  12459. ggml_tensor * src3 = tensor->src[3];
  12460. void * tensor_data = tensor->data;
  12461. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  12462. size_t tensor_size = ggml_nbytes(tensor);
  12463. tensor_data = malloc(tensor_size);
  12464. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12465. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12466. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  12467. if (offset + tensor_size >= buffer_gpu->size) {
  12468. tensor_size = buffer_gpu->size - offset;
  12469. }
  12470. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  12471. }
  12472. float first_error_result = -1.0f;
  12473. float first_error_correct = -1.0f;
  12474. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  12475. double avg_err = 0.0;
  12476. size_t counter = 0;
  12477. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  12478. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  12479. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  12480. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  12481. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  12482. float correct = 0.0f;
  12483. float result = 0.0f;
  12484. if (buffer_size_fit) {
  12485. if (tensor->type == GGML_TYPE_F32) {
  12486. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12487. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12488. } else if (tensor->type == GGML_TYPE_F16) {
  12489. 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]));
  12490. 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]));
  12491. } else if (tensor->type == GGML_TYPE_BF16) {
  12492. 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]));
  12493. 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]));
  12494. } else if (tensor->type == GGML_TYPE_I32) {
  12495. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12496. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12497. } else if (tensor->type == GGML_TYPE_I64) {
  12498. correct = *(int64_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12499. result = *(int64_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12500. } else {
  12501. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  12502. }
  12503. } else {
  12504. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  12505. GGML_ABORT("fatal error");
  12506. }
  12507. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  12508. 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;
  12509. 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;
  12510. if (src0 != nullptr) {
  12511. 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;
  12512. }
  12513. if (src1 != nullptr) {
  12514. 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;
  12515. }
  12516. if (src2 != nullptr) {
  12517. 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;
  12518. }
  12519. if (src3 != nullptr) {
  12520. 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;
  12521. }
  12522. 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;
  12523. std::cerr << std::endl << "Result:" << std::endl;
  12524. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  12525. std::cerr << std::endl << "Correct:" << std::endl;
  12526. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  12527. std::cerr << std::endl;
  12528. std::vector<const ggml_tensor *> done;
  12529. ggml_vk_print_graph_origin(tensor, done);
  12530. GGML_ABORT("fatal error");
  12531. }
  12532. const double denom = std::fabs(correct) > 1.0f ? (std::fabs(correct) > 1e-8 ? std::fabs(correct) : 1e-8) : 1.0f;
  12533. if (first_error[0] == -1 && std::fabs(correct - result) / denom > 0.5) {
  12534. first_error[0] = i0;
  12535. first_error[1] = i1;
  12536. first_error[2] = i2;
  12537. first_error[3] = i3;
  12538. first_error_result = result;
  12539. first_error_correct = correct;
  12540. }
  12541. // Special case, value is infinite, avoid NaN result in avg_err
  12542. // NaN also appears in results, if both are nan error is 0
  12543. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  12544. avg_err += std::fabs(correct - result) / denom;
  12545. }
  12546. counter++;
  12547. }
  12548. }
  12549. }
  12550. }
  12551. avg_err /= counter;
  12552. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12553. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  12554. 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;
  12555. if (src0 != nullptr) {
  12556. 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;
  12557. }
  12558. if (src1 != nullptr) {
  12559. 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;
  12560. }
  12561. if (src2 != nullptr) {
  12562. 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;
  12563. }
  12564. if (src3 != nullptr) {
  12565. 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;
  12566. }
  12567. 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;
  12568. std::cerr << std::endl << "Result:" << std::endl;
  12569. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  12570. std::cerr << std::endl << "Correct:" << std::endl;
  12571. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  12572. std::cerr << std::endl;
  12573. std::vector<const ggml_tensor *> done;
  12574. ggml_vk_print_graph_origin(tensor, done);
  12575. }
  12576. if (avg_err > 0.5 || std::isnan(avg_err)) {
  12577. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  12578. 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;
  12579. if (src0 != nullptr) {
  12580. 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;
  12581. }
  12582. if (src1 != nullptr) {
  12583. 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;
  12584. }
  12585. if (src2 != nullptr) {
  12586. 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;
  12587. }
  12588. if (src3 != nullptr) {
  12589. 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;
  12590. }
  12591. 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;
  12592. std::cerr << std::endl << "Result:" << std::endl;
  12593. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  12594. std::cerr << std::endl << "Correct:" << std::endl;
  12595. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  12596. std::cerr << std::endl;
  12597. std::vector<const ggml_tensor *> done;
  12598. ggml_vk_print_graph_origin(tensor, done);
  12599. GGML_ABORT("fatal error");
  12600. } else {
  12601. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  12602. }
  12603. free(comp_result);
  12604. comp_result = nullptr;
  12605. comp_size = 0;
  12606. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  12607. free(tensor_data);
  12608. }
  12609. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  12610. }
  12611. #endif
  12612. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)