ggml-vulkan.cpp 724 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543
  1. #include "ggml-vulkan.h"
  2. #include <vulkan/vulkan_core.h>
  3. #if defined(GGML_VULKAN_RUN_TESTS) || defined(GGML_VULKAN_CHECK_RESULTS)
  4. #include <chrono>
  5. #include "ggml-cpu.h"
  6. #endif
  7. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  8. #define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
  9. // We use VULKAN_HPP_DEFAULT_DISPATCHER, but not VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
  10. // to avoid conflicts with applications or other libraries who might use it.
  11. #if VK_HEADER_VERSION >= 301
  12. namespace vk::detail { class DispatchLoaderDynamic; }
  13. using vk::detail::DispatchLoaderDynamic;
  14. #else
  15. namespace vk { class DispatchLoaderDynamic; }
  16. using vk::DispatchLoaderDynamic;
  17. #endif
  18. DispatchLoaderDynamic & ggml_vk_default_dispatcher();
  19. #define VULKAN_HPP_DEFAULT_DISPATCHER ggml_vk_default_dispatcher()
  20. #include <vulkan/vulkan.hpp>
  21. #include <algorithm>
  22. #include <cmath>
  23. #include <iomanip>
  24. #include <iostream>
  25. #include <tuple>
  26. #include <vector>
  27. #include <sstream>
  28. #include <utility>
  29. #include <memory>
  30. #include <limits>
  31. #include <map>
  32. #include <unordered_map>
  33. #include <memory>
  34. #include <mutex>
  35. #include <future>
  36. #include <thread>
  37. #if defined(_MSC_VER)
  38. # define NOMINMAX 1
  39. # include <windows.h>
  40. # define YIELD() YieldProcessor()
  41. #elif defined(__clang__) || defined(__GNUC__)
  42. # if defined(__x86_64__) ||defined(__i386__)
  43. # include <immintrin.h>
  44. # define YIELD() _mm_pause()
  45. # elif defined(__arm__) || defined(__aarch64__)
  46. # if defined(__clang__)
  47. # include <arm_acle.h>
  48. # define YIELD() __yield()
  49. # else
  50. # define YIELD() asm volatile("yield")
  51. # endif
  52. # endif
  53. #endif
  54. #if !defined(YIELD)
  55. #define YIELD()
  56. #endif
  57. #include "ggml-impl.h"
  58. #include "ggml-backend-impl.h"
  59. #include "ggml-vulkan-shaders.hpp"
  60. // remove this once it's more widely available in the SDK
  61. #if !defined(VK_KHR_shader_bfloat16)
  62. #define VK_KHR_shader_bfloat16 1
  63. #define VK_KHR_SHADER_BFLOAT16_SPEC_VERSION 1
  64. #define VK_KHR_SHADER_BFLOAT16_EXTENSION_NAME "VK_KHR_shader_bfloat16"
  65. #define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR ((VkStructureType)1000141000)
  66. #define VK_COMPONENT_TYPE_BFLOAT16_KHR ((VkComponentTypeKHR)1000141000)
  67. typedef struct VkPhysicalDeviceShaderBfloat16FeaturesKHR {
  68. VkStructureType sType;
  69. void* pNext;
  70. VkBool32 shaderBFloat16Type;
  71. VkBool32 shaderBFloat16DotProduct;
  72. VkBool32 shaderBFloat16CooperativeMatrix;
  73. } VkPhysicalDeviceShaderBfloat16FeaturesKHR;
  74. #endif
  75. #define ROUNDUP_POW2(M, N) (((M) + (N) - 1) & ~((N) - 1))
  76. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  77. static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; }
  78. #define VK_VENDOR_ID_AMD 0x1002
  79. #define VK_VENDOR_ID_APPLE 0x106b
  80. #define VK_VENDOR_ID_INTEL 0x8086
  81. #define VK_VENDOR_ID_NVIDIA 0x10de
  82. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 256
  83. #define GGML_VK_MAX_NODES 8192
  84. #define VK_CHECK(err, msg) \
  85. do { \
  86. vk::Result err_ = (err); \
  87. if (err_ != vk::Result::eSuccess) { \
  88. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  89. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  90. exit(1); \
  91. } \
  92. } while (0)
  93. #ifdef GGML_VULKAN_DEBUG
  94. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  95. #else
  96. #define VK_LOG_DEBUG(msg) ((void) 0)
  97. #endif // GGML_VULKAN_DEBUG
  98. struct ggml_backend_vk_context;
  99. #define MAX_PARAMETER_COUNT 12
  100. // Max number of adds that can be fused without exceeding MAX_PARAMETER_COUNT.
  101. #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3)
  102. struct vk_pipeline_struct {
  103. std::string name;
  104. vk::ShaderModule shader_module;
  105. vk::PipelineLayout layout;
  106. vk::Pipeline pipeline;
  107. uint32_t push_constant_size;
  108. uint32_t parameter_count;
  109. std::array<uint32_t, 3> wg_denoms;
  110. uint32_t align;
  111. // true if fields have been set by ggml_vk_create_pipeline
  112. bool initialized {};
  113. // set to true to request the pipeline is compiled after the dryrun
  114. bool needed {};
  115. // set to true when the shader has been compiled
  116. bool compiled {};
  117. // number of registers used, extracted from pipeline executable properties
  118. uint32_t register_count {};
  119. };
  120. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  121. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  122. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  123. struct vk_matmul_pipeline_struct {
  124. vk_pipeline l, m, s;
  125. vk_pipeline a_l, a_m, a_s;
  126. // Returns true when all unaligned pipelines are null.
  127. // We only check for unaligned variants since one of the unaligned pipelines must exist
  128. // while aligned pipelines are optional
  129. bool is_empty() const {
  130. return l == nullptr && m == nullptr && s == nullptr;
  131. }
  132. };
  133. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  134. struct vk_matmul_pipeline2 {
  135. vk_matmul_pipeline2() {
  136. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  137. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  138. }
  139. vk_matmul_pipeline f32acc;
  140. vk_matmul_pipeline f16acc;
  141. };
  142. struct vk_device_struct;
  143. typedef std::shared_ptr<vk_device_struct> vk_device;
  144. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  145. struct vk_buffer_struct;
  146. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  147. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  148. struct ggml_backend_vk_buffer_type_context {
  149. std::string name;
  150. vk_device device;
  151. };
  152. struct vk_queue;
  153. // Stores command pool/buffers. There's an instance of this
  154. // for each (context,queue) pair and for each (device,queue) pair.
  155. struct vk_command_pool {
  156. void init(vk_device& device, vk_queue *q_);
  157. void destroy(vk::Device& device);
  158. vk::CommandPool pool;
  159. uint32_t cmd_buffer_idx;
  160. std::vector<vk::CommandBuffer> cmd_buffers;
  161. vk_queue *q;
  162. };
  163. // Prevent simultaneous submissions to the same queue.
  164. // This could be per vk_queue if we stopped having two vk_queue structures
  165. // sharing the same vk::Queue.
  166. static std::mutex queue_mutex;
  167. struct vk_queue {
  168. uint32_t queue_family_index;
  169. vk::Queue queue;
  170. vk_command_pool cmd_pool;
  171. vk::PipelineStageFlags stage_flags;
  172. bool transfer_only;
  173. // copy everything except the cmd_pool
  174. void copyFrom(vk_queue &other) {
  175. queue_family_index = other.queue_family_index;
  176. queue = other.queue;
  177. stage_flags = other.stage_flags;
  178. transfer_only = other.transfer_only;
  179. }
  180. };
  181. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  182. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  183. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  184. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  185. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  186. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  187. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  188. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  189. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  190. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  191. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  192. /* .is_host = */ NULL,
  193. };
  194. #ifdef GGML_VULKAN_MEMORY_DEBUG
  195. class vk_memory_logger;
  196. #endif
  197. class vk_perf_logger;
  198. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  199. static constexpr uint32_t mul_mat_vec_max_cols = 8;
  200. static constexpr uint32_t p021_max_gqa_ratio = 8;
  201. enum vk_device_architecture {
  202. OTHER,
  203. AMD_GCN,
  204. AMD_RDNA1,
  205. AMD_RDNA2,
  206. AMD_RDNA3,
  207. INTEL_XE2,
  208. NVIDIA_PRE_TURING,
  209. };
  210. static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) {
  211. vk::PhysicalDeviceProperties props = device.getProperties();
  212. if (props.vendorID == VK_VENDOR_ID_AMD) {
  213. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  214. bool amd_shader_core_properties = false;
  215. bool integer_dot_product = false;
  216. bool subgroup_size_control = false;
  217. for (const auto& properties : ext_props) {
  218. if (strcmp("VK_AMD_shader_core_properties", properties.extensionName) == 0) {
  219. amd_shader_core_properties = true;
  220. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0) {
  221. integer_dot_product = true;
  222. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  223. subgroup_size_control = true;
  224. }
  225. }
  226. if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) {
  227. return vk_device_architecture::OTHER;
  228. }
  229. vk::PhysicalDeviceProperties2 props2;
  230. vk::PhysicalDeviceShaderCorePropertiesAMD shader_core_props_amd;
  231. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR integer_dot_props;
  232. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  233. props2.pNext = &shader_core_props_amd;
  234. shader_core_props_amd.pNext = &integer_dot_props;
  235. integer_dot_props.pNext = &subgroup_size_control_props;
  236. device.getProperties2(&props2);
  237. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 64) {
  238. return vk_device_architecture::AMD_GCN;
  239. }
  240. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 32) {
  241. // RDNA
  242. if (shader_core_props_amd.wavefrontsPerSimd == 20) {
  243. return vk_device_architecture::AMD_RDNA1;
  244. }
  245. if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
  246. return vk_device_architecture::AMD_RDNA3;
  247. }
  248. return vk_device_architecture::AMD_RDNA2;
  249. }
  250. } else if (props.vendorID == VK_VENDOR_ID_INTEL) {
  251. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  252. bool subgroup_size_control = false;
  253. for (const auto& properties : ext_props) {
  254. if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  255. subgroup_size_control = true;
  256. }
  257. }
  258. if (!subgroup_size_control) {
  259. return vk_device_architecture::OTHER;
  260. }
  261. vk::PhysicalDeviceProperties2 props2;
  262. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  263. props2.pNext = &subgroup_size_control_props;
  264. device.getProperties2(&props2);
  265. if (subgroup_size_control_props.minSubgroupSize == 16) {
  266. // Xe2 architecture uses SIMD16 while previous Xe and Gen architecture uses SIMD8.
  267. // Minimum subgroup size matches the SIMD width so we distinguish architecture by checking this value.
  268. // https://www.intel.com/content/www/us/en/content-details/824434/2024-intel-tech-tour-xe2-and-lunar-lake-s-gpu.html
  269. // https://www.intel.com/content/www/us/en/docs/oneapi/optimization-guide-gpu/2025-0/intel-xe-gpu-architecture.html
  270. return vk_device_architecture::INTEL_XE2;
  271. }
  272. } else if (props.vendorID == VK_VENDOR_ID_NVIDIA) {
  273. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  274. bool cooperative_matrix = false;
  275. // Detect "pre-turing" based on lack of coopmat support.
  276. for (const auto& properties : ext_props) {
  277. if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0) {
  278. cooperative_matrix = true;
  279. break;
  280. }
  281. }
  282. if (!cooperative_matrix) {
  283. return vk_device_architecture::NVIDIA_PRE_TURING;
  284. }
  285. }
  286. return vk_device_architecture::OTHER;
  287. }
  288. enum vk_conv_shapes {
  289. CONV_SHAPE_128x128,
  290. CONV_SHAPE_64x32,
  291. CONV_SHAPE_32x256,
  292. CONV_SHAPE_COUNT,
  293. };
  294. enum dmmv_wg_sizes {
  295. DMMV_WG_SIZE_SUBGROUP,
  296. DMMV_WG_SIZE_LARGE,
  297. DMMV_WG_SIZE_COUNT,
  298. };
  299. enum FaCodePath {
  300. FA_SCALAR,
  301. FA_COOPMAT1,
  302. FA_COOPMAT2,
  303. };
  304. struct vk_fa_pipeline_state {
  305. vk_fa_pipeline_state(uint32_t HSK, uint32_t HSV, bool small_rows, FaCodePath path, bool aligned, bool f32acc)
  306. : HSK(HSK), HSV(HSV), small_rows(small_rows), path(path), aligned(aligned), f32acc(f32acc) {}
  307. uint32_t HSK, HSV;
  308. bool small_rows;
  309. FaCodePath path;
  310. bool aligned;
  311. bool f32acc;
  312. bool operator<(const vk_fa_pipeline_state &b) const {
  313. return std::tie(HSK, HSV, small_rows, path, aligned, f32acc) <
  314. std::tie(b.HSK, b.HSV, b.small_rows, b.path, b.aligned, b.f32acc);
  315. }
  316. };
  317. enum shader_reduction_mode {
  318. SHADER_REDUCTION_MODE_SHMEM,
  319. SHADER_REDUCTION_MODE_HYBRID,
  320. SHADER_REDUCTION_MODE_SUBGROUP,
  321. SHADER_REDUCTION_MODE_COUNT,
  322. };
  323. static constexpr uint32_t num_argsort_pipelines = 11;
  324. static constexpr uint32_t max_argsort_cols = 1 << (num_argsort_pipelines-1);
  325. static constexpr uint32_t num_topk_moe_pipelines = 10;
  326. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax_norm{ GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  327. GGML_OP_VIEW, GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  328. GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV,
  329. GGML_OP_RESHAPE };
  330. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax { GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  331. GGML_OP_VIEW, GGML_OP_GET_ROWS };
  332. static constexpr std::initializer_list<ggml_op> topk_moe_late_softmax { GGML_OP_ARGSORT, GGML_OP_VIEW,
  333. GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  334. GGML_OP_SOFT_MAX, GGML_OP_RESHAPE };
  335. //node #978 ( SOFT_MAX): ffn_moe_probs-15 ( 0K) [Vulka ] use=2: ffn_moe_logits-15 ( 0K) [Vulka ]
  336. //node #979 ( RESHAPE): ffn_moe_probs-15 (re ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  337. //node #980 ( ARGSORT): ffn_moe_argsort-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  338. //node #981 ( VIEW): ffn_moe_topk-15 ( 0K) [Vulka ] use=4: ffn_moe_argsort-15 ( 0K) [Vulka ]
  339. //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 ]
  340. //node #983 ( RESHAPE): ffn_moe_weights-15 ( ( 0K) [Vulka ] use=2: ffn_moe_weights-15 ( 0K) [Vulka ]
  341. //node #984 ( SUM_ROWS): ffn_moe_weights_sum- ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ]
  342. //node #985 ( CLAMP): ffn_moe_weights_sum_ ( 0K) [Vulka ] use=1: ffn_moe_weights_sum- ( 0K) [Vulka ]
  343. //node #986 ( DIV): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ] ffn_moe_weights_sum_ ( 0K) [Vulka ]
  344. //node #987 ( RESHAPE): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights_norm ( 0K) [Vulka ]
  345. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_norm_edges {
  346. { 1, 0, 0 }, // reshape->src[0] == softmax
  347. { 2, 0, 0 }, // argsort->src[0] == softmax
  348. { 3, 0, 2 }, // view->src[0] == argsort
  349. { 4, 0, 1 }, // get_rows->src[0] == reshape
  350. { 4, 1, 3 }, // get_rows->src[1] == view
  351. { 5, 0, 4 }, // reshape->src[0] == get_rows
  352. { 6, 0, 5 }, // sum_rows->src[0] == reshape
  353. { 7, 0, 6 }, // clamp->src[0] == sum_rows
  354. { 8, 0, 5 }, // div->src[0] == reshape
  355. { 8, 1, 7 }, // div->src[1] == clamp
  356. { 9, 0, 8 }, // reshape->src[0] == div
  357. };
  358. // same as early_softmax_norm but ending after the get_rows
  359. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_edges {
  360. { 1, 0, 0 }, // reshape->src[0] == softmax
  361. { 2, 0, 0 }, // argsort->src[0] == softmax
  362. { 3, 0, 2 }, // view->src[0] == argsort
  363. { 4, 0, 1 }, // get_rows->src[0] == reshape
  364. { 4, 1, 3 }, // get_rows->src[1] == view
  365. };
  366. //node #652 ( ARGSORT): ffn_moe_argsort-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 ( 0K) [Vulka ]
  367. //node #653 ( VIEW): ffn_moe_topk-11 ( 0K) [Vulka ] use=7: ffn_moe_argsort-11 ( 0K) [Vulka ]
  368. //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 ]
  369. //node #655 ( RESHAPE): ffn_moe_weights-11 ( ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( 0K) [Vulka ]
  370. //node #656 ( SOFT_MAX): node_656 ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( ( 0K) [Vulka ]
  371. //node #657 ( RESHAPE): ffn_moe_weights_soft ( 0K) [Vulka ] use=1: node_656 ( 0K) [Vulka ]
  372. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_late_softmax_edges {
  373. { 1, 0, 0 }, // view->src[0] == argsort
  374. { 2, 1, 1 }, // get_rows->src[1] == view
  375. { 3, 0, 2 }, // reshape->src[0] == get_rows
  376. { 4, 0, 3 }, // soft_max->src[0] == reshape
  377. { 5, 0, 4 }, // reshape->src[0] == soft_max
  378. };
  379. enum topk_moe_mode {
  380. TOPK_MOE_EARLY_SOFTMAX,
  381. TOPK_MOE_EARLY_SOFTMAX_NORM,
  382. TOPK_MOE_LATE_SOFTMAX,
  383. TOPK_MOE_COUNT,
  384. };
  385. static topk_moe_mode ggml_vk_num_additional_ops_to_topk_moe_mode(uint32_t num) {
  386. topk_moe_mode mode = num == topk_moe_early_softmax_norm.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX_NORM :
  387. num == topk_moe_early_softmax.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX :
  388. TOPK_MOE_LATE_SOFTMAX;
  389. return mode;
  390. }
  391. static constexpr std::initializer_list<std::array<int, 3>> rope_view_set_rows_edges {
  392. { 1, 0, 0 }, // view->src[0] == rope
  393. { 2, 0, 1 }, // set_rows->src[0] == view
  394. };
  395. struct vk_device_struct {
  396. std::recursive_mutex mutex;
  397. vk::PhysicalDevice physical_device;
  398. vk::PhysicalDeviceProperties properties;
  399. std::string name;
  400. uint64_t max_memory_allocation_size;
  401. uint64_t max_buffer_size;
  402. uint64_t suballocation_block_size;
  403. bool fp16;
  404. bool bf16;
  405. bool pipeline_robustness;
  406. vk::Device device;
  407. uint32_t vendor_id;
  408. vk::DriverId driver_id;
  409. vk_device_architecture architecture;
  410. vk_queue compute_queue;
  411. vk_queue transfer_queue;
  412. bool single_queue;
  413. uint32_t subgroup_size;
  414. uint32_t shader_core_count;
  415. bool uma;
  416. bool prefer_host_memory;
  417. bool float_controls_rte_fp16;
  418. bool subgroup_arithmetic;
  419. bool subgroup_shuffle;
  420. bool subgroup_ballot;
  421. bool subgroup_clustered;
  422. bool multi_add;
  423. bool shader_int64;
  424. bool buffer_device_address;
  425. bool add_rms_fusion;
  426. uint32_t partials_binding_alignment;
  427. bool integer_dot_product;
  428. // 0: default, 1: force mmvq, -1: disable mmvq
  429. int32_t mmvq_mode;
  430. bool subgroup_size_control;
  431. uint32_t subgroup_min_size;
  432. uint32_t subgroup_max_size;
  433. bool subgroup_require_full_support;
  434. bool coopmat_support;
  435. bool coopmat_acc_f32_support {};
  436. bool coopmat_acc_f16_support {};
  437. bool coopmat_bf16_support {};
  438. bool coopmat_support_16x16x16_f16acc {};
  439. bool coopmat_support_16x16x16_f32acc {};
  440. bool coopmat1_fa_support {};
  441. uint32_t coopmat_m;
  442. uint32_t coopmat_n;
  443. uint32_t coopmat_k;
  444. bool coopmat_int_support;
  445. uint32_t coopmat_int_m;
  446. uint32_t coopmat_int_n;
  447. uint32_t coopmat_int_k;
  448. bool coopmat2;
  449. bool pipeline_executable_properties_support {};
  450. size_t idx;
  451. bool mul_mat_l[GGML_TYPE_COUNT];
  452. bool mul_mat_m[GGML_TYPE_COUNT];
  453. bool mul_mat_s[GGML_TYPE_COUNT];
  454. bool mul_mat_id_l[GGML_TYPE_COUNT];
  455. bool mul_mat_id_m[GGML_TYPE_COUNT];
  456. bool mul_mat_id_s[GGML_TYPE_COUNT];
  457. // set to true to indicate that some shaders need to be compiled after the dryrun
  458. bool need_compiles {};
  459. vk::DescriptorSetLayout dsl;
  460. vk_matmul_pipeline pipeline_matmul_f32 {};
  461. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  462. vk_matmul_pipeline pipeline_matmul_bf16 {};
  463. vk_matmul_pipeline2 pipeline_matmul_f16;
  464. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  465. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  466. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  467. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_COUNT];
  468. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  469. vk_matmul_pipeline pipeline_matmul_id_bf16 {};
  470. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  471. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  472. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  473. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_COUNT];
  474. vk_pipeline pipeline_matmul_split_k_reduce;
  475. vk_pipeline pipeline_quantize_q8_1;
  476. vk_pipeline pipeline_quantize_q8_1_x4;
  477. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  478. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  479. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  480. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_COUNT];
  481. vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  482. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio];
  483. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  484. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  485. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  486. vk_pipeline pipeline_acc_f32;
  487. // [src0 0=fp32,1=fp16][src1 0=fp32,1=fp16][dst 0=fp32,1=fp16]
  488. vk_pipeline pipeline_add[2][2][2];
  489. vk_pipeline pipeline_add_norepeat[2][2][2];
  490. vk_pipeline pipeline_sub[2][2][2];
  491. vk_pipeline pipeline_sub_norepeat[2][2][2];
  492. vk_pipeline pipeline_mul[2][2][2];
  493. vk_pipeline pipeline_mul_norepeat[2][2][2];
  494. vk_pipeline pipeline_div[2][2][2];
  495. vk_pipeline pipeline_div_norepeat[2][2][2];
  496. vk_pipeline pipeline_add_rms[2][2][2];
  497. vk_pipeline pipeline_add_rms_norepeat[2][2][2];
  498. // indexed by num_additional_fused_ops == num_adds - 1
  499. vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS];
  500. vk_pipeline pipeline_multi_add_rms[MAX_FUSED_ADDS];
  501. vk_pipeline pipeline_add_id_f32;
  502. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  503. vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32;
  504. vk_pipeline pipeline_scale_f32;
  505. vk_pipeline pipeline_sqr_f32;
  506. vk_pipeline pipeline_sqrt_f32;
  507. vk_pipeline pipeline_sin_f32;
  508. vk_pipeline pipeline_cos_f32;
  509. vk_pipeline pipeline_clamp_f32;
  510. vk_pipeline pipeline_pad_f32;
  511. vk_pipeline pipeline_roll_f32;
  512. vk_pipeline pipeline_repeat_f32, pipeline_repeat_back_f32;
  513. 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;
  514. 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;
  515. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  516. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  517. vk_pipeline pipeline_set_rows_i32[GGML_TYPE_COUNT];
  518. vk_pipeline pipeline_set_rows_i64[GGML_TYPE_COUNT];
  519. vk_pipeline pipeline_norm_f32;
  520. vk_pipeline pipeline_group_norm_f32;
  521. vk_pipeline pipeline_rms_norm_f32;
  522. vk_pipeline pipeline_rms_norm_mul_f32;
  523. vk_pipeline pipeline_rms_norm_partials_f32;
  524. vk_pipeline pipeline_rms_norm_mul_partials_f32;
  525. vk_pipeline pipeline_rms_norm_back_f32;
  526. vk_pipeline pipeline_l2_norm_f32;
  527. // [src/dst 0=fp32,1=fp16]
  528. vk_pipeline pipeline_exp[2];
  529. vk_pipeline pipeline_gelu[2];
  530. vk_pipeline pipeline_gelu_erf[2];
  531. vk_pipeline pipeline_gelu_quick[2];
  532. vk_pipeline pipeline_silu[2];
  533. vk_pipeline pipeline_relu[2];
  534. vk_pipeline pipeline_tanh[2];
  535. vk_pipeline pipeline_sigmoid[2];
  536. vk_pipeline pipeline_hardsigmoid[2];
  537. vk_pipeline pipeline_hardswish[2];
  538. vk_pipeline pipeline_geglu[2];
  539. vk_pipeline pipeline_reglu[2];
  540. vk_pipeline pipeline_swiglu[2];
  541. vk_pipeline pipeline_swiglu_oai[2];
  542. vk_pipeline pipeline_geglu_erf[2];
  543. vk_pipeline pipeline_geglu_quick[2];
  544. vk_pipeline pipeline_leaky_relu_f32;
  545. vk_pipeline pipeline_silu_back_f32;
  546. vk_pipeline pipeline_diag_mask_inf_f32;
  547. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  548. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  549. vk_pipeline pipeline_soft_max_back_f32;
  550. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16, pipeline_rope_norm_f32_f16;
  551. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16, pipeline_rope_neox_f32_f16;
  552. vk_pipeline pipeline_rope_multi_f32, pipeline_rope_multi_f16;
  553. vk_pipeline pipeline_rope_vision_f32, pipeline_rope_vision_f16;
  554. vk_pipeline pipeline_argsort_f32[num_argsort_pipelines];
  555. vk_pipeline pipeline_sum_rows_f32;
  556. vk_pipeline pipeline_argmax_f32;
  557. vk_pipeline pipeline_count_equal_i32;
  558. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  559. vk_pipeline pipeline_im2col_3d_f32, pipeline_im2col_3d_f32_f16;
  560. vk_pipeline pipeline_timestep_embedding_f32;
  561. vk_pipeline pipeline_conv_transpose_1d_f32;
  562. vk_pipeline pipeline_pool2d_f32;
  563. vk_pipeline pipeline_rwkv_wkv6_f32;
  564. vk_pipeline pipeline_rwkv_wkv7_f32;
  565. vk_pipeline pipeline_ssm_scan_f32_d128;
  566. vk_pipeline pipeline_ssm_scan_f32_d256;
  567. vk_pipeline pipeline_ssm_conv_f32;
  568. vk_pipeline pipeline_opt_step_adamw_f32;
  569. vk_pipeline pipeline_opt_step_sgd_f32;
  570. vk_pipeline pipeline_conv2d_f32[CONV_SHAPE_COUNT];
  571. vk_pipeline pipeline_conv2d_f16_f32[CONV_SHAPE_COUNT];
  572. vk_pipeline pipeline_conv_transpose_2d_f32[CONV_SHAPE_COUNT];
  573. vk_pipeline pipeline_conv_transpose_2d_f16_f32[CONV_SHAPE_COUNT];
  574. vk_pipeline pipeline_conv2d_dw_whcn_f32, pipeline_conv2d_dw_whcn_f16_f32;
  575. vk_pipeline pipeline_conv2d_dw_cwhn_f32, pipeline_conv2d_dw_cwhn_f16_f32;
  576. std::map<vk_fa_pipeline_state, vk_pipeline> pipeline_flash_attn_f32_f16[GGML_TYPE_COUNT];
  577. vk_pipeline pipeline_flash_attn_split_k_reduce;
  578. vk_pipeline pipeline_topk_moe[num_topk_moe_pipelines][TOPK_MOE_COUNT];
  579. std::vector<vk_pipeline_ref> all_pipelines;
  580. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  581. vk::Fence fence;
  582. vk_buffer sync_staging;
  583. ggml_backend_buffer_type buffer_type;
  584. bool disable_fusion;
  585. bool disable_host_visible_vidmem;
  586. bool allow_sysmem_fallback;
  587. bool disable_graph_optimize;
  588. #ifdef GGML_VULKAN_MEMORY_DEBUG
  589. std::unique_ptr<vk_memory_logger> memory_logger;
  590. #endif
  591. // for GGML_VK_PERF_LOGGER
  592. std::unique_ptr<vk_perf_logger> perf_logger;
  593. vk::QueryPool query_pool;
  594. int32_t num_queries;
  595. ~vk_device_struct() {
  596. VK_LOG_DEBUG("destroy device " << name);
  597. device.destroyFence(fence);
  598. ggml_vk_destroy_buffer(sync_staging);
  599. compute_queue.cmd_pool.destroy(device);
  600. transfer_queue.cmd_pool.destroy(device);
  601. for (auto& pipeline : all_pipelines) {
  602. if (pipeline.expired()) {
  603. continue;
  604. }
  605. vk_pipeline pl = pipeline.lock();
  606. ggml_vk_destroy_pipeline(device, pl);
  607. }
  608. all_pipelines.clear();
  609. device.destroyDescriptorSetLayout(dsl);
  610. device.destroy();
  611. }
  612. };
  613. void vk_command_pool::init(vk_device& device, vk_queue *q_) {
  614. cmd_buffer_idx = 0;
  615. q = q_;
  616. vk::CommandPoolCreateInfo command_pool_create_info(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), q->queue_family_index);
  617. pool = device->device.createCommandPool(command_pool_create_info);
  618. }
  619. void vk_command_pool::destroy(vk::Device& device) {
  620. device.destroyCommandPool(pool);
  621. pool = nullptr;
  622. cmd_buffers.clear();
  623. }
  624. struct vk_buffer_struct {
  625. vk::Buffer buffer = VK_NULL_HANDLE;
  626. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  627. vk::MemoryPropertyFlags memory_property_flags;
  628. void * ptr;
  629. size_t size = 0;
  630. vk::DeviceAddress bda_addr {};
  631. vk_device device;
  632. ~vk_buffer_struct() {
  633. if (size == 0) {
  634. return;
  635. }
  636. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  637. device->device.freeMemory(device_memory);
  638. device->device.destroyBuffer(buffer);
  639. }
  640. };
  641. struct vk_subbuffer {
  642. vk_buffer buffer;
  643. uint64_t offset;
  644. uint64_t size;
  645. operator vk::DescriptorBufferInfo() const {
  646. return { buffer->buffer, offset, size };
  647. }
  648. };
  649. struct vk_semaphore {
  650. vk::Semaphore s;
  651. uint64_t value;
  652. };
  653. struct vk_submission {
  654. vk::CommandBuffer buffer;
  655. std::vector<vk_semaphore> wait_semaphores;
  656. std::vector<vk_semaphore> signal_semaphores;
  657. };
  658. typedef std::vector<vk_submission> vk_sequence;
  659. struct vk_mat_mat_push_constants {
  660. uint32_t M; uint32_t N; uint32_t K;
  661. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  662. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  663. uint32_t k_split;
  664. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  665. uint32_t padded_N;
  666. };
  667. struct vk_mat_vec_push_constants {
  668. uint32_t ncols; uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  669. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  670. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  671. };
  672. struct vk_mat_mat_id_push_constants {
  673. uint32_t M; uint32_t N; uint32_t K;
  674. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  675. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  676. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  677. uint32_t padded_N;
  678. };
  679. struct vk_mat_vec_id_push_constants {
  680. uint32_t ncols; uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  681. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  682. uint32_t nei0; uint32_t ne11;
  683. };
  684. struct vk_flash_attn_push_constants {
  685. uint32_t N;
  686. uint32_t KV;
  687. uint32_t ne1;
  688. uint32_t ne2;
  689. uint32_t ne3;
  690. uint32_t neq2;
  691. uint32_t neq3;
  692. uint32_t nek2;
  693. uint32_t nek3;
  694. uint32_t nev2;
  695. uint32_t nev3;
  696. uint32_t nem1;
  697. uint32_t nem2;
  698. uint32_t nem3;
  699. uint32_t nb01;
  700. uint32_t nb02;
  701. uint32_t nb03;
  702. uint32_t nb11;
  703. uint32_t nb12;
  704. uint32_t nb13;
  705. uint32_t nb21;
  706. uint32_t nb22;
  707. uint32_t nb23;
  708. float scale;
  709. float max_bias;
  710. float logit_softcap;
  711. uint32_t mask_n_head_log2;
  712. float m0;
  713. float m1;
  714. uint32_t gqa_ratio;
  715. uint32_t split_kv;
  716. uint32_t k_num;
  717. };
  718. static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128");
  719. struct vk_op_push_constants {
  720. uint32_t KX;
  721. uint32_t KY;
  722. float param1;
  723. float param2;
  724. };
  725. struct vk_op_glu_push_constants {
  726. uint32_t N;
  727. uint32_t ne00;
  728. uint32_t ne20;
  729. uint32_t mode; // 0: default, 1: swapped, 2: split
  730. float alpha; // for swiglu_oai
  731. float limit;
  732. };
  733. struct vk_op_unary_push_constants {
  734. uint32_t ne;
  735. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  736. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  737. uint32_t misalign_offsets;
  738. float param1; float param2;
  739. uint32_t ne0_012mp; uint32_t ne0_012L;
  740. uint32_t ne0_01mp; uint32_t ne0_01L;
  741. uint32_t ne0_0mp; uint32_t ne0_0L;
  742. uint32_t ne1_012mp; uint32_t ne1_012L;
  743. uint32_t ne1_01mp; uint32_t ne1_01L;
  744. uint32_t ne1_0mp; uint32_t ne1_0L;
  745. };
  746. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  747. static vk_op_unary_push_constants vk_op_unary_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst, int64_t ne = 0) {
  748. GGML_ASSERT(ne != 0 || (ggml_nelements(src0) == ggml_nelements(dst)));
  749. ne = ne != 0 ? ne : ggml_nelements(dst);
  750. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  751. vk_op_unary_push_constants p{};
  752. p.ne = (uint32_t)ne;
  753. size_t src0_tsize = ggml_type_size(src0->type);
  754. p.ne00 = (uint32_t)src0->ne[0];
  755. p.ne01 = (uint32_t)src0->ne[1];
  756. p.ne02 = (uint32_t)src0->ne[2];
  757. p.ne03 = (uint32_t)src0->ne[3];
  758. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  759. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  760. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  761. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  762. size_t dst_tsize = ggml_type_size(dst->type);
  763. p.ne10 = (uint32_t)dst->ne[0];
  764. p.ne11 = (uint32_t)dst->ne[1];
  765. p.ne12 = (uint32_t)dst->ne[2];
  766. p.ne13 = (uint32_t)dst->ne[3];
  767. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  768. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  769. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  770. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  771. return p; // offsets are initialized later in ggml_vk_op
  772. }
  773. struct vk_op_pad_push_constants {
  774. uint32_t ne;
  775. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  776. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  777. uint32_t misalign_offsets;
  778. uint32_t lp0; uint32_t rp0;
  779. uint32_t lp1; uint32_t rp1;
  780. uint32_t lp2; uint32_t rp2;
  781. uint32_t lp3; uint32_t rp3;
  782. };
  783. static vk_op_pad_push_constants vk_op_pad_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst) {
  784. int64_t ne = ggml_nelements(dst);
  785. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  786. vk_op_pad_push_constants p{};
  787. p.ne = (uint32_t)ne;
  788. size_t src0_tsize = ggml_type_size(src0->type);
  789. p.ne00 = (uint32_t)src0->ne[0];
  790. p.ne01 = (uint32_t)src0->ne[1];
  791. p.ne02 = (uint32_t)src0->ne[2];
  792. p.ne03 = (uint32_t)src0->ne[3];
  793. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  794. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  795. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  796. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  797. size_t dst_tsize = ggml_type_size(dst->type);
  798. p.ne10 = (uint32_t)dst->ne[0];
  799. p.ne11 = (uint32_t)dst->ne[1];
  800. p.ne12 = (uint32_t)dst->ne[2];
  801. p.ne13 = (uint32_t)dst->ne[3];
  802. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  803. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  804. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  805. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  806. p.lp0 = dst->op_params[0];
  807. p.rp0 = dst->op_params[1];
  808. p.lp1 = dst->op_params[2];
  809. p.rp1 = dst->op_params[3];
  810. p.lp2 = dst->op_params[4];
  811. p.rp2 = dst->op_params[5];
  812. p.lp3 = dst->op_params[6];
  813. p.rp3 = dst->op_params[7];
  814. return p; // fastdiv values and offsets are initialized later in ggml_vk_op
  815. }
  816. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  817. // Precompute mp (m' in the paper) and L such that division
  818. // can be computed using a multiply (high 32b of 64b result)
  819. // and a shift:
  820. //
  821. // n/d = (mulhi(n, mp) + n) >> L;
  822. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  823. {
  824. // compute L = ceil(log2(d));
  825. L = 0;
  826. while (L < 32 && (uint32_t{1} << L) < d) {
  827. L++;
  828. }
  829. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  830. }
  831. template <typename T> void init_pushconst_fastdiv(T &p) {
  832. GGML_UNUSED(p);
  833. static_assert(!std::is_const<T>::value, "unexpected type");
  834. }
  835. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  836. // Compute magic values to divide by these six numbers.
  837. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  838. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  839. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  840. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  841. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  842. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  843. }
  844. struct vk_op_binary_push_constants {
  845. uint32_t ne;
  846. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  847. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  848. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  849. uint32_t misalign_offsets;
  850. float param1; float param2; int32_t param3;
  851. };
  852. struct vk_op_multi_add_push_constants {
  853. // shape for dst
  854. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23;
  855. // strides for srcs+dst
  856. uint32_t nb[MAX_PARAMETER_COUNT][4];
  857. uint32_t rms_partials;
  858. };
  859. // update multi_add.comp if this changes
  860. static_assert(MAX_PARAMETER_COUNT == 12);
  861. static_assert(sizeof(vk_op_multi_add_push_constants) <= 256);
  862. struct vk_op_topk_moe_push_constants {
  863. uint32_t n_rows;
  864. uint32_t n_expert_used;
  865. float clamp_min;
  866. float clamp_max;
  867. };
  868. struct vk_op_add_id_push_constants {
  869. uint32_t ne0;
  870. uint32_t ne1;
  871. uint32_t s01;
  872. uint32_t s02;
  873. uint32_t s11;
  874. uint32_t s21;
  875. };
  876. struct vk_op_diag_mask_push_constants {
  877. uint32_t ncols;
  878. uint32_t rows_per_channel;
  879. int32_t n_past;
  880. };
  881. struct vk_op_rope_push_constants {
  882. uint32_t ncols;
  883. uint32_t n_dims;
  884. float freq_scale;
  885. uint32_t p_delta_rows;
  886. float freq_base;
  887. float ext_factor;
  888. float attn_factor;
  889. float corr_dims[2];
  890. float theta_scale;
  891. uint32_t has_ff;
  892. uint32_t ne02;
  893. uint32_t s1;
  894. uint32_t s2;
  895. int32_t sections[4];
  896. uint32_t is_imrope;
  897. uint32_t is_back;
  898. uint32_t set_rows_stride;
  899. };
  900. struct vk_op_soft_max_push_constants {
  901. uint32_t KX;
  902. uint32_t KY;
  903. uint32_t ne00;
  904. uint32_t ne01;
  905. uint32_t ne02;
  906. uint32_t ne12;
  907. uint32_t ne13;
  908. uint32_t nb11;
  909. uint32_t nb12;
  910. uint32_t nb13;
  911. float scale;
  912. float max_bias;
  913. float m0;
  914. float m1;
  915. uint32_t n_head_log2;
  916. uint32_t nrows_x;
  917. uint32_t has_sinks;
  918. };
  919. struct vk_op_argsort_push_constants {
  920. uint32_t ncols;
  921. uint32_t nrows;
  922. int32_t order;
  923. };
  924. struct vk_op_im2col_push_constants {
  925. uint64_t dst_addr;
  926. uint32_t batch_offset; uint32_t offset_delta;
  927. uint32_t IC;
  928. uint32_t IW; uint32_t IH;
  929. uint32_t OW; uint32_t OH;
  930. uint32_t KW; uint32_t KH;
  931. uint32_t pelements;
  932. uint32_t CHW;
  933. int32_t s0; int32_t s1;
  934. int32_t p0; int32_t p1;
  935. int32_t d0; int32_t d1;
  936. };
  937. struct vk_op_im2col_3d_push_constants {
  938. uint64_t dst_addr;
  939. uint32_t nb10;
  940. uint32_t nb11;
  941. uint32_t nb12;
  942. uint32_t nb13;
  943. uint32_t s0;
  944. uint32_t s1;
  945. uint32_t s2;
  946. uint32_t p0;
  947. uint32_t p1;
  948. uint32_t p2;
  949. uint32_t d0;
  950. uint32_t d1;
  951. uint32_t d2;
  952. uint32_t IW;
  953. uint32_t IH;
  954. uint32_t ID;
  955. uint32_t IC;
  956. uint32_t KW;
  957. uint32_t OH;
  958. uint32_t KD_KH_KW;
  959. uint32_t KH_KW;
  960. uint32_t IC_KD_KH_KW;
  961. uint32_t N_OD_OH;
  962. uint32_t OD_OH;
  963. uint32_t OD_OH_OW_IC_KD_KH_KW;
  964. uint32_t OH_OW_IC_KD_KH_KW;
  965. uint32_t OW_IC_KD_KH_KW;
  966. uint32_t misalign_offsets;
  967. };
  968. struct vk_op_timestep_embedding_push_constants {
  969. uint32_t nb1;
  970. uint32_t dim;
  971. uint32_t max_period;
  972. };
  973. struct vk_op_conv_transpose_1d_push_constants {
  974. uint32_t Cout;
  975. uint32_t Cin;
  976. uint32_t K;
  977. uint32_t L;
  978. uint32_t KL;
  979. uint32_t nb01;
  980. uint32_t nb02;
  981. uint32_t nb11;
  982. uint32_t nb1;
  983. int32_t s0;
  984. };
  985. struct vk_op_pool2d_push_constants {
  986. uint32_t IW; uint32_t IH;
  987. uint32_t OW; uint32_t OH;
  988. uint32_t OC;
  989. uint32_t pelements;
  990. uint32_t op;
  991. int32_t k0; int32_t k1;
  992. int32_t s0; int32_t s1;
  993. int32_t p0; int32_t p1;
  994. };
  995. struct vk_op_rwkv_wkv6_push_constants {
  996. uint32_t B;
  997. uint32_t T;
  998. uint32_t C;
  999. uint32_t H;
  1000. };
  1001. struct vk_op_rwkv_wkv7_push_constants {
  1002. uint32_t B;
  1003. uint32_t T;
  1004. uint32_t C;
  1005. uint32_t H;
  1006. };
  1007. struct vk_op_ssm_scan_push_constants {
  1008. uint32_t nb02, nb03, nb12, nb13;
  1009. uint32_t nb21, nb22, nb31;
  1010. uint32_t nb42, nb43, nb52, nb53;
  1011. uint32_t s_off;
  1012. uint32_t n_head, d_head, n_group, n_tok;
  1013. };
  1014. struct vk_op_ssm_conv_push_constants {
  1015. uint32_t nb01, nb02;
  1016. uint32_t nb11;
  1017. uint32_t dst_nb0, dst_nb1, dst_nb2;
  1018. uint32_t nc, ncs, nr, n_t, n_s;
  1019. };
  1020. struct vk_op_conv2d_push_constants {
  1021. uint32_t Cout;
  1022. uint32_t Cin;
  1023. uint32_t N;
  1024. uint32_t KW;
  1025. uint32_t KH;
  1026. uint32_t W;
  1027. uint32_t H;
  1028. uint32_t OW;
  1029. uint32_t OH;
  1030. uint32_t s0;
  1031. uint32_t s1;
  1032. uint32_t p0;
  1033. uint32_t p1;
  1034. uint32_t d0;
  1035. uint32_t d1;
  1036. uint32_t nb01;
  1037. uint32_t nb02;
  1038. uint32_t nb03;
  1039. uint32_t nb11;
  1040. uint32_t nb12;
  1041. uint32_t nb13;
  1042. uint32_t nb1;
  1043. uint32_t nb2;
  1044. uint32_t nb3;
  1045. // init_fastdiv_values constants for dividing by KW, KW*KH, OW, OW*OH
  1046. uint32_t KWmp; uint32_t KWL;
  1047. uint32_t KWKHmp; uint32_t KWKHL;
  1048. uint32_t OWmp; uint32_t OWL;
  1049. uint32_t OWOHmp; uint32_t OWOHL;
  1050. };
  1051. template <> void init_pushconst_fastdiv(vk_op_conv2d_push_constants &p) {
  1052. // Compute magic values to divide by KW, KW*KH, OW, OW*OH
  1053. init_fastdiv_values(p.KW, p.KWmp, p.KWL);
  1054. init_fastdiv_values(p.KW*p.KH, p.KWKHmp, p.KWKHL);
  1055. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1056. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1057. }
  1058. struct vk_op_conv_transpose_2d_push_constants {
  1059. uint32_t Cout;
  1060. uint32_t Cin;
  1061. uint32_t N;
  1062. uint32_t KW;
  1063. uint32_t KH;
  1064. uint32_t W;
  1065. uint32_t H;
  1066. uint32_t OW;
  1067. uint32_t OH;
  1068. uint32_t s0;
  1069. uint32_t s1;
  1070. uint32_t p0;
  1071. uint32_t p1;
  1072. uint32_t d0;
  1073. uint32_t d1;
  1074. uint32_t nb01;
  1075. uint32_t nb02;
  1076. uint32_t nb03;
  1077. uint32_t nb11;
  1078. uint32_t nb12;
  1079. uint32_t nb13;
  1080. uint32_t nb1;
  1081. uint32_t nb2;
  1082. uint32_t nb3;
  1083. // init_fastdiv_values constants for dividing by KW, KW*KH, OW, OW*OH, s0, s1
  1084. uint32_t KWmp; uint32_t KWL;
  1085. uint32_t KWKHmp; uint32_t KWKHL;
  1086. uint32_t OWmp; uint32_t OWL;
  1087. uint32_t OWOHmp; uint32_t OWOHL;
  1088. uint32_t s0mp; uint32_t s0L;
  1089. uint32_t s1mp; uint32_t s1L;
  1090. };
  1091. template <> void init_pushconst_fastdiv(vk_op_conv_transpose_2d_push_constants &p) {
  1092. // Compute magic values to divide by KW, KW*KH, OW, OW*OH, s0, s1
  1093. init_fastdiv_values(p.KW, p.KWmp, p.KWL);
  1094. init_fastdiv_values(p.KW*p.KH, p.KWKHmp, p.KWKHL);
  1095. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1096. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1097. init_fastdiv_values(p.s0, p.s0mp, p.s0L);
  1098. init_fastdiv_values(p.s1, p.s1mp, p.s1L);
  1099. }
  1100. struct vk_op_conv2d_dw_push_constants {
  1101. uint32_t ne;
  1102. uint32_t batches;
  1103. uint32_t channels;
  1104. uint32_t dst_w;
  1105. uint32_t dst_h;
  1106. uint32_t src_w;
  1107. uint32_t src_h;
  1108. uint32_t knl_w;
  1109. uint32_t knl_h;
  1110. int32_t stride_x;
  1111. int32_t stride_y;
  1112. int32_t pad_x;
  1113. int32_t pad_y;
  1114. int32_t dilation_x;
  1115. int32_t dilation_y;
  1116. };
  1117. struct vk_op_upscale_push_constants {
  1118. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  1119. uint32_t ne00; uint32_t ne01;
  1120. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1121. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  1122. float sf0; float sf1; float sf2; float sf3;
  1123. float pixel_offset;
  1124. };
  1125. struct vk_op_sum_rows_push_constants
  1126. {
  1127. uint32_t n_cols;
  1128. uint32_t ne01, ne02;
  1129. uint32_t nb01, nb02, nb03;
  1130. uint32_t nb11, nb12, nb13;
  1131. float weight;
  1132. uint32_t misalign_offsets;
  1133. uint32_t ne0_12mp, ne0_12L;
  1134. uint32_t ne0_1mp, ne0_1L;
  1135. };
  1136. 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) {
  1137. uint32_t type_size = (uint32_t)ggml_type_size(src->type);
  1138. vk_op_sum_rows_push_constants p = {};
  1139. p.n_cols = (uint32_t)n_cols;
  1140. p.ne01 = (uint32_t)src->ne[1];
  1141. p.ne02 = (uint32_t)src->ne[2];
  1142. p.nb01 = (uint32_t)src->nb[1] / type_size;
  1143. p.nb02 = (uint32_t)src->nb[2] / type_size;
  1144. p.nb03 = (uint32_t)src->nb[3] / type_size;
  1145. p.nb11 = (uint32_t)dst->nb[1] / type_size;
  1146. p.nb12 = (uint32_t)dst->nb[2] / type_size;
  1147. p.nb13 = (uint32_t)dst->nb[3] / type_size;
  1148. p.weight = 1.0f;
  1149. return p;
  1150. }
  1151. template <> void init_pushconst_fastdiv(vk_op_sum_rows_push_constants &p) {
  1152. init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L);
  1153. init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L);
  1154. }
  1155. // Allow pre-recording command buffers
  1156. struct vk_staging_memcpy {
  1157. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  1158. void * dst;
  1159. const void * src;
  1160. size_t n;
  1161. };
  1162. struct vk_staging_memset {
  1163. vk_staging_memset(void * _dst, uint32_t _val, size_t _n) : dst(_dst), val(_val), n(_n) {}
  1164. void * dst;
  1165. uint32_t val;
  1166. size_t n;
  1167. };
  1168. struct vk_context_struct {
  1169. vk_submission * s;
  1170. std::vector<vk_sequence> seqs;
  1171. int exit_tensor_idx;
  1172. std::vector<vk_staging_memcpy> in_memcpys;
  1173. std::vector<vk_staging_memcpy> out_memcpys;
  1174. std::vector<vk_staging_memset> memsets;
  1175. vk_command_pool * p {};
  1176. };
  1177. typedef std::shared_ptr<vk_context_struct> vk_context;
  1178. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  1179. struct ggml_vk_garbage_collector {
  1180. std::vector<vk_semaphore> tl_semaphores;
  1181. std::vector<vk_semaphore> semaphores;
  1182. std::vector<vk::Event> events;
  1183. std::vector<vk_context> contexts;
  1184. };
  1185. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  1186. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  1187. static std::string format_size(size_t size) {
  1188. const size_t kib = 1024;
  1189. const size_t mib = kib * 1024;
  1190. const size_t gib = mib * 1024;
  1191. std::ostringstream oss;
  1192. oss << std::fixed << std::setprecision(2);
  1193. if (size >= gib) {
  1194. oss << static_cast<double>(size) / gib << " GiB";
  1195. } else if (size >= mib) {
  1196. oss << static_cast<double>(size) / mib << " MiB";
  1197. } else if (size >= kib) {
  1198. oss << static_cast<double>(size) / kib << " KiB";
  1199. } else {
  1200. oss << size << " B";
  1201. }
  1202. return oss.str();
  1203. }
  1204. class vk_memory_logger {
  1205. public:
  1206. vk_memory_logger(): total_device(0), total_host(0) {}
  1207. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  1208. void log_deallocation(vk_buffer_ref buf_ref);
  1209. private:
  1210. std::map<vk::Buffer, size_t> allocations; // Track allocations
  1211. size_t total_device;
  1212. size_t total_host;
  1213. };
  1214. #else
  1215. #define VK_LOG_MEMORY(msg) ((void) 0)
  1216. #endif // GGML_VULKAN_MEMORY_DEBUG
  1217. class vk_perf_logger {
  1218. public:
  1219. void print_timings() {
  1220. if (timings.empty()) {
  1221. return;
  1222. }
  1223. uint64_t total_all_op_times = 0;
  1224. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  1225. for (const auto & t : timings) {
  1226. uint64_t total_op_times = 0;
  1227. for (const auto & time : t.second) {
  1228. total_op_times += time;
  1229. }
  1230. std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0)
  1231. << " us";
  1232. // If we have as many flops entries as timing entries for the op, then compute and log the flops/S.
  1233. auto it = flops.find(t.first);
  1234. if (it != flops.end() && (it->second).size() == t.second.size()) {
  1235. uint64_t total_op_flops = 0;
  1236. for (const auto & elem : it->second) {
  1237. total_op_flops += elem;
  1238. }
  1239. std::cerr << " ("
  1240. << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) /
  1241. (double(total_op_times) / (1000.0 * 1000.0 * 1000.0))
  1242. << " GFLOPS/s)";
  1243. }
  1244. total_all_op_times += total_op_times;
  1245. std::cerr << std::endl;
  1246. }
  1247. if (timings.size() > 0) {
  1248. std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl;
  1249. }
  1250. timings.clear();
  1251. flops.clear();
  1252. }
  1253. void log_timing(const ggml_tensor * node, uint64_t time) {
  1254. if (node->op == GGML_OP_UNARY) {
  1255. timings[ggml_unary_op_name(ggml_get_unary_op(node))].push_back(time);
  1256. return;
  1257. }
  1258. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  1259. const uint64_t m = node->src[0]->ne[1];
  1260. const uint64_t n = node->ne[1];
  1261. const uint64_t k = node->src[1]->ne[0];
  1262. const uint64_t batch = node->src[1]->ne[2] * node->src[1]->ne[3];
  1263. std::string name = ggml_op_name(node->op);
  1264. if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) ||
  1265. (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) {
  1266. name += "_VEC";
  1267. }
  1268. name += " ";
  1269. name += ggml_type_name(node->src[0]->type);
  1270. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  1271. if (batch > 1) {
  1272. name += " batch=" + std::to_string(batch);
  1273. }
  1274. timings[name].push_back(time);
  1275. flops[name].push_back(m * n * (k + (k - 1)) * batch);
  1276. return;
  1277. }
  1278. if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) {
  1279. std::string name = ggml_op_name(node->op);
  1280. ggml_tensor * knl = node->src[0];
  1281. uint64_t OW = node->ne[0];
  1282. uint64_t OH = node->ne[1];
  1283. uint64_t N = node->ne[3];
  1284. uint64_t Cout = node->ne[2];
  1285. uint64_t KW = knl->ne[0];
  1286. uint64_t KH = knl->ne[1];
  1287. uint64_t Cin = node->src[1]->ne[2];
  1288. // KxCRS @ CRSxNPQ = KxNPQ -> M=K, K=CRS, N=NPQ
  1289. uint64_t size_M = Cout;
  1290. uint64_t size_K = Cin * KW * KH;
  1291. uint64_t size_N = N * OW * OH;
  1292. uint64_t n_flops = size_M * size_N * (size_K + (size_K - 1));
  1293. name += " M=Cout=" + std::to_string(size_M) + ", K=Cin*KW*KH=" + std::to_string(size_K) +
  1294. ", N=N*OW*OH=" + std::to_string(size_N);
  1295. flops[name].push_back(n_flops);
  1296. timings[name].push_back(time);
  1297. return;
  1298. }
  1299. if (node->op == GGML_OP_RMS_NORM) {
  1300. std::string name = ggml_op_name(node->op);
  1301. 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]) + ")";
  1302. timings[name].push_back(time);
  1303. return;
  1304. }
  1305. timings[ggml_op_name(node->op)].push_back(time);
  1306. }
  1307. private:
  1308. std::map<std::string, std::vector<uint64_t>> timings;
  1309. std::map<std::string, std::vector<uint64_t>> flops;
  1310. };
  1311. struct ggml_backend_vk_context {
  1312. std::string name;
  1313. vk_device device;
  1314. size_t semaphore_idx, event_idx;
  1315. ggml_vk_garbage_collector gc;
  1316. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset;
  1317. vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials;
  1318. vk::Fence fence, almost_ready_fence;
  1319. bool almost_ready_fence_pending {};
  1320. // Set before op_add and unset after op_rms_norm to indicate that the add should
  1321. // write partial sums to accumulate the square of the vector components
  1322. bool do_add_rms_partials;
  1323. // Cache most recent tensor that was converted into prealloc_y, and what pipeline it used to convert.
  1324. vk_pipeline_struct * prealloc_y_last_pipeline_used {};
  1325. const ggml_tensor * prealloc_y_last_tensor_used {};
  1326. // Track which nodes have been used since the last sync, and whether they were written to
  1327. std::vector<const ggml_tensor *> unsynced_nodes_written;
  1328. std::vector<const ggml_tensor *> unsynced_nodes_read;
  1329. // Track which prealloc buffers have pending reads that need to be synchronized.
  1330. // These are checked before writing to the buffer (and call ggml_vk_sync_buffers if set),
  1331. // and set to true after the buffer contents are consumed.
  1332. bool prealloc_x_need_sync, prealloc_y_need_sync, prealloc_split_k_need_sync;
  1333. vk_context_ref compute_ctx;
  1334. vk_context_ref transfer_ctx;
  1335. std::vector<vk_context_ref> tensor_ctxs;
  1336. std::vector<vk::DescriptorPool> descriptor_pools;
  1337. std::vector<vk::DescriptorSet> descriptor_sets;
  1338. uint32_t descriptor_set_idx {};
  1339. uint32_t pipeline_descriptor_set_requirements {};
  1340. vk_command_pool compute_cmd_pool;
  1341. vk_command_pool transfer_cmd_pool;
  1342. // number of additional consecutive nodes that are being fused with the
  1343. // node currently being processed
  1344. int num_additional_fused_ops {};
  1345. // Bitmask of which fused ops need to write an intermediate value to memory.
  1346. // Bit 'i' means nodes[start_of_fusion + i] writes to memory.
  1347. // If there's no fusion, bit 0 is still set.
  1348. int fused_ops_write_mask {};
  1349. };
  1350. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  1351. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  1352. if (tensor->view_src) {
  1353. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  1354. }
  1355. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  1356. }
  1357. struct ggml_backend_vk_buffer_context {
  1358. vk_device_ref device;
  1359. vk_buffer dev_buffer;
  1360. std::string name;
  1361. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  1362. device(device),
  1363. dev_buffer(dev_buffer),
  1364. name(name) {
  1365. }
  1366. ~ggml_backend_vk_buffer_context() {
  1367. ggml_vk_destroy_buffer(dev_buffer);
  1368. }
  1369. };
  1370. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1371. static std::mutex log_mutex;
  1372. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  1373. std::lock_guard<std::mutex> guard(log_mutex);
  1374. vk_buffer buf = buf_ref.lock();
  1375. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1376. const std::string type = device ? "device" : "host";
  1377. allocations[buf->buffer] = size;
  1378. total_device += device ? size : 0;
  1379. total_host += device ? 0 : size;
  1380. 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));
  1381. }
  1382. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  1383. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  1384. return;
  1385. }
  1386. std::lock_guard<std::mutex> guard(log_mutex);
  1387. vk_buffer buf = buf_ref.lock();
  1388. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1389. std::string type = device ? "device" : "host";
  1390. auto it = allocations.find(buf->buffer);
  1391. total_device -= device ? it->second : 0;
  1392. total_host -= device ? 0 : it->second;
  1393. if (it != allocations.end()) {
  1394. 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));
  1395. allocations.erase(it);
  1396. } else {
  1397. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  1398. }
  1399. }
  1400. #endif // GGML_VULKAN_MEMORY_DEBUG
  1401. struct vk_instance_t {
  1402. vk::Instance instance;
  1403. bool debug_utils_support = false; // VK_EXT_debug_utils enabled
  1404. PFN_vkSetDebugUtilsObjectNameEXT pfn_vkSetDebugUtilsObjectNameEXT = {};
  1405. PFN_vkQueueBeginDebugUtilsLabelEXT pfn_vkQueueBeginDebugUtilsLabelEXT = {};
  1406. PFN_vkQueueEndDebugUtilsLabelEXT pfn_vkQueueEndDebugUtilsLabelEXT = {};
  1407. PFN_vkCmdBeginDebugUtilsLabelEXT pfn_vkCmdBeginDebugUtilsLabelEXT = {};
  1408. PFN_vkCmdEndDebugUtilsLabelEXT pfn_vkCmdEndDebugUtilsLabelEXT = {};
  1409. PFN_vkCmdInsertDebugUtilsLabelEXT pfn_vkCmdInsertDebugUtilsLabelEXT = {};
  1410. std::vector<size_t> device_indices;
  1411. std::vector<bool> device_supports_membudget;
  1412. vk_device devices[GGML_VK_MAX_DEVICES];
  1413. };
  1414. static bool vk_instance_initialized = false;
  1415. static vk_instance_t vk_instance;
  1416. static bool vk_perf_logger_enabled = false;
  1417. #ifdef GGML_VULKAN_CHECK_RESULTS
  1418. static size_t vk_skip_checks;
  1419. static size_t vk_output_tensor;
  1420. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  1421. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1422. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1423. #endif
  1424. 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);
  1425. static void ggml_backend_vk_free(ggml_backend_t backend);
  1426. static VkDeviceSize ggml_vk_get_max_buffer_range(const ggml_backend_vk_context * ctx, const vk_buffer &buf, const VkDeviceSize offset) {
  1427. const VkDeviceSize range = std::min(VkDeviceSize{buf->size - offset},
  1428. VkDeviceSize{ctx->device->properties.limits.maxStorageBufferRange});
  1429. return range;
  1430. }
  1431. // Wait for ctx->fence to be signaled.
  1432. static void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) {
  1433. // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep
  1434. // during this wait.
  1435. if (ctx->almost_ready_fence_pending) {
  1436. VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence");
  1437. ctx->device->device.resetFences({ ctx->almost_ready_fence });
  1438. ctx->almost_ready_fence_pending = false;
  1439. }
  1440. // Spin (w/pause) waiting for the graph to finish executing.
  1441. vk::Result result;
  1442. while ((result = ctx->device->device.getFenceStatus(ctx->fence)) != vk::Result::eSuccess) {
  1443. if (result != vk::Result::eNotReady) {
  1444. fprintf(stderr, "ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__);
  1445. exit(1);
  1446. }
  1447. for (uint32_t i = 0; i < 100; ++i) {
  1448. YIELD();
  1449. YIELD();
  1450. YIELD();
  1451. YIELD();
  1452. YIELD();
  1453. YIELD();
  1454. YIELD();
  1455. YIELD();
  1456. YIELD();
  1457. YIELD();
  1458. }
  1459. }
  1460. ctx->device->device.resetFences({ ctx->fence });
  1461. }
  1462. // variables to track number of compiles in progress
  1463. static uint32_t compile_count = 0;
  1464. static std::mutex compile_count_mutex;
  1465. static std::condition_variable compile_count_cond;
  1466. 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,
  1467. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  1468. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  1469. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  1470. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  1471. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  1472. GGML_ASSERT(parameter_count > 0);
  1473. GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT);
  1474. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  1475. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  1476. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  1477. vk::PushConstantRange pcr(
  1478. vk::ShaderStageFlagBits::eCompute,
  1479. 0,
  1480. pipeline->push_constant_size
  1481. );
  1482. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr);
  1483. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  1484. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  1485. for (size_t i = 0; i < specialization_constants.size(); i++) {
  1486. specialization_entries[i].constantID = i;
  1487. specialization_entries[i].offset = i * sizeof(uint32_t);
  1488. specialization_entries[i].size = sizeof(uint32_t);
  1489. }
  1490. vk::SpecializationInfo specialization_info(
  1491. specialization_entries.size(),
  1492. specialization_entries.data(),
  1493. specialization_constants.size() * sizeof(uint32_t),
  1494. specialization_constants.data()
  1495. );
  1496. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  1497. if (device->subgroup_require_full_support && require_full_subgroups) {
  1498. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  1499. }
  1500. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  1501. pipeline_shader_stage_create_flags,
  1502. vk::ShaderStageFlagBits::eCompute,
  1503. pipeline->shader_module,
  1504. entrypoint.c_str(),
  1505. &specialization_info);
  1506. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  1507. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  1508. if (device->subgroup_size_control && required_subgroup_size > 0) {
  1509. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  1510. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  1511. }
  1512. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  1513. device->pipeline_executable_properties_support ?
  1514. vk::PipelineCreateFlagBits::eCaptureStatisticsKHR :
  1515. vk::PipelineCreateFlags{},
  1516. pipeline_shader_create_info,
  1517. pipeline->layout);
  1518. vk::PipelineRobustnessCreateInfoEXT rci;
  1519. if (device->pipeline_robustness && disable_robustness) {
  1520. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1521. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1522. compute_pipeline_create_info.setPNext(&rci);
  1523. }
  1524. try {
  1525. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  1526. } catch (const vk::SystemError& e) {
  1527. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  1528. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1529. throw e;
  1530. }
  1531. pipeline->compiled = true;
  1532. if (vk_instance.debug_utils_support) {
  1533. vk::DebugUtilsObjectNameInfoEXT duoni;
  1534. duoni.objectType = vk::ObjectType::ePipeline;
  1535. duoni.pObjectName = pipeline->name.c_str();
  1536. duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast<VkPipeline>(pipeline->pipeline));
  1537. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast<VkDebugUtilsObjectNameInfoEXT &>(duoni));
  1538. }
  1539. if (device->pipeline_executable_properties_support) {
  1540. vk::PipelineExecutableInfoKHR executableInfo;
  1541. executableInfo.pipeline = pipeline->pipeline;
  1542. auto statistics = device->device.getPipelineExecutableStatisticsKHR(executableInfo);
  1543. for (auto & s : statistics) {
  1544. // "Register Count" is reported by NVIDIA drivers.
  1545. if (strcmp(s.name, "Register Count") == 0) {
  1546. VK_LOG_DEBUG(pipeline->name << " " << s.name << ": " << s.value.u64 << " registers");
  1547. pipeline->register_count = (uint32_t)s.value.u64;
  1548. }
  1549. }
  1550. }
  1551. {
  1552. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1553. device->all_pipelines.push_back(pipeline);
  1554. }
  1555. {
  1556. std::lock_guard<std::mutex> guard(compile_count_mutex);
  1557. assert(compile_count > 0);
  1558. compile_count--;
  1559. }
  1560. compile_count_cond.notify_all();
  1561. }
  1562. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  1563. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  1564. device.destroyPipelineLayout(pipeline->layout);
  1565. device.destroyShaderModule(pipeline->shader_module);
  1566. device.destroyPipeline(pipeline->pipeline);
  1567. }
  1568. static void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) {
  1569. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  1570. ctx->pipeline_descriptor_set_requirements += n;
  1571. if (!pipeline->compiled) {
  1572. pipeline->needed = true;
  1573. ctx->device->need_compiles = true;
  1574. }
  1575. }
  1576. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
  1577. if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) {
  1578. // Enough descriptors are available
  1579. return;
  1580. }
  1581. vk_device& device = ctx->device;
  1582. uint32_t to_alloc = ctx->pipeline_descriptor_set_requirements - ctx->descriptor_sets.size();
  1583. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1584. uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1585. while (to_alloc > 0) {
  1586. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  1587. to_alloc -= alloc_count;
  1588. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1589. if (pool_idx >= ctx->descriptor_pools.size()) {
  1590. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  1591. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  1592. ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  1593. }
  1594. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  1595. for (uint32_t i = 0; i < alloc_count; i++) {
  1596. layouts[i] = device->dsl;
  1597. }
  1598. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
  1599. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  1600. ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
  1601. pool_idx++;
  1602. }
  1603. }
  1604. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) {
  1605. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  1606. if (p.cmd_buffers.size() > p.cmd_buffer_idx) {
  1607. // Reuse command buffer
  1608. return p.cmd_buffers[p.cmd_buffer_idx++];
  1609. }
  1610. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  1611. p.pool,
  1612. vk::CommandBufferLevel::ePrimary,
  1613. 1);
  1614. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  1615. auto buf = cmd_buffers.front();
  1616. p.cmd_buffers.push_back(buf);
  1617. p.cmd_buffer_idx++;
  1618. return buf;
  1619. }
  1620. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  1621. if (ctx->seqs.empty()) {
  1622. if (fence) {
  1623. std::lock_guard<std::mutex> guard(queue_mutex);
  1624. ctx->p->q->queue.submit({}, fence);
  1625. }
  1626. return;
  1627. }
  1628. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  1629. std::vector<std::vector<uint64_t>> tl_wait_vals;
  1630. std::vector<std::vector<uint64_t>> tl_signal_vals;
  1631. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  1632. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  1633. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  1634. std::vector<vk::SubmitInfo> submit_infos;
  1635. int idx = -1;
  1636. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  1637. size_t reserve = 0;
  1638. for (const auto& sequence : ctx->seqs) {
  1639. reserve += sequence.size();
  1640. }
  1641. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  1642. tl_wait_semaphores.reserve(reserve);
  1643. tl_wait_vals.reserve(reserve);
  1644. tl_signal_semaphores.reserve(reserve);
  1645. tl_signal_vals.reserve(reserve);
  1646. tl_submit_infos.reserve(reserve);
  1647. submit_infos.reserve(reserve);
  1648. stage_flags.reserve(reserve);
  1649. for (const auto& sequence : ctx->seqs) {
  1650. for (const auto& submission : sequence) {
  1651. stage_flags.push_back({});
  1652. idx++;
  1653. tl_wait_vals.push_back({});
  1654. tl_wait_semaphores.push_back({});
  1655. tl_signal_vals.push_back({});
  1656. tl_signal_semaphores.push_back({});
  1657. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  1658. stage_flags[idx].push_back(ctx->p->q->stage_flags);
  1659. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  1660. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  1661. }
  1662. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  1663. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  1664. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  1665. }
  1666. tl_submit_infos.push_back({
  1667. (uint32_t) submission.wait_semaphores.size(),
  1668. tl_wait_vals[idx].data(),
  1669. (uint32_t) submission.signal_semaphores.size(),
  1670. tl_signal_vals[idx].data(),
  1671. });
  1672. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  1673. tl_submit_infos[idx].pNext = nullptr;
  1674. vk::SubmitInfo si{
  1675. (uint32_t) submission.wait_semaphores.size(),
  1676. tl_wait_semaphores[idx].data(),
  1677. stage_flags[idx].data(),
  1678. 1,
  1679. &submission.buffer,
  1680. (uint32_t) submission.signal_semaphores.size(),
  1681. tl_signal_semaphores[idx].data(),
  1682. };
  1683. si.setPNext(&tl_submit_infos[idx]);
  1684. submit_infos.push_back(si);
  1685. }
  1686. }
  1687. std::lock_guard<std::mutex> guard(queue_mutex);
  1688. ctx->p->q->queue.submit(submit_infos, fence);
  1689. ctx->seqs.clear();
  1690. }
  1691. 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) {
  1692. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  1693. const uint32_t qfsize = queue_family_props.size();
  1694. // Try with avoid preferences first
  1695. for (uint32_t i = 0; i < qfsize; i++) {
  1696. 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)) {
  1697. return i;
  1698. }
  1699. }
  1700. // Fall back to only required
  1701. for (size_t i = 0; i < qfsize; i++) {
  1702. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  1703. return i;
  1704. }
  1705. }
  1706. // Fall back to reusing compute queue
  1707. for (size_t i = 0; i < qfsize; i++) {
  1708. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  1709. return i;
  1710. }
  1711. }
  1712. // Fall back to ignoring min_num_queries
  1713. for (size_t i = 0; i < qfsize; i++) {
  1714. if (queue_family_props[i].queueFlags & required) {
  1715. return i;
  1716. }
  1717. }
  1718. // 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.
  1719. // 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.
  1720. if (compute_index >= 0) {
  1721. return compute_index;
  1722. }
  1723. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  1724. for(auto &q_family : queue_family_props) {
  1725. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  1726. }
  1727. abort();
  1728. }
  1729. 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) {
  1730. VK_LOG_DEBUG("ggml_vk_create_queue()");
  1731. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1732. q.queue_family_index = queue_family_index;
  1733. q.transfer_only = transfer_only;
  1734. q.cmd_pool.init(device, &q);
  1735. q.queue = device->device.getQueue(queue_family_index, queue_index);
  1736. q.stage_flags = stage_flags;
  1737. }
  1738. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) {
  1739. vk_context result = std::make_shared<vk_context_struct>();
  1740. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  1741. ctx->gc.contexts.emplace_back(result);
  1742. result->p = &p;
  1743. return result;
  1744. }
  1745. static vk_context ggml_vk_create_temporary_context(vk_command_pool& p) {
  1746. vk_context result = std::make_shared<vk_context_struct>();
  1747. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  1748. result->p = &p;
  1749. return result;
  1750. }
  1751. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  1752. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1753. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  1754. vk::SemaphoreCreateInfo ci{};
  1755. ci.setPNext(&tci);
  1756. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1757. ctx->gc.semaphores.push_back({ semaphore, 0 });
  1758. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  1759. }
  1760. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  1761. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1762. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  1763. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  1764. vk::SemaphoreCreateInfo ci{};
  1765. ci.setPNext(&tci);
  1766. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1767. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  1768. }
  1769. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  1770. }
  1771. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  1772. if (ctx->event_idx >= ctx->gc.events.size()) {
  1773. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  1774. }
  1775. return ctx->gc.events[ctx->event_idx++];
  1776. }
  1777. static void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) {
  1778. VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()");
  1779. // Requires command buffers to be done
  1780. device->device.resetCommandPool(p.pool);
  1781. p.cmd_buffer_idx = 0;
  1782. }
  1783. static void ggml_vk_queue_command_pools_cleanup(vk_device& device) {
  1784. VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()");
  1785. // Arbitrary frequency to cleanup/reuse command buffers
  1786. static constexpr uint32_t cleanup_frequency = 10;
  1787. if (device->compute_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1788. ggml_vk_command_pool_cleanup(device, device->compute_queue.cmd_pool);
  1789. }
  1790. if (device->transfer_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1791. ggml_vk_command_pool_cleanup(device, device->transfer_queue.cmd_pool);
  1792. }
  1793. }
  1794. static uint32_t find_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  1795. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  1796. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  1797. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  1798. (flags & memory_type.propertyFlags) == flags &&
  1799. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  1800. return static_cast<int32_t>(i);
  1801. }
  1802. }
  1803. return UINT32_MAX;
  1804. }
  1805. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, const std::initializer_list<vk::MemoryPropertyFlags> & req_flags_list) {
  1806. 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]) << ")");
  1807. if (size > device->max_buffer_size) {
  1808. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device buffer size limit");
  1809. }
  1810. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  1811. if (size == 0) {
  1812. buf->size = 0;
  1813. return buf;
  1814. }
  1815. vk::BufferUsageFlags usage_flags = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst;
  1816. vk::MemoryAllocateFlags mem_flags {};
  1817. if (device->buffer_device_address) {
  1818. usage_flags |= vk::BufferUsageFlagBits::eShaderDeviceAddress;
  1819. mem_flags |= vk::MemoryAllocateFlagBits::eDeviceAddress;
  1820. }
  1821. vk::BufferCreateInfo buffer_create_info{
  1822. vk::BufferCreateFlags(),
  1823. size,
  1824. usage_flags,
  1825. vk::SharingMode::eExclusive,
  1826. 0,
  1827. nullptr,
  1828. };
  1829. buf->buffer = device->device.createBuffer(buffer_create_info);
  1830. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  1831. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  1832. const vk::MemoryAllocateFlagsInfo mem_flags_info { mem_flags };
  1833. for (auto it = req_flags_list.begin(); it != req_flags_list.end(); it++) {
  1834. const auto & req_flags = *it;
  1835. uint32_t memory_type_index = find_properties(&mem_props, &mem_req, req_flags);
  1836. if (memory_type_index == UINT32_MAX) {
  1837. continue;
  1838. }
  1839. buf->memory_property_flags = req_flags;
  1840. try {
  1841. buf->device_memory = device->device.allocateMemory({ mem_req.size, memory_type_index, &mem_flags_info });
  1842. break;
  1843. } catch (const vk::SystemError& e) {
  1844. // loop and retry
  1845. // during last attempt throw the exception
  1846. if (it + 1 == req_flags_list.end()) {
  1847. device->device.destroyBuffer(buf->buffer);
  1848. throw e;
  1849. }
  1850. }
  1851. }
  1852. if (!buf->device_memory) {
  1853. device->device.destroyBuffer(buf->buffer);
  1854. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  1855. }
  1856. buf->ptr = nullptr;
  1857. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1858. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  1859. }
  1860. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  1861. buf->device = device;
  1862. buf->size = size;
  1863. if (device->buffer_device_address) {
  1864. const vk::BufferDeviceAddressInfo addressInfo(buf->buffer);
  1865. buf->bda_addr = device->device.getBufferAddress(addressInfo);
  1866. }
  1867. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1868. device->memory_logger->log_allocation(buf, size);
  1869. #endif
  1870. return buf;
  1871. }
  1872. 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)) {
  1873. try {
  1874. return ggml_vk_create_buffer(device, size, {req_flags, fallback_flags});
  1875. } catch (const vk::SystemError& e) {
  1876. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  1877. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1878. throw e;
  1879. }
  1880. }
  1881. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  1882. vk_buffer buf;
  1883. try {
  1884. if (device->prefer_host_memory) {
  1885. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1886. vk::MemoryPropertyFlagBits::eDeviceLocal});
  1887. } else if (device->uma) {
  1888. // Fall back to host memory type
  1889. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  1890. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1891. } else if (device->disable_host_visible_vidmem) {
  1892. if (device->allow_sysmem_fallback) {
  1893. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  1894. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1895. } else {
  1896. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  1897. }
  1898. } else {
  1899. // use rebar if available, otherwise fallback to device only visible memory
  1900. if (device->allow_sysmem_fallback) {
  1901. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1902. vk::MemoryPropertyFlagBits::eDeviceLocal,
  1903. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1904. } else {
  1905. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1906. vk::MemoryPropertyFlagBits::eDeviceLocal});
  1907. }
  1908. }
  1909. } catch (const vk::SystemError& e) {
  1910. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  1911. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1912. throw e;
  1913. }
  1914. return buf;
  1915. }
  1916. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  1917. if (buf == nullptr) {
  1918. return;
  1919. }
  1920. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1921. if (buf->device != nullptr) {
  1922. buf->device->memory_logger->log_deallocation(buf);
  1923. }
  1924. #endif
  1925. buf.reset();
  1926. }
  1927. static vk_subbuffer ggml_vk_subbuffer(const ggml_backend_vk_context* ctx, const vk_buffer& buf, size_t offset = 0) {
  1928. return { buf, offset, ggml_vk_get_max_buffer_range(ctx, buf, offset) };
  1929. }
  1930. static void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) {
  1931. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  1932. const bool transfer_queue = subctx->p->q->transfer_only;
  1933. if (ctx) {
  1934. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  1935. }
  1936. subctx->s->buffer.pipelineBarrier(
  1937. subctx->p->q->stage_flags,
  1938. subctx->p->q->stage_flags,
  1939. {},
  1940. { {
  1941. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  1942. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  1943. } },
  1944. {},
  1945. {}
  1946. );
  1947. }
  1948. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  1949. VK_LOG_DEBUG("ggml_vk_wait_events()");
  1950. if (events.empty()) {
  1951. return;
  1952. }
  1953. ctx->s->buffer.waitEvents(
  1954. events,
  1955. ctx->p->q->stage_flags,
  1956. ctx->p->q->stage_flags,
  1957. {},
  1958. {},
  1959. {}
  1960. );
  1961. }
  1962. // number of rows/cols for flash attention shader
  1963. static constexpr uint32_t flash_attention_num_small_rows = 32;
  1964. static constexpr uint32_t scalar_flash_attention_num_small_rows = 1;
  1965. static uint32_t get_fa_scalar_num_large_rows(uint32_t hsv) {
  1966. if (hsv >= 192) {
  1967. return 2;
  1968. } else {
  1969. return 8;
  1970. }
  1971. }
  1972. // The FA coopmat1 shader assumes 16x16x16 matrix multiply support.
  1973. // 128 threads split into four subgroups, each subgroup does 1/4
  1974. // of the Bc dimension.
  1975. static constexpr uint32_t coopmat1_flash_attention_num_large_rows = 16;
  1976. static constexpr uint32_t scalar_flash_attention_Bc = 64;
  1977. static constexpr uint32_t scalar_flash_attention_workgroup_size = 128;
  1978. static uint32_t get_fa_num_small_rows(FaCodePath path) {
  1979. if (path == FA_COOPMAT2) {
  1980. return flash_attention_num_small_rows;
  1981. } else {
  1982. return scalar_flash_attention_num_small_rows;
  1983. }
  1984. }
  1985. 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) {
  1986. GGML_UNUSED(clamp);
  1987. GGML_UNUSED(hsv);
  1988. if (path == FA_SCALAR) {
  1989. if (small_rows) {
  1990. return {scalar_flash_attention_num_small_rows, 64};
  1991. } else {
  1992. if ((hsv | hsk) & 8) {
  1993. // HSV/HSK not being a multiple of 16 makes D_split smaller, which makes cols_per_iter
  1994. // larger, and Bc needs to be >= cols_per_thread. 64 is large enough, 32 is not.
  1995. return {get_fa_scalar_num_large_rows(hsv), 64};
  1996. } else {
  1997. return {get_fa_scalar_num_large_rows(hsv), 32};
  1998. }
  1999. }
  2000. }
  2001. if (path == FA_COOPMAT1) {
  2002. if (small_rows) {
  2003. return {scalar_flash_attention_num_small_rows, scalar_flash_attention_Bc};
  2004. } else {
  2005. return {coopmat1_flash_attention_num_large_rows, scalar_flash_attention_Bc};
  2006. }
  2007. }
  2008. // small rows, large cols
  2009. if (small_rows) {
  2010. return {get_fa_num_small_rows(FA_COOPMAT2), 32};
  2011. }
  2012. // small cols to reduce register count
  2013. if (ggml_is_quantized(type) || hsk >= 256 || hsv >= 256) {
  2014. if (hsk >= 512 || hsv >= 512) {
  2015. return {32, 32};
  2016. } else {
  2017. return {64, 32};
  2018. }
  2019. }
  2020. return {64, 64};
  2021. }
  2022. static uint32_t fa_align(FaCodePath path, uint32_t hsk, uint32_t hsv, ggml_type type, bool small_rows) {
  2023. return fa_rows_cols(path, hsk, hsv, 0, type, small_rows)[1];
  2024. }
  2025. 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) {
  2026. uint32_t lut_size = 0;
  2027. switch (src0_type) {
  2028. case GGML_TYPE_IQ1_S:
  2029. case GGML_TYPE_IQ1_M:
  2030. lut_size = 2*2048;
  2031. break;
  2032. case GGML_TYPE_IQ2_XXS:
  2033. lut_size = 8*256;
  2034. break;
  2035. case GGML_TYPE_IQ2_XS:
  2036. lut_size = 8*512;
  2037. break;
  2038. case GGML_TYPE_IQ2_S:
  2039. lut_size = 8*1024;
  2040. break;
  2041. case GGML_TYPE_IQ3_XXS:
  2042. lut_size = 4*256;
  2043. break;
  2044. case GGML_TYPE_IQ3_S:
  2045. lut_size = 4*512;
  2046. break;
  2047. case GGML_TYPE_IQ4_NL:
  2048. case GGML_TYPE_IQ4_XS:
  2049. case GGML_TYPE_MXFP4:
  2050. lut_size = 4*16;
  2051. break;
  2052. default:
  2053. break;
  2054. }
  2055. // Needs to be kept up to date on shader changes
  2056. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  2057. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  2058. const uint32_t warps = warptile[0] / warptile[10];
  2059. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  2060. const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0;
  2061. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  2062. const uint32_t ballots_sh = mul_mat_id ? (warps * 4 * sizeof(uint32_t)) : 0;
  2063. const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size + ballots_sh;
  2064. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  2065. VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), "
  2066. "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported);
  2067. return supported;
  2068. }
  2069. struct GpuPipelineConfig {
  2070. // GPU architecture identifier.
  2071. // Example: vk_device_architecture::AMD_GCN
  2072. vk_device_architecture arch;
  2073. // Mapping of pipeline names to their specific subgroup sizes.
  2074. // Example: {"soft_max_f32", 64}
  2075. std::unordered_map<std::string, uint32_t> pipelines;
  2076. // Default subgroup size for this GPU.
  2077. // Defaults to 0 if not explicitly provided.
  2078. uint32_t default_subgroup_size = 0;
  2079. };
  2080. // Pipeline configuration for RDNA1 GPUs.
  2081. static const std::unordered_map<std::string, uint32_t> rdna1_pipelines = {
  2082. {"soft_max", 64}, {"im2col", 64},
  2083. {"argmax", 64}, {"mul_mat_vec", 64},
  2084. {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32}
  2085. };
  2086. // Pipeline configuration for RDNA2 GPUs.
  2087. static const std::unordered_map<std::string, uint32_t> rdna2_pipelines = {
  2088. {"soft_max", 64}, {"im2col", 64},
  2089. };
  2090. static constexpr uint32_t RDNA_DEFAULT_SUBGROUP_SIZE = 32;
  2091. // Define configurations for different GPUs.
  2092. static std::vector<GpuPipelineConfig> gpu_pipeline_configs = {
  2093. {
  2094. vk_device_architecture::AMD_RDNA1,
  2095. {
  2096. rdna1_pipelines,
  2097. },
  2098. RDNA_DEFAULT_SUBGROUP_SIZE
  2099. },
  2100. {
  2101. vk_device_architecture::AMD_RDNA2,
  2102. {
  2103. rdna2_pipelines,
  2104. },
  2105. RDNA_DEFAULT_SUBGROUP_SIZE
  2106. },
  2107. };
  2108. static uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) {
  2109. for (const auto &config : gpu_pipeline_configs) {
  2110. if (config.arch == arch) {
  2111. auto pipIt = config.pipelines.find(pipeline_name);
  2112. if (pipIt != config.pipelines.end()) {
  2113. return pipIt->second;
  2114. }
  2115. std::vector<std::pair<std::string, uint32_t>> sorted_pipelines(config.pipelines.begin(), config.pipelines.end());
  2116. std::sort(sorted_pipelines.begin(), sorted_pipelines.end(),
  2117. [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
  2118. for (const auto &entry : sorted_pipelines) {
  2119. if (pipeline_name.find(entry.first) != std::string::npos) {
  2120. return entry.second;
  2121. }
  2122. }
  2123. return config.default_subgroup_size;
  2124. }
  2125. }
  2126. return 0; // If no matching configuration is found
  2127. }
  2128. static void ggml_vk_load_shaders(vk_device& device) {
  2129. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  2130. // some shaders have a minimum subgroup size
  2131. const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u);
  2132. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  2133. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  2134. 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;
  2135. const uint32_t mul_mat_subgroup_size_8 = std::max(mul_mat_subgroup_size, 8u);
  2136. const uint32_t mul_mat_subgroup_size_16 = std::max(mul_mat_subgroup_size, 16u);
  2137. const uint32_t mul_mat_subgroup_size_32 = std::max(mul_mat_subgroup_size, 32u);
  2138. const bool subgroup_min_size_16 = (!device->subgroup_size_control && device->subgroup_size >= 16) ||
  2139. (device->subgroup_size_control && device->subgroup_max_size >= 16);
  2140. // mulmat
  2141. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  2142. l_warptile_id, m_warptile_id, s_warptile_id,
  2143. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  2144. l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int,
  2145. l_warptile_mmq_int_k, m_warptile_mmq_int_k, s_warptile_mmq_int_k,
  2146. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  2147. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid,
  2148. l_warptile_mmqid_int, m_warptile_mmqid_int, s_warptile_mmqid_int,
  2149. l_warptile_mmqid_int_k, m_warptile_mmqid_int_k, s_warptile_mmqid_int_k;
  2150. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  2151. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  2152. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  2153. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  2154. uint32_t l_align, m_align, s_align;
  2155. if (device->coopmat2) {
  2156. // spec constants and tile sizes for non-quant matmul/matmul_id
  2157. l_warptile = { 256, 128, 256, 64, 1 };
  2158. m_warptile = { 256, 128, 128, 64, 0 };
  2159. s_warptile = { 128, 64, 64, 64, 0 };
  2160. l_wg_denoms = {128, 256, 1 };
  2161. m_wg_denoms = {128, 128, 1 };
  2162. s_wg_denoms = { 64, 64, 1 };
  2163. // spec constants and tile sizes for quant matmul (non-Qi_K)
  2164. l_warptile_mmq = { 256, 128, 256, 64, 1 };
  2165. m_warptile_mmq = { 256, 128, 128, 64, 1 };
  2166. s_warptile_mmq = { 256, 32, 64, 128, 0 };
  2167. l_mmq_wg_denoms = { 128, 256, 1 };
  2168. m_mmq_wg_denoms = { 128, 128, 1 };
  2169. s_mmq_wg_denoms = { 32, 64, 1 };
  2170. // spec constants and tile sizes for quant matmul (Qi_K)
  2171. l_warptile_mmq_k = { 256, 128, 256, 64, 1 };
  2172. m_warptile_mmq_k = { 256, 128, 128, 64, 1 };
  2173. s_warptile_mmq_k = { 256, 32, 64, 128, 0 };
  2174. l_mmq_wg_denoms_k = { 128, 256, 1 };
  2175. m_mmq_wg_denoms_k = { 128, 128, 1 };
  2176. s_mmq_wg_denoms_k = { 32, 64, 1 };
  2177. // spec constants and tile sizes for quant matmul_id
  2178. l_warptile_mmqid = { 256, 128, 128, 16, 1, device->subgroup_size };
  2179. m_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2180. s_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2181. l_mmqid_wg_denoms = { 128, 128, 1 };
  2182. m_mmqid_wg_denoms = { 128, 64, 1 };
  2183. s_mmqid_wg_denoms = { 128, 64, 1 };
  2184. l_align = 128;
  2185. m_align = 64;
  2186. s_align = 32;
  2187. } else {
  2188. // Matrix cores require different warp group sizes
  2189. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  2190. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  2191. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  2192. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  2193. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  2194. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  2195. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  2196. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  2197. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  2198. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2199. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2200. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2201. l_warptile_mmq = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2202. m_warptile_mmq = { 128, 64, 64, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2203. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2204. // Integer MMQ has a smaller shared memory profile, but heavier register use
  2205. l_warptile_mmq_int = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2206. m_warptile_mmq_int = { 128, 64, 64, 32, subgroup_size_8, 32, 2, 2, 2, 1, subgroup_size_8 };
  2207. s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, subgroup_size_8 };
  2208. // K-quants use even more registers, mitigate by setting WMITER to 1
  2209. l_warptile_mmq_int_k = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 1, 4, 4, 1, subgroup_size_8 };
  2210. m_warptile_mmq_int_k = { 128, 64, 64, 32, subgroup_size_8, 32, 1, 2, 2, 1, subgroup_size_8 };
  2211. s_warptile_mmq_int_k = { subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, subgroup_size_8 };
  2212. 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 };
  2213. 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 };
  2214. 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 };
  2215. 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 };
  2216. 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 };
  2217. 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 };
  2218. l_warptile_mmqid_int = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, 4, 4, 1, mul_mat_subgroup_size_8 };
  2219. m_warptile_mmqid_int = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, 2, 2, 1, mul_mat_subgroup_size_8 };
  2220. s_warptile_mmqid_int = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, mul_mat_subgroup_size_8 };
  2221. 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 };
  2222. m_warptile_mmqid_int_k = { 128, 64, 64, 32, mul_mat_subgroup_size_16, 32, 1, 2, 2, 1, mul_mat_subgroup_size_16 };
  2223. s_warptile_mmqid_int_k = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, mul_mat_subgroup_size_16 };
  2224. // chip specific tuning
  2225. if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) {
  2226. m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2227. m_warptile_mmqid = m_warptile_mmqid_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2228. }
  2229. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  2230. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  2231. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  2232. l_align = 128;
  2233. m_align = 64;
  2234. s_align = 32;
  2235. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  2236. ggml_type t = (ggml_type)i;
  2237. // Disable medium and large matrix multiplication if not enough shared memory is available
  2238. // Check mmq warptiles as the largest configuration
  2239. // Throw an error if not enough for any matrix multiplication is available
  2240. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) {
  2241. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  2242. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  2243. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) {
  2244. device->mul_mat_m[i] = false;
  2245. device->mul_mat_l[i] = false;
  2246. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) {
  2247. device->mul_mat_l[i] = false;
  2248. }
  2249. // Disable mul_mat_id if not enough shared memory is available
  2250. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmqid, true, t)) {
  2251. device->mul_mat_id_s[i] = false;
  2252. device->mul_mat_id_m[i] = false;
  2253. device->mul_mat_id_l[i] = false;
  2254. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmqid, true, t)) {
  2255. device->mul_mat_id_m[i] = false;
  2256. device->mul_mat_id_l[i] = false;
  2257. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmqid, true, t)) {
  2258. device->mul_mat_id_l[i] = false;
  2259. }
  2260. }
  2261. }
  2262. if (!device->pipeline_matmul_f32) {
  2263. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2264. }
  2265. if (!device->pipeline_matmul_f32_f16) {
  2266. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  2267. }
  2268. if (!device->pipeline_matmul_id_f32) {
  2269. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2270. }
  2271. if (!device->pipeline_matmul_bf16) {
  2272. device->pipeline_matmul_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2273. }
  2274. if (!device->pipeline_matmul_id_bf16) {
  2275. device->pipeline_matmul_id_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2276. }
  2277. std::vector<std::future<void>> compiles;
  2278. 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,
  2279. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2280. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2281. if (!require_full_subgroups && required_subgroup_size == 0) {
  2282. required_subgroup_size = get_subgroup_size(name, device->architecture);
  2283. }
  2284. if (!pipeline) {
  2285. pipeline = std::make_shared<vk_pipeline_struct>();
  2286. }
  2287. if (!pipeline->initialized) {
  2288. pipeline->name = name;
  2289. pipeline->parameter_count = parameter_count;
  2290. pipeline->push_constant_size = push_constant_size;
  2291. pipeline->wg_denoms = wg_denoms;
  2292. pipeline->align = align;
  2293. pipeline->initialized = true;
  2294. }
  2295. if (!pipeline->needed || pipeline->compiled) {
  2296. return;
  2297. }
  2298. {
  2299. // wait until fewer than N compiles are in progress
  2300. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  2301. std::unique_lock<std::mutex> guard(compile_count_mutex);
  2302. while (compile_count >= N) {
  2303. compile_count_cond.wait(guard);
  2304. }
  2305. compile_count++;
  2306. }
  2307. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  2308. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  2309. };
  2310. 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,
  2311. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2312. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2313. return ggml_vk_create_pipeline(device, pipeline, name.c_str(), spv_size, spv_data, entrypoint,
  2314. parameter_count, push_constant_size, wg_denoms, specialization_constants,
  2315. align, disable_robustness, require_full_subgroups, required_subgroup_size);
  2316. };
  2317. 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> {
  2318. return {fa_rows_cols(path, hsk, hsv, clamp, type, small_rows)[0], 1, 1};
  2319. };
  2320. 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> {
  2321. // For large number of rows, 128 invocations seems to work best.
  2322. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  2323. // can't use 256 for D==80.
  2324. // For scalar, use 128 (arbitrary)
  2325. // The same D_split value is used for both HSK and HSV, so just base it on the union of the LSBs.
  2326. const uint32_t D = (hsk|hsv);
  2327. uint32_t wg_size = (path == FA_SCALAR || path == FA_COOPMAT1)
  2328. ? scalar_flash_attention_workgroup_size
  2329. : ((small_rows && (D % 32) == 0) ? 256 : 128);
  2330. auto rows_cols = fa_rows_cols(path, hsk, hsv, clamp, type, small_rows);
  2331. // D_split can't be larger than a subgroup because we use subgroupShuffle to reduce it.
  2332. // D_split can't be larger than the LSB of D divided by 4 due to vectorization in the shader.
  2333. const uint32_t D_lsb = D ^ (D & (D-1));
  2334. uint32_t D_split = std::min(std::min(device->subgroup_size, 8u), D_lsb / 4);
  2335. return {wg_size, rows_cols[0], rows_cols[1], hsk, hsv, clamp, D_split};
  2336. };
  2337. #define CREATE_FA(TYPE, NAMELC, FAPATH, SUFFIX) \
  2338. for (auto &fa : device->pipeline_flash_attn_f32_f16[TYPE]) { \
  2339. uint32_t HSK = fa.first.HSK; \
  2340. uint32_t HSV = fa.first.HSV; \
  2341. bool small_rows = fa.first.small_rows; \
  2342. FaCodePath path = fa.first.path; \
  2343. bool aligned = fa.first.aligned; \
  2344. bool f32acc = fa.first.f32acc; \
  2345. if (path == FAPATH) { \
  2346. if (aligned) { \
  2347. if (f32acc) { \
  2348. 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)); \
  2349. } else { \
  2350. 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)); \
  2351. } \
  2352. } else { \
  2353. if (f32acc) { \
  2354. 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)); \
  2355. } else { \
  2356. 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)); \
  2357. } \
  2358. } \
  2359. } \
  2360. }
  2361. CREATE_FA(GGML_TYPE_F32, f32, FA_SCALAR, )
  2362. CREATE_FA(GGML_TYPE_F16, f16, FA_SCALAR, )
  2363. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_SCALAR, )
  2364. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_SCALAR, )
  2365. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2366. if (device->coopmat1_fa_support) {
  2367. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT1, _cm1)
  2368. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT1, _cm1)
  2369. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT1, _cm1)
  2370. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT1, _cm1)
  2371. }
  2372. #endif
  2373. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2374. if (device->coopmat2) {
  2375. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT2, _cm2)
  2376. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT2, _cm2)
  2377. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT2, _cm2)
  2378. CREATE_FA(GGML_TYPE_Q4_1, q4_1, FA_COOPMAT2, _cm2)
  2379. CREATE_FA(GGML_TYPE_Q5_0, q5_0, FA_COOPMAT2, _cm2)
  2380. CREATE_FA(GGML_TYPE_Q5_1, q5_1, FA_COOPMAT2, _cm2)
  2381. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT2, _cm2)
  2382. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl, FA_COOPMAT2, _cm2)
  2383. }
  2384. #endif
  2385. #undef CREATE_FA
  2386. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2387. if (device->coopmat2) {
  2388. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2389. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2390. 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); \
  2391. 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); \
  2392. 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); \
  2393. 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); \
  2394. 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); \
  2395. 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); \
  2396. // Create 2 variants, {f16,f32} accumulator
  2397. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2398. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2399. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2400. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2401. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2402. if (device->coopmat_bf16_support) {
  2403. CREATE_MM(pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2404. }
  2405. #endif
  2406. 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)
  2407. 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)
  2408. 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)
  2409. 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)
  2410. 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)
  2411. 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)
  2412. 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)
  2413. 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)
  2414. 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)
  2415. 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)
  2416. 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)
  2417. 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)
  2418. 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)
  2419. 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)
  2420. 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)
  2421. 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)
  2422. 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)
  2423. 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)
  2424. 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)
  2425. 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)
  2426. GGML_ASSERT(device->subgroup_ballot);
  2427. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2428. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2429. if (device->coopmat_bf16_support) {
  2430. CREATE_MM(pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2431. }
  2432. #endif
  2433. 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)
  2434. 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)
  2435. 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)
  2436. 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)
  2437. 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)
  2438. 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)
  2439. 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)
  2440. 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)
  2441. 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)
  2442. 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)
  2443. 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)
  2444. 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)
  2445. 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)
  2446. 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)
  2447. 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)
  2448. 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)
  2449. 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)
  2450. 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)
  2451. 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)
  2452. 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)
  2453. #undef CREATE_MM
  2454. #undef CREATE_MM2
  2455. } else
  2456. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2457. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2458. if (device->coopmat_support) {
  2459. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2460. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2461. if (device->mul_mat ## ID ## _l[TYPE]) \
  2462. 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); \
  2463. if (device->mul_mat ## ID ## _m[TYPE]) \
  2464. 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); \
  2465. if (device->mul_mat ## ID ## _s[TYPE]) \
  2466. 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); \
  2467. if (device->mul_mat ## ID ## _l[TYPE]) \
  2468. 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); \
  2469. if (device->mul_mat ## ID ## _m[TYPE]) \
  2470. 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); \
  2471. if (device->mul_mat ## ID ## _s[TYPE]) \
  2472. 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); \
  2473. // Create 2 variants, {f16,f32} accumulator
  2474. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2475. if (device->coopmat_acc_f16_support) { \
  2476. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2477. } \
  2478. if (device->coopmat_acc_f32_support) { \
  2479. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2480. } \
  2481. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2482. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2483. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2484. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2485. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2486. if (device->coopmat_bf16_support) {
  2487. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, )
  2488. }
  2489. #endif
  2490. if (device->coopmat_acc_f16_support) {
  2491. 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, );
  2492. 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, );
  2493. 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, );
  2494. 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, );
  2495. 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, );
  2496. 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, );
  2497. 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, );
  2498. 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, );
  2499. 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, );
  2500. 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, );
  2501. 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, );
  2502. 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, );
  2503. 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, );
  2504. 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, );
  2505. 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, );
  2506. 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, );
  2507. 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, );
  2508. 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, );
  2509. 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, );
  2510. 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, );
  2511. } else {
  2512. 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, );
  2513. 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, );
  2514. 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, );
  2515. 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, );
  2516. 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, );
  2517. 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, );
  2518. 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, );
  2519. 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, );
  2520. 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, );
  2521. 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, );
  2522. 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, );
  2523. 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, );
  2524. 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, );
  2525. 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, );
  2526. 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, );
  2527. 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, );
  2528. 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, );
  2529. 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, );
  2530. 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, );
  2531. 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, );
  2532. }
  2533. GGML_ASSERT(device->subgroup_ballot);
  2534. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2535. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2536. 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);
  2537. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2538. if (device->coopmat_bf16_support) {
  2539. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2540. }
  2541. #endif
  2542. 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);
  2543. 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);
  2544. 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);
  2545. 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);
  2546. 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);
  2547. 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);
  2548. 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);
  2549. 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);
  2550. 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);
  2551. 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);
  2552. 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);
  2553. 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);
  2554. 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);
  2555. 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);
  2556. 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);
  2557. 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);
  2558. 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);
  2559. 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);
  2560. 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);
  2561. 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);
  2562. #undef CREATE_MM2
  2563. #undef CREATE_MM
  2564. } else
  2565. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2566. if (device->fp16) {
  2567. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2568. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2569. if (device->mul_mat ## ID ## _l[TYPE]) \
  2570. 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); \
  2571. if (device->mul_mat ## ID ## _m[TYPE]) \
  2572. 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); \
  2573. if (device->mul_mat ## ID ## _s[TYPE]) \
  2574. 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); \
  2575. if (device->mul_mat ## ID ## _l[TYPE]) \
  2576. 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); \
  2577. if (device->mul_mat ## ID ## _m[TYPE]) \
  2578. 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); \
  2579. if (device->mul_mat ## ID ## _s[TYPE]) \
  2580. 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); \
  2581. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2582. if (device->mul_mat ## ID ## _l[TYPE]) { \
  2583. 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); \
  2584. } \
  2585. if (device->mul_mat ## ID ## _m[TYPE]) { \
  2586. 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); \
  2587. } \
  2588. if (device->mul_mat ## ID ## _s[TYPE]) { \
  2589. 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); \
  2590. } \
  2591. // Create 2 variants, {f16,f32} accumulator
  2592. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2593. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2594. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2595. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2596. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2597. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2598. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2599. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2600. 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);
  2601. 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);
  2602. 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);
  2603. 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);
  2604. 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);
  2605. 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);
  2606. 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);
  2607. 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);
  2608. 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);
  2609. 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);
  2610. 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);
  2611. 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);
  2612. 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);
  2613. 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);
  2614. 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);
  2615. 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);
  2616. 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);
  2617. 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);
  2618. 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);
  2619. 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);
  2620. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2621. if (device->integer_dot_product) {
  2622. 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);
  2623. 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);
  2624. 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);
  2625. 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);
  2626. 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);
  2627. 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);
  2628. 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);
  2629. 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);
  2630. 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);
  2631. 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);
  2632. 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);
  2633. }
  2634. #endif
  2635. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2636. 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);
  2637. 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);
  2638. 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);
  2639. 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);
  2640. 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);
  2641. 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);
  2642. 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);
  2643. 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);
  2644. 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);
  2645. 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);
  2646. 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);
  2647. 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);
  2648. 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);
  2649. 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);
  2650. 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);
  2651. 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);
  2652. 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);
  2653. 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);
  2654. 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);
  2655. 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);
  2656. 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);
  2657. 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);
  2658. 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);
  2659. 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);
  2660. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2661. if (device->integer_dot_product) {
  2662. 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);
  2663. 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);
  2664. 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);
  2665. 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);
  2666. 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);
  2667. 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);
  2668. 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);
  2669. 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);
  2670. 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);
  2671. 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);
  2672. 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);
  2673. }
  2674. #endif
  2675. } else {
  2676. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2677. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2678. 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);
  2679. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2680. 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);
  2681. 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);
  2682. 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);
  2683. 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);
  2684. 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);
  2685. 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);
  2686. 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);
  2687. 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);
  2688. 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);
  2689. 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);
  2690. 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);
  2691. 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);
  2692. 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);
  2693. 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);
  2694. 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);
  2695. 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);
  2696. 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);
  2697. 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);
  2698. 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);
  2699. 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);
  2700. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2701. if (device->integer_dot_product) {
  2702. 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);
  2703. 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);
  2704. 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);
  2705. 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);
  2706. 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);
  2707. 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);
  2708. 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);
  2709. 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);
  2710. 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);
  2711. 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);
  2712. 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);
  2713. }
  2714. #endif
  2715. }
  2716. #undef CREATE_MM2
  2717. #undef CREATE_MMQ
  2718. #undef CREATE_MM
  2719. } else {
  2720. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2721. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2722. if (device->mul_mat ## ID ## _l[TYPE]) \
  2723. 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); \
  2724. if (device->mul_mat ## ID ## _m[TYPE]) \
  2725. 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); \
  2726. if (device->mul_mat ## ID ## _s[TYPE]) \
  2727. 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); \
  2728. if (device->mul_mat ## ID ## _l[TYPE]) \
  2729. 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); \
  2730. if (device->mul_mat ## ID ## _m[TYPE]) \
  2731. 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); \
  2732. if (device->mul_mat ## ID ## _s[TYPE]) \
  2733. 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); \
  2734. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2735. if (device->mul_mat ## ID ## _l[TYPE]) \
  2736. 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); \
  2737. if (device->mul_mat ## ID ## _m[TYPE]) \
  2738. 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); \
  2739. if (device->mul_mat ## ID ## _s[TYPE]) \
  2740. 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); \
  2741. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2742. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2743. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2744. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2745. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2746. 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);
  2747. 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);
  2748. 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);
  2749. 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);
  2750. 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);
  2751. 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);
  2752. 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);
  2753. 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);
  2754. 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);
  2755. 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);
  2756. 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);
  2757. 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);
  2758. 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);
  2759. 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);
  2760. 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);
  2761. 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);
  2762. 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);
  2763. 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);
  2764. 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);
  2765. 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);
  2766. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2767. if (device->integer_dot_product) {
  2768. 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, );
  2769. 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, );
  2770. 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, );
  2771. 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, );
  2772. 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, );
  2773. 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, );
  2774. 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, );
  2775. 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, );
  2776. 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, );
  2777. 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, );
  2778. }
  2779. #endif
  2780. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2781. 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);
  2782. 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);
  2783. 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);
  2784. 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);
  2785. 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);
  2786. 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);
  2787. 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);
  2788. 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);
  2789. 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);
  2790. 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);
  2791. 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);
  2792. 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);
  2793. 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);
  2794. 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);
  2795. 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);
  2796. 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);
  2797. 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);
  2798. 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);
  2799. 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);
  2800. 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);
  2801. 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);
  2802. 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);
  2803. 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);
  2804. 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);
  2805. } else {
  2806. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2807. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2808. 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);
  2809. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2810. 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);
  2811. 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);
  2812. 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);
  2813. 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);
  2814. 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);
  2815. 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);
  2816. 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);
  2817. 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);
  2818. 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);
  2819. 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);
  2820. 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);
  2821. 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);
  2822. 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);
  2823. 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);
  2824. 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);
  2825. 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);
  2826. 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);
  2827. 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);
  2828. 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);
  2829. 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);
  2830. }
  2831. }
  2832. // reusing CREATE_MM from the fp32 path
  2833. if ((device->coopmat2 || device->coopmat_support)
  2834. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2835. && !device->coopmat_bf16_support
  2836. #endif
  2837. ) {
  2838. // use scalar tile sizes
  2839. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2840. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, 4, 2, 1, subgroup_size_8 };
  2841. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, 2, 2, 1, subgroup_size_8 };
  2842. l_wg_denoms = {128, 128, 1 };
  2843. m_wg_denoms = { 64, 64, 1 };
  2844. s_wg_denoms = { 32, 32, 1 };
  2845. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2846. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2847. }
  2848. #undef CREATE_MM
  2849. // mul mat vec
  2850. // the number of rows computed per shader depends on GPU model and quant
  2851. uint32_t rm_stdq = 1;
  2852. uint32_t rm_kq = 2;
  2853. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  2854. if (device->architecture == AMD_GCN) {
  2855. rm_stdq = 2;
  2856. rm_kq = 4;
  2857. }
  2858. } else if (device->vendor_id == VK_VENDOR_ID_INTEL)
  2859. rm_stdq = 2;
  2860. uint32_t rm_iq = 2 * rm_kq;
  2861. const bool use_subgroups = device->subgroup_arithmetic && device->architecture != vk_device_architecture::AMD_GCN;
  2862. // Ensure a subgroup size >= 16 is available
  2863. const bool use_subgroups16 = use_subgroups && subgroup_min_size_16;
  2864. 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;
  2865. const uint32_t subgroup_size16 = std::max(subgroup_size, 16u);
  2866. const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0;
  2867. const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0;
  2868. for (uint32_t w = 0; w < DMMV_WG_SIZE_COUNT; ++w) {
  2869. const uint32_t wg_size_subgroup = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size : (subgroup_size * 4);
  2870. const uint32_t wg_size_subgroup16 = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size16 : (subgroup_size16 * 4);
  2871. const shader_reduction_mode reduc = (use_subgroups && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  2872. (use_subgroups && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  2873. SHADER_REDUCTION_MODE_SHMEM;
  2874. const shader_reduction_mode reduc16 = (use_subgroups16 && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  2875. (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  2876. SHADER_REDUCTION_MODE_SHMEM;
  2877. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  2878. 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", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2879. 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", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2880. 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", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2881. 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", 3, 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);
  2882. 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", 3, 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);
  2883. 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", 3, 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);
  2884. 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", 3, 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);
  2885. 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", 3, 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);
  2886. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2887. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2888. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2889. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2890. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2891. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2892. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2893. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2894. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2895. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2896. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2897. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2898. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2899. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2900. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2901. 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", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2902. 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", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2903. 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", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2904. 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", 3, 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);
  2905. 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", 3, 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);
  2906. 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", 3, 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);
  2907. 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", 3, 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);
  2908. 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", 3, 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);
  2909. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2910. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2911. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2912. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2913. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2914. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2915. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2916. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2917. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2918. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2919. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2920. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2921. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2922. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2923. 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", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2924. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2925. if (device->integer_dot_product) {
  2926. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  2927. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  2928. 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", 3, 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);
  2929. 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", 3, 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);
  2930. 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", 3, 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);
  2931. 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", 3, 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);
  2932. 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", 3, 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);
  2933. }
  2934. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  2935. }
  2936. }
  2937. 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", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  2938. 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", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  2939. 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", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  2940. 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", 4, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2941. 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", 4, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2942. 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", 4, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2943. 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", 4, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  2944. 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", 4, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq, 1, 1}, {device->subgroup_size, 1*rm_stdq}, 1, true);
  2945. 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", 4, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2946. 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", 4, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2947. 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", 4, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2948. 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", 4, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2949. 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", 4, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  2950. 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", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2951. 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", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2952. 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", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2953. 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", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2954. 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", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2955. 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", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2956. 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", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2957. 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", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2958. 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", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2959. 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", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2960. // dequant shaders
  2961. 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);
  2962. 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);
  2963. 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);
  2964. 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);
  2965. 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);
  2966. 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);
  2967. 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);
  2968. 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);
  2969. 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);
  2970. 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);
  2971. 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);
  2972. 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);
  2973. 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);
  2974. 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);
  2975. 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);
  2976. 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);
  2977. 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);
  2978. 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);
  2979. 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);
  2980. 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);
  2981. 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);
  2982. // get_rows
  2983. 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);
  2984. 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);
  2985. 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);
  2986. 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);
  2987. 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);
  2988. 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);
  2989. 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);
  2990. 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);
  2991. 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);
  2992. 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);
  2993. 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);
  2994. 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);
  2995. 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);
  2996. 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);
  2997. 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);
  2998. 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);
  2999. 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);
  3000. 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);
  3001. 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);
  3002. 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);
  3003. 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);
  3004. 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);
  3005. 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);
  3006. 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);
  3007. 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);
  3008. 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);
  3009. 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);
  3010. 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);
  3011. 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);
  3012. 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);
  3013. 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);
  3014. 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);
  3015. 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);
  3016. 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);
  3017. 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);
  3018. 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);
  3019. 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);
  3020. 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);
  3021. 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);
  3022. 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);
  3023. 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);
  3024. 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);
  3025. 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);
  3026. 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);
  3027. 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);
  3028. 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);
  3029. 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);
  3030. 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);
  3031. if (device->subgroup_clustered && device->subgroup_require_full_support) {
  3032. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1, "quantize_q8_1", quantize_q8_1_subgroup_len, quantize_q8_1_subgroup_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1, true, true);
  3033. 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);
  3034. } else {
  3035. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1, "quantize_q8_1", quantize_q8_1_len, quantize_q8_1_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1);
  3036. 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);
  3037. }
  3038. for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) {
  3039. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3040. 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", 3, 6 * sizeof(uint32_t), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true, true);
  3041. } else {
  3042. 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", 3, 6 * sizeof(uint32_t), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true);
  3043. }
  3044. }
  3045. 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", 3, 12 * sizeof(uint32_t), {1, 1, 1}, {}, 1);
  3046. 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);
  3047. 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);
  3048. 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);
  3049. 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);
  3050. 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);
  3051. 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);
  3052. 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);
  3053. 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);
  3054. 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);
  3055. 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);
  3056. 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);
  3057. 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);
  3058. 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);
  3059. 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);
  3060. 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);
  3061. 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);
  3062. 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);
  3063. 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);
  3064. 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);
  3065. 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);
  3066. 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);
  3067. 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);
  3068. if (device->float_controls_rte_fp16) {
  3069. 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);
  3070. 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);
  3071. 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);
  3072. 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);
  3073. 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);
  3074. 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);
  3075. } else {
  3076. 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);
  3077. 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);
  3078. 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);
  3079. 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);
  3080. 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);
  3081. 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);
  3082. }
  3083. #define SET_ROWS(itype, rte) \
  3084. 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); \
  3085. 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); \
  3086. 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); \
  3087. 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); \
  3088. 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); \
  3089. 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); \
  3090. 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); \
  3091. 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); \
  3092. 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);
  3093. if (device->float_controls_rte_fp16) {
  3094. SET_ROWS(_i32, _rte)
  3095. SET_ROWS(_i64, _rte)
  3096. } else {
  3097. SET_ROWS(_i32, )
  3098. SET_ROWS(_i64, )
  3099. }
  3100. #undef SET_ROWS
  3101. 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);
  3102. 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);
  3103. 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);
  3104. 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);
  3105. 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);
  3106. 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);
  3107. auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) {
  3108. std::string s;
  3109. s += std::string(src0_f16 ? "_f16" : "_f32");
  3110. s += std::string(src1_f16 ? "_f16" : "_f32");
  3111. s += std::string(dst_f16 ? "_f16" : "_f32");
  3112. return s;
  3113. };
  3114. bool rte = device->float_controls_rte_fp16;
  3115. #define CREATE_BINARY(name, namemod, spec, bindings) \
  3116. for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \
  3117. ggml_vk_create_pipeline2(device, device->pipeline_ ## name ## namemod[s0][s1][d], \
  3118. #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d][rte], name ## _data[s0][s1][d][rte], \
  3119. "main", (bindings), sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1);
  3120. CREATE_BINARY(add, , {0}, 4)
  3121. CREATE_BINARY(add, _norepeat, {1}, 4)
  3122. CREATE_BINARY(sub, , {0}, 3)
  3123. CREATE_BINARY(sub, _norepeat, {1}, 3)
  3124. CREATE_BINARY(mul, , {0}, 3)
  3125. CREATE_BINARY(mul, _norepeat, {1}, 3)
  3126. CREATE_BINARY(div, , {0}, 3)
  3127. CREATE_BINARY(div, _norepeat, {1}, 3)
  3128. CREATE_BINARY(add_rms, , {0}, 4)
  3129. CREATE_BINARY(add_rms, _norepeat, {1}, 4)
  3130. #undef CREATE_BINARY
  3131. if (device->multi_add) {
  3132. for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) {
  3133. 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);
  3134. 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);
  3135. }
  3136. }
  3137. 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);
  3138. 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);
  3139. 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);
  3140. 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);
  3141. 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);
  3142. 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);
  3143. 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);
  3144. 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);
  3145. 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);
  3146. 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);
  3147. 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);
  3148. 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);
  3149. 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);
  3150. 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);
  3151. 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);
  3152. 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);
  3153. 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);
  3154. #define CREATE_UNARY(name) \
  3155. 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); \
  3156. 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);
  3157. CREATE_UNARY(gelu)
  3158. CREATE_UNARY(gelu_erf)
  3159. CREATE_UNARY(gelu_quick)
  3160. CREATE_UNARY(silu)
  3161. CREATE_UNARY(relu)
  3162. CREATE_UNARY(tanh)
  3163. CREATE_UNARY(sigmoid)
  3164. CREATE_UNARY(hardsigmoid)
  3165. CREATE_UNARY(hardswish)
  3166. #undef CREATE_UNARY
  3167. #define CREATE_UNARY_RTE(name) \
  3168. if (device->float_controls_rte_fp16) { \
  3169. 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); \
  3170. 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); \
  3171. } else { \
  3172. 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); \
  3173. 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); \
  3174. }
  3175. CREATE_UNARY_RTE(exp)
  3176. #undef CREATE_UNARY_RTE
  3177. #define CREATE_GLU(name) \
  3178. if (device->float_controls_rte_fp16) { \
  3179. 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); \
  3180. 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); \
  3181. } else { \
  3182. 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); \
  3183. 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); \
  3184. }
  3185. CREATE_GLU(geglu)
  3186. CREATE_GLU(reglu)
  3187. CREATE_GLU(swiglu)
  3188. CREATE_GLU(swiglu_oai)
  3189. CREATE_GLU(geglu_erf)
  3190. CREATE_GLU(geglu_quick)
  3191. #undef CREATE_GLU
  3192. 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);
  3193. 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);
  3194. 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);
  3195. 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);
  3196. 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);
  3197. 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);
  3198. 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);
  3199. 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);
  3200. 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);
  3201. 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);
  3202. 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);
  3203. 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);
  3204. if (device->float_controls_rte_fp16) {
  3205. 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);
  3206. 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);
  3207. 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);
  3208. 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);
  3209. 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);
  3210. 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);
  3211. } else {
  3212. 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);
  3213. 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);
  3214. 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);
  3215. 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);
  3216. 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);
  3217. 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);
  3218. }
  3219. for (uint32_t i = 0; i < num_argsort_pipelines; ++i) {
  3220. 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);
  3221. }
  3222. 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);
  3223. 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);
  3224. 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);
  3225. #define IM2COL(bda) \
  3226. 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); \
  3227. 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); \
  3228. if (device->float_controls_rte_fp16) { \
  3229. 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); \
  3230. 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); \
  3231. } else { \
  3232. 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); \
  3233. 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); \
  3234. }
  3235. if (device->shader_int64 && device->buffer_device_address) {
  3236. IM2COL(_bda)
  3237. } else {
  3238. IM2COL()
  3239. }
  3240. 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);
  3241. 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);
  3242. 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);
  3243. 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);
  3244. 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);
  3245. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3246. 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);
  3247. 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);
  3248. } else {
  3249. 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);
  3250. 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);
  3251. }
  3252. 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);
  3253. 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);
  3254. 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);
  3255. // conv2d, conv_transpose_2d
  3256. for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) {
  3257. uint32_t conv2d_WG_SIZE = 256;
  3258. uint32_t conv2d_BS_K = 128;
  3259. uint32_t conv2d_BS_CRS = 16;
  3260. uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices.
  3261. uint32_t conv2d_BS_NPQ = 128;
  3262. uint32_t conv2d_TS_K = 8;
  3263. uint32_t conv2d_SHMEM_PAD = 4;
  3264. bool conv2d_UNROLL = true;
  3265. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3266. if (device->coopmat2) {
  3267. conv2d_SHMEM_PAD = 8; // 8 float16_t
  3268. }
  3269. #endif
  3270. if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3271. conv2d_SHMEM_PAD = 0;
  3272. conv2d_UNROLL = false;
  3273. } else if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3274. conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4;
  3275. }
  3276. switch (s) {
  3277. default:
  3278. case CONV_SHAPE_128x128:
  3279. conv2d_BS_K = 128;
  3280. conv2d_BS_NPQ = 128;
  3281. conv2d_BS_CRS = 16;
  3282. if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != vk_device_architecture::AMD_GCN) {
  3283. conv2d_UNROLL = false;
  3284. }
  3285. break;
  3286. case CONV_SHAPE_64x32:
  3287. conv2d_BS_K = 64;
  3288. conv2d_BS_NPQ = 32;
  3289. conv2d_BS_CRS = 32;
  3290. conv2d_TS_K = 4;
  3291. break;
  3292. case CONV_SHAPE_32x256:
  3293. conv2d_BS_K = 32;
  3294. conv2d_BS_NPQ = 256;
  3295. conv2d_BS_CRS = 16;
  3296. break;
  3297. }
  3298. // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math.
  3299. bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA ||
  3300. device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  3301. bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD ||
  3302. device->architecture == vk_device_architecture::AMD_GCN;
  3303. if (device->subgroup_shuffle &&
  3304. device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316.
  3305. allow_collectives_nv &&
  3306. allow_collectives_amd) {
  3307. use_collectives = 1;
  3308. conv2d_BS_CRS = std::min(
  3309. device->subgroup_size,
  3310. conv2d_BS_CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used.
  3311. }
  3312. uint32_t conv2d_shmem_req =
  3313. (conv2d_BS_K * (conv2d_BS_CRS + conv2d_SHMEM_PAD) + conv2d_BS_CRS * (conv2d_BS_NPQ + conv2d_SHMEM_PAD)) * sizeof(float);
  3314. if (device->properties.limits.maxComputeSharedMemorySize < conv2d_shmem_req) {
  3315. conv2d_BS_CRS = 8;
  3316. if (use_collectives) {
  3317. conv2d_BS_CRS = std::min(device->subgroup_size, conv2d_BS_CRS);
  3318. }
  3319. }
  3320. std::array<uint32_t, 3> wg_denoms = { conv2d_BS_K, conv2d_BS_NPQ, 1 };
  3321. 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 };
  3322. #define CREATE_CONV(name, type_suffix, spv_suffix) \
  3323. ggml_vk_create_pipeline( \
  3324. device, device->pipeline_##name##type_suffix[s], #name #type_suffix, \
  3325. name##type_suffix##spv_suffix##_len, name##type_suffix##spv_suffix##_data, "main", 3, \
  3326. sizeof(vk_op_##name##_push_constants), wg_denoms, spec_constants, 1, true, use_collectives);
  3327. #define CREATE_CONVS(spv_suffix) \
  3328. CREATE_CONV(conv2d, _f32, spv_suffix) \
  3329. CREATE_CONV(conv2d, _f16_f32, spv_suffix) \
  3330. if (device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_conv_transpose_2d_push_constants)) { \
  3331. CREATE_CONV(conv_transpose_2d, _f32, spv_suffix) \
  3332. CREATE_CONV(conv_transpose_2d, _f16_f32, spv_suffix) \
  3333. }
  3334. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3335. if (device->coopmat2) {
  3336. CREATE_CONVS(_cm2)
  3337. } else
  3338. #endif
  3339. if (conv2d_UNROLL) {
  3340. CREATE_CONVS(_unroll)
  3341. } else {
  3342. CREATE_CONVS( )
  3343. }
  3344. #undef CREATE_CONV
  3345. #undef CREATE_CONVS
  3346. }
  3347. 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);
  3348. 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);
  3349. 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);
  3350. 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);
  3351. for (uint32_t i = 0; i < num_topk_moe_pipelines; ++i) {
  3352. 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);
  3353. 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);
  3354. 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);
  3355. }
  3356. for (auto &c : compiles) {
  3357. c.wait();
  3358. }
  3359. device->need_compiles = false;
  3360. }
  3361. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch);
  3362. static vk_device ggml_vk_get_device(size_t idx) {
  3363. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  3364. if (vk_instance.devices[idx] == nullptr) {
  3365. VK_LOG_DEBUG("Initializing new vk_device");
  3366. vk_device device = std::make_shared<vk_device_struct>();
  3367. vk_instance.devices[idx] = device;
  3368. #ifdef GGML_VULKAN_MEMORY_DEBUG
  3369. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  3370. #endif
  3371. if (vk_perf_logger_enabled) {
  3372. device->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  3373. }
  3374. size_t dev_num = vk_instance.device_indices[idx];
  3375. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  3376. if (dev_num >= physical_devices.size()) {
  3377. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3378. throw std::runtime_error("Device not found");
  3379. }
  3380. device->physical_device = physical_devices[dev_num];
  3381. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  3382. device->architecture = get_device_architecture(device->physical_device);
  3383. const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY");
  3384. device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr;
  3385. const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM");
  3386. device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr;
  3387. const char* GGML_VK_ALLOW_SYSMEM_FALLBACK = getenv("GGML_VK_ALLOW_SYSMEM_FALLBACK");
  3388. device->allow_sysmem_fallback = GGML_VK_ALLOW_SYSMEM_FALLBACK != nullptr;
  3389. const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE");
  3390. device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr;
  3391. bool fp16_storage = false;
  3392. bool fp16_compute = false;
  3393. bool maintenance4_support = false;
  3394. bool sm_builtins = false;
  3395. bool amd_shader_core_properties2 = false;
  3396. bool pipeline_robustness = false;
  3397. bool coopmat2_support = false;
  3398. bool pipeline_executable_properties_support = false;
  3399. device->coopmat_support = false;
  3400. device->integer_dot_product = false;
  3401. bool bfloat16_support = false;
  3402. for (const auto& properties : ext_props) {
  3403. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  3404. maintenance4_support = true;
  3405. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3406. fp16_storage = true;
  3407. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3408. fp16_compute = true;
  3409. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  3410. sm_builtins = true;
  3411. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  3412. amd_shader_core_properties2 = true;
  3413. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  3414. pipeline_robustness = true;
  3415. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  3416. device->subgroup_size_control = true;
  3417. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3418. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3419. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3420. device->coopmat_support = true;
  3421. device->coopmat_m = 0;
  3422. device->coopmat_n = 0;
  3423. device->coopmat_k = 0;
  3424. #endif
  3425. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3426. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3427. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3428. coopmat2_support = true;
  3429. #endif
  3430. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3431. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3432. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3433. device->integer_dot_product = true;
  3434. #endif
  3435. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3436. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3437. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3438. bfloat16_support = true;
  3439. #endif
  3440. } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) {
  3441. pipeline_executable_properties_support = true;
  3442. }
  3443. }
  3444. vk::PhysicalDeviceProperties2 props2;
  3445. vk::PhysicalDeviceMaintenance3Properties props3;
  3446. vk::PhysicalDeviceMaintenance4Properties props4;
  3447. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3448. vk::PhysicalDeviceDriverProperties driver_props;
  3449. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  3450. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  3451. vk::PhysicalDeviceVulkan11Properties vk11_props;
  3452. vk::PhysicalDeviceVulkan12Properties vk12_props;
  3453. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  3454. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3455. props2.pNext = &props3;
  3456. props3.pNext = &subgroup_props;
  3457. subgroup_props.pNext = &driver_props;
  3458. driver_props.pNext = &vk11_props;
  3459. vk11_props.pNext = &vk12_props;
  3460. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  3461. if (maintenance4_support) {
  3462. last_struct->pNext = (VkBaseOutStructure *)&props4;
  3463. last_struct = (VkBaseOutStructure *)&props4;
  3464. }
  3465. if (sm_builtins) {
  3466. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  3467. last_struct = (VkBaseOutStructure *)&sm_props;
  3468. }
  3469. if (amd_shader_core_properties2) {
  3470. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3471. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3472. }
  3473. if (device->subgroup_size_control) {
  3474. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  3475. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  3476. }
  3477. #if defined(VK_NV_cooperative_matrix2)
  3478. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  3479. if (coopmat2_support) {
  3480. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  3481. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  3482. }
  3483. #endif
  3484. if (device->integer_dot_product) {
  3485. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3486. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3487. }
  3488. device->physical_device.getProperties2(&props2);
  3489. device->properties = props2.properties;
  3490. device->vendor_id = device->properties.vendorID;
  3491. device->driver_id = driver_props.driverID;
  3492. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  3493. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  3494. device->max_memory_allocation_size = std::stoull(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  3495. } else if (maintenance4_support) {
  3496. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  3497. } else {
  3498. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  3499. }
  3500. const char* GGML_VK_FORCE_MAX_BUFFER_SIZE = getenv("GGML_VK_FORCE_MAX_BUFFER_SIZE");
  3501. if (GGML_VK_FORCE_MAX_BUFFER_SIZE != nullptr) {
  3502. device->max_buffer_size = std::stoull(GGML_VK_FORCE_MAX_BUFFER_SIZE);
  3503. } else if (maintenance4_support) {
  3504. device->max_buffer_size = props4.maxBufferSize;
  3505. } else {
  3506. device->max_buffer_size = device->max_memory_allocation_size;
  3507. }
  3508. const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE");
  3509. if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) {
  3510. device->suballocation_block_size = std::stoull(GGML_VK_SUBALLOCATION_BLOCK_SIZE);
  3511. } else {
  3512. // Limit batching of allocations to 1GB by default to avoid fragmentation issues
  3513. device->suballocation_block_size = 1024*1024*1024;
  3514. }
  3515. device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size);
  3516. device->subgroup_size = subgroup_props.subgroupSize;
  3517. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3518. if (sm_builtins) {
  3519. device->shader_core_count = sm_props.shaderSMCount;
  3520. } else if (amd_shader_core_properties2) {
  3521. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  3522. } else {
  3523. device->shader_core_count = 0;
  3524. }
  3525. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  3526. device->subgroup_arithmetic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3527. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic);
  3528. #ifdef __APPLE__
  3529. // Workaround for subgroup arithmetic failing on MoltenVK with AMD GPUs (issue 15846)
  3530. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3531. device->subgroup_arithmetic = false;
  3532. }
  3533. #endif
  3534. device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3535. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle);
  3536. device->subgroup_clustered = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3537. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eClustered);
  3538. device->subgroup_ballot = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3539. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBallot);
  3540. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  3541. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  3542. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) {
  3543. device->coopmat_support = false;
  3544. }
  3545. device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated;
  3546. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  3547. // Try to find a non-graphics compute queue and transfer-focused queues
  3548. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  3549. 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);
  3550. const float priorities[] = { 1.0f, 1.0f };
  3551. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  3552. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  3553. if (compute_queue_family_index != transfer_queue_family_index) {
  3554. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3555. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  3556. } else if(!device->single_queue) {
  3557. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  3558. } else {
  3559. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3560. }
  3561. vk::DeviceCreateInfo device_create_info;
  3562. std::vector<const char *> device_extensions;
  3563. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  3564. VkPhysicalDeviceFeatures2 device_features2;
  3565. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  3566. device_features2.pNext = nullptr;
  3567. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  3568. VkPhysicalDeviceVulkan11Features vk11_features;
  3569. vk11_features.pNext = nullptr;
  3570. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  3571. device_features2.pNext = &vk11_features;
  3572. VkPhysicalDeviceVulkan12Features vk12_features;
  3573. vk12_features.pNext = nullptr;
  3574. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  3575. vk11_features.pNext = &vk12_features;
  3576. last_struct = (VkBaseOutStructure *)&vk12_features;
  3577. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  3578. pl_robustness_features.pNext = nullptr;
  3579. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  3580. pl_robustness_features.pipelineRobustness = VK_FALSE;
  3581. if (pipeline_robustness) {
  3582. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  3583. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  3584. device_extensions.push_back("VK_EXT_pipeline_robustness");
  3585. }
  3586. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  3587. subgroup_size_control_features.pNext = nullptr;
  3588. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  3589. subgroup_size_control_features.computeFullSubgroups = false;
  3590. subgroup_size_control_features.subgroupSizeControl = false;
  3591. if (device->subgroup_size_control) {
  3592. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  3593. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  3594. }
  3595. #if defined(VK_KHR_cooperative_matrix)
  3596. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  3597. coopmat_features.pNext = nullptr;
  3598. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  3599. coopmat_features.cooperativeMatrix = VK_FALSE;
  3600. if (device->coopmat_support) {
  3601. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  3602. last_struct = (VkBaseOutStructure *)&coopmat_features;
  3603. }
  3604. #endif
  3605. #if defined(VK_NV_cooperative_matrix2)
  3606. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  3607. coopmat2_features.pNext = nullptr;
  3608. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  3609. if (coopmat2_support) {
  3610. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  3611. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  3612. device_extensions.push_back("VK_NV_cooperative_matrix2");
  3613. }
  3614. #endif
  3615. #if defined(VK_KHR_shader_bfloat16)
  3616. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  3617. bfloat16_features.pNext = nullptr;
  3618. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  3619. if (bfloat16_support) {
  3620. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  3621. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  3622. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3623. }
  3624. #endif
  3625. VkPhysicalDeviceMaintenance4Features maint4_features {};
  3626. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  3627. if (maintenance4_support) {
  3628. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  3629. last_struct = (VkBaseOutStructure *)&maint4_features;
  3630. device_extensions.push_back("VK_KHR_maintenance4");
  3631. }
  3632. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  3633. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  3634. if (device->integer_dot_product) {
  3635. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3636. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3637. device_extensions.push_back("VK_KHR_shader_integer_dot_product");
  3638. }
  3639. VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pep_features {};
  3640. pep_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR;
  3641. if (pipeline_executable_properties_support) {
  3642. last_struct->pNext = (VkBaseOutStructure *)&pep_features;
  3643. last_struct = (VkBaseOutStructure *)&pep_features;
  3644. device_extensions.push_back("VK_KHR_pipeline_executable_properties");
  3645. }
  3646. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  3647. device->pipeline_executable_properties_support = pipeline_executable_properties_support;
  3648. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  3649. #if defined(VK_KHR_shader_bfloat16)
  3650. device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  3651. #else
  3652. device->bf16 = false;
  3653. #endif
  3654. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  3655. device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 &&
  3656. device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) &&
  3657. vk12_features.runtimeDescriptorArray &&
  3658. device->vendor_id != VK_VENDOR_ID_INTEL &&
  3659. getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr;
  3660. device->shader_int64 = device_features2.features.shaderInt64;
  3661. device->buffer_device_address = vk12_features.bufferDeviceAddress;
  3662. if (device->subgroup_size_control) {
  3663. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  3664. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  3665. device_extensions.push_back("VK_EXT_subgroup_size_control");
  3666. }
  3667. device->subgroup_size_control = device->subgroup_size_control &&
  3668. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  3669. subgroup_size_control_features.subgroupSizeControl;
  3670. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  3671. #if defined(VK_KHR_cooperative_matrix)
  3672. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  3673. // coopmat1 fa shader currently assumes 32 invocations per subgroup
  3674. device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support &&
  3675. device->subgroup_size_control && device->subgroup_min_size <= 32 &&
  3676. device->subgroup_max_size >= 32;
  3677. #endif
  3678. if (coopmat2_support) {
  3679. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3680. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  3681. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  3682. coopmat2_features.cooperativeMatrixReductions &&
  3683. coopmat2_features.cooperativeMatrixConversions &&
  3684. coopmat2_features.cooperativeMatrixPerElementOperations &&
  3685. coopmat2_features.cooperativeMatrixTensorAddressing &&
  3686. coopmat2_features.cooperativeMatrixBlockLoads &&
  3687. vk12_features.bufferDeviceAddress) {
  3688. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  3689. uint32_t count = 0;
  3690. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  3691. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  3692. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  3693. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  3694. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  3695. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  3696. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  3697. flexible_dimensions.resize(count, empty_prop);
  3698. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  3699. bool found_fp16_128 = false,
  3700. found_fp16_256 = false,
  3701. found_fp32_128 = false,
  3702. found_fp32_256 = false;
  3703. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  3704. // with 32x16x16 and 256 with 32x32x16.
  3705. for (auto &prop : flexible_dimensions) {
  3706. if (prop.saturatingAccumulation == VK_FALSE &&
  3707. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  3708. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3709. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3710. if (prop.workgroupInvocations == 128 &&
  3711. prop.MGranularity <= 32 &&
  3712. prop.NGranularity <= 16 &&
  3713. prop.KGranularity <= 16) {
  3714. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3715. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3716. found_fp16_128 = true;
  3717. }
  3718. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3719. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3720. found_fp32_128 = true;
  3721. }
  3722. }
  3723. if (prop.workgroupInvocations == 256 &&
  3724. prop.MGranularity <= 32 &&
  3725. prop.NGranularity <= 32 &&
  3726. prop.KGranularity <= 16) {
  3727. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3728. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3729. found_fp16_256 = true;
  3730. }
  3731. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3732. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3733. found_fp32_256 = true;
  3734. }
  3735. }
  3736. }
  3737. }
  3738. if (found_fp16_128 && found_fp16_256 &&
  3739. found_fp32_128 && found_fp32_256 &&
  3740. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  3741. device->coopmat2 = true;
  3742. }
  3743. }
  3744. #endif
  3745. }
  3746. if (!vk11_features.storageBuffer16BitAccess) {
  3747. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  3748. throw std::runtime_error("Unsupported device");
  3749. }
  3750. device_extensions.push_back("VK_KHR_16bit_storage");
  3751. #ifdef GGML_VULKAN_VALIDATE
  3752. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  3753. #endif
  3754. if (device->fp16) {
  3755. device_extensions.push_back("VK_KHR_shader_float16_int8");
  3756. }
  3757. #if defined(VK_KHR_cooperative_matrix)
  3758. if (device->coopmat_support) {
  3759. // Query supported shapes
  3760. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  3761. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  3762. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  3763. uint32_t cm_props_num;
  3764. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  3765. cm_props.resize(cm_props_num);
  3766. for (auto& prop : cm_props) {
  3767. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  3768. }
  3769. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  3770. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  3771. for (auto& prop : cm_props) {
  3772. 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));
  3773. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  3774. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  3775. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3776. ) {
  3777. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  3778. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  3779. // coopmat sizes not set yet
  3780. if (device->coopmat_m == 0) {
  3781. device->coopmat_acc_f32_support = true;
  3782. device->coopmat_m = prop.MSize;
  3783. device->coopmat_n = prop.NSize;
  3784. device->coopmat_k = prop.KSize;
  3785. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3786. // Only enable if shape is identical
  3787. device->coopmat_acc_f32_support = true;
  3788. }
  3789. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3790. device->coopmat_support_16x16x16_f32acc = true;
  3791. }
  3792. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  3793. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  3794. // coopmat sizes not set yet
  3795. if (device->coopmat_m == 0) {
  3796. device->coopmat_acc_f16_support = true;
  3797. device->coopmat_m = prop.MSize;
  3798. device->coopmat_n = prop.NSize;
  3799. device->coopmat_k = prop.KSize;
  3800. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3801. // Only enable if shape is identical
  3802. device->coopmat_acc_f16_support = true;
  3803. }
  3804. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3805. device->coopmat_support_16x16x16_f16acc = true;
  3806. }
  3807. }
  3808. } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 &&
  3809. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 &&
  3810. (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 &&
  3811. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 &&
  3812. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup &&
  3813. device->coopmat_int_m == 0
  3814. ) {
  3815. device->coopmat_int_support = true;
  3816. device->coopmat_int_m = prop.MSize;
  3817. device->coopmat_int_n = prop.NSize;
  3818. device->coopmat_int_k = prop.KSize;
  3819. }
  3820. #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3821. if (prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3822. prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3823. prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3824. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3825. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3826. ) {
  3827. // coopmat sizes not set yet
  3828. if (device->coopmat_m == 0) {
  3829. device->coopmat_bf16_support = true;
  3830. device->coopmat_m = prop.MSize;
  3831. device->coopmat_n = prop.NSize;
  3832. device->coopmat_k = prop.KSize;
  3833. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3834. // Only enable if shape is identical
  3835. device->coopmat_bf16_support = true;
  3836. }
  3837. }
  3838. #endif
  3839. }
  3840. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  3841. // No suitable matmul mode found
  3842. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  3843. device->coopmat_support = false;
  3844. }
  3845. if (getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3846. device->coopmat_bf16_support = false;
  3847. }
  3848. }
  3849. if (device->coopmat_support) {
  3850. device_extensions.push_back("VK_KHR_cooperative_matrix");
  3851. }
  3852. #if defined(VK_KHR_shader_bfloat16)
  3853. if (device->coopmat_bf16_support) {
  3854. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3855. }
  3856. #endif
  3857. #endif
  3858. device->name = GGML_VK_NAME + std::to_string(idx);
  3859. device_create_info = {
  3860. vk::DeviceCreateFlags(),
  3861. device_queue_create_infos,
  3862. {},
  3863. device_extensions
  3864. };
  3865. device_create_info.setPNext(&device_features2);
  3866. device->device = device->physical_device.createDevice(device_create_info);
  3867. // Queues
  3868. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  3869. // Shaders
  3870. // Disable matmul tile sizes early if performance low or not supported
  3871. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  3872. switch (device->vendor_id) {
  3873. #ifndef GGML_VULKAN_RUN_TESTS
  3874. case VK_VENDOR_ID_AMD:
  3875. case VK_VENDOR_ID_INTEL:
  3876. device->mul_mat_l[i] = false;
  3877. device->mul_mat_m[i] = true;
  3878. device->mul_mat_s[i] = true;
  3879. device->mul_mat_id_l[i] = false;
  3880. device->mul_mat_id_m[i] = true;
  3881. device->mul_mat_id_s[i] = true;
  3882. break;
  3883. case VK_VENDOR_ID_APPLE:
  3884. device->mul_mat_l[i] = false;
  3885. device->mul_mat_m[i] = true;
  3886. device->mul_mat_s[i] = false;
  3887. device->mul_mat_id_l[i] = false;
  3888. device->mul_mat_id_m[i] = true;
  3889. device->mul_mat_id_s[i] = false;
  3890. break;
  3891. #endif
  3892. default:
  3893. device->mul_mat_l[i] = true;
  3894. device->mul_mat_m[i] = true;
  3895. device->mul_mat_s[i] = true;
  3896. device->mul_mat_id_l[i] = true;
  3897. device->mul_mat_id_m[i] = true;
  3898. device->mul_mat_id_s[i] = true;
  3899. break;
  3900. }
  3901. }
  3902. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  3903. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  3904. for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
  3905. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  3906. dsl_binding_flags.push_back({});
  3907. }
  3908. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  3909. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  3910. {},
  3911. dsl_binding);
  3912. descriptor_set_layout_create_info.setPNext(&dslbfci);
  3913. device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  3914. ggml_vk_load_shaders(device);
  3915. if (!device->single_queue) {
  3916. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  3917. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  3918. } else {
  3919. // TODO: Use pointer or reference to avoid copy
  3920. device->transfer_queue.copyFrom(device->compute_queue);
  3921. device->transfer_queue.cmd_pool.init(device, &device->transfer_queue);
  3922. }
  3923. device->buffer_type = {
  3924. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  3925. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  3926. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  3927. };
  3928. device->fence = device->device.createFence({});
  3929. device->idx = idx;
  3930. device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr;
  3931. device->add_rms_fusion = !device->disable_fusion &&
  3932. device->subgroup_arithmetic &&
  3933. device->vendor_id != VK_VENDOR_ID_INTEL;
  3934. device->partials_binding_alignment =
  3935. std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment);
  3936. device->mmvq_mode = 0;
  3937. if (getenv("GGML_VK_DISABLE_MMVQ")) {
  3938. device->mmvq_mode = -1;
  3939. } else if (getenv("GGML_VK_FORCE_MMVQ")) {
  3940. device->mmvq_mode = 1;
  3941. }
  3942. return device;
  3943. }
  3944. return vk_instance.devices[idx];
  3945. }
  3946. static void ggml_vk_print_gpu_info(size_t idx) {
  3947. GGML_ASSERT(idx < vk_instance.device_indices.size());
  3948. size_t dev_num = vk_instance.device_indices[idx];
  3949. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  3950. GGML_ASSERT(vk_instance_initialized);
  3951. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  3952. if (dev_num >= devices.size()) {
  3953. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3954. throw std::runtime_error("Device not found");
  3955. }
  3956. vk::PhysicalDevice physical_device = devices[dev_num];
  3957. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  3958. bool fp16_storage = false;
  3959. bool fp16_compute = false;
  3960. bool coopmat_support = false;
  3961. bool coopmat2_support = false;
  3962. bool integer_dot_product = false;
  3963. bool bfloat16_support = false;
  3964. for (auto properties : ext_props) {
  3965. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3966. fp16_storage = true;
  3967. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3968. fp16_compute = true;
  3969. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3970. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3971. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3972. coopmat_support = true;
  3973. #endif
  3974. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3975. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3976. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3977. coopmat2_support = true;
  3978. #endif
  3979. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3980. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3981. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3982. integer_dot_product = true;
  3983. #endif
  3984. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3985. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3986. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3987. bfloat16_support = true;
  3988. #endif
  3989. }
  3990. }
  3991. const vk_device_architecture device_architecture = get_device_architecture(physical_device);
  3992. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  3993. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  3994. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  3995. vk::PhysicalDeviceProperties2 props2;
  3996. vk::PhysicalDeviceMaintenance3Properties props3;
  3997. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3998. vk::PhysicalDeviceDriverProperties driver_props;
  3999. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  4000. props2.pNext = &props3;
  4001. props3.pNext = &subgroup_props;
  4002. subgroup_props.pNext = &driver_props;
  4003. // Pointer to the last chain element
  4004. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  4005. if (integer_dot_product) {
  4006. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4007. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4008. }
  4009. physical_device.getProperties2(&props2);
  4010. VkPhysicalDeviceFeatures2 device_features2;
  4011. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  4012. device_features2.pNext = nullptr;
  4013. VkPhysicalDeviceVulkan11Features vk11_features;
  4014. vk11_features.pNext = nullptr;
  4015. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  4016. device_features2.pNext = &vk11_features;
  4017. VkPhysicalDeviceVulkan12Features vk12_features;
  4018. vk12_features.pNext = nullptr;
  4019. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  4020. vk11_features.pNext = &vk12_features;
  4021. // Pointer to the last chain element
  4022. last_struct = (VkBaseOutStructure *)&vk12_features;
  4023. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4024. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  4025. coopmat_features.pNext = nullptr;
  4026. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  4027. coopmat_features.cooperativeMatrix = VK_FALSE;
  4028. if (coopmat_support) {
  4029. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  4030. last_struct = (VkBaseOutStructure *)&coopmat_features;
  4031. }
  4032. #endif
  4033. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  4034. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  4035. if (integer_dot_product) {
  4036. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4037. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4038. }
  4039. #if defined(VK_KHR_shader_bfloat16)
  4040. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  4041. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  4042. if (bfloat16_support) {
  4043. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  4044. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  4045. }
  4046. #endif
  4047. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  4048. fp16 = fp16 && vk12_features.shaderFloat16;
  4049. #if defined(VK_KHR_shader_bfloat16)
  4050. bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4051. #else
  4052. bool bf16 = false;
  4053. #endif
  4054. uint32_t default_subgroup_size = get_subgroup_size("", device_architecture);
  4055. const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize;
  4056. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  4057. integer_dot_product = integer_dot_product
  4058. && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated
  4059. && shader_integer_dot_product_features.shaderIntegerDotProduct;
  4060. coopmat_support = coopmat_support
  4061. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4062. && coopmat_features.cooperativeMatrix
  4063. #endif
  4064. && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture);
  4065. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  4066. std::string device_name = props2.properties.deviceName.data();
  4067. 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",
  4068. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, bf16, subgroup_size,
  4069. props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str());
  4070. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  4071. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  4072. }
  4073. }
  4074. static bool ggml_vk_instance_validation_ext_available();
  4075. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  4076. static bool ggml_vk_instance_debug_utils_ext_available(const std::vector<vk::ExtensionProperties> & instance_extensions);
  4077. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev);
  4078. static DispatchLoaderDynamic ggml_vk_default_dispatcher_instance;
  4079. DispatchLoaderDynamic & ggml_vk_default_dispatcher() {
  4080. return ggml_vk_default_dispatcher_instance;
  4081. }
  4082. static void ggml_vk_instance_init() {
  4083. if (vk_instance_initialized) {
  4084. return;
  4085. }
  4086. VK_LOG_DEBUG("ggml_vk_instance_init()");
  4087. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4088. ggml_vk_default_dispatcher_instance.init(vkGetInstanceProcAddr);
  4089. uint32_t api_version = vk::enumerateInstanceVersion();
  4090. if (api_version < VK_API_VERSION_1_2) {
  4091. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  4092. throw vk::SystemError(vk::Result::eErrorFeatureNotPresent, "Vulkan 1.2 required");
  4093. }
  4094. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  4095. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  4096. const bool validation_ext = ggml_vk_instance_validation_ext_available();
  4097. #ifdef __APPLE__
  4098. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  4099. #endif
  4100. const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr;
  4101. std::vector<const char*> layers;
  4102. if (validation_ext) {
  4103. layers.push_back("VK_LAYER_KHRONOS_validation");
  4104. }
  4105. std::vector<const char*> extensions;
  4106. if (validation_ext) {
  4107. extensions.push_back("VK_EXT_validation_features");
  4108. }
  4109. #ifdef __APPLE__
  4110. if (portability_enumeration_ext) {
  4111. extensions.push_back("VK_KHR_portability_enumeration");
  4112. }
  4113. #endif
  4114. if (debug_utils_ext) {
  4115. extensions.push_back("VK_EXT_debug_utils");
  4116. }
  4117. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions);
  4118. #ifdef __APPLE__
  4119. if (portability_enumeration_ext) {
  4120. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  4121. }
  4122. #endif
  4123. std::vector<vk::ValidationFeatureEnableEXT> features_enable;
  4124. vk::ValidationFeaturesEXT validation_features;
  4125. if (validation_ext) {
  4126. features_enable = { vk::ValidationFeatureEnableEXT::eBestPractices };
  4127. validation_features = {
  4128. features_enable,
  4129. {},
  4130. };
  4131. validation_features.setPNext(nullptr);
  4132. instance_create_info.setPNext(&validation_features);
  4133. GGML_LOG_DEBUG("ggml_vulkan: Validation layers enabled\n");
  4134. }
  4135. vk_instance.instance = vk::createInstance(instance_create_info);
  4136. vk_instance_initialized = true;
  4137. if (debug_utils_ext) {
  4138. vk_instance.debug_utils_support = true;
  4139. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT");
  4140. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT");
  4141. vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT");
  4142. vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT");
  4143. vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT");
  4144. vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT");
  4145. }
  4146. vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr;
  4147. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4148. VULKAN_HPP_DEFAULT_DISPATCHER.init(vk_instance.instance);
  4149. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4150. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  4151. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  4152. if (devices_env != nullptr) {
  4153. size_t num_available_devices = devices.size();
  4154. std::string devices(devices_env);
  4155. std::replace(devices.begin(), devices.end(), ',', ' ');
  4156. std::stringstream ss(devices);
  4157. size_t tmp;
  4158. while (ss >> tmp) {
  4159. if(tmp >= num_available_devices) {
  4160. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  4161. throw std::runtime_error("Invalid Vulkan device index");
  4162. }
  4163. vk_instance.device_indices.push_back(tmp);
  4164. }
  4165. } else {
  4166. // If no vulkan devices are found, return early
  4167. if (devices.empty()) {
  4168. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4169. return;
  4170. }
  4171. // Default to using all dedicated GPUs
  4172. for (size_t i = 0; i < devices.size(); i++) {
  4173. vk::PhysicalDeviceProperties2 new_props;
  4174. vk::PhysicalDeviceDriverProperties new_driver;
  4175. vk::PhysicalDeviceIDProperties new_id;
  4176. new_props.pNext = &new_driver;
  4177. new_driver.pNext = &new_id;
  4178. devices[i].getProperties2(&new_props);
  4179. if ((new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu || new_props.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) && ggml_vk_device_is_supported(devices[i])) {
  4180. // Check if there are two physical devices corresponding to the same GPU
  4181. auto old_device = std::find_if(
  4182. vk_instance.device_indices.begin(),
  4183. vk_instance.device_indices.end(),
  4184. [&devices, &new_id](const size_t k){
  4185. vk::PhysicalDeviceProperties2 old_props;
  4186. vk::PhysicalDeviceIDProperties old_id;
  4187. old_props.pNext = &old_id;
  4188. devices[k].getProperties2(&old_props);
  4189. bool equals = std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  4190. equals = equals || (
  4191. old_id.deviceLUIDValid && new_id.deviceLUIDValid &&
  4192. std::equal(std::begin(old_id.deviceLUID), std::end(old_id.deviceLUID), std::begin(new_id.deviceLUID))
  4193. );
  4194. return equals;
  4195. }
  4196. );
  4197. if (old_device == vk_instance.device_indices.end()) {
  4198. vk_instance.device_indices.push_back(i);
  4199. } else {
  4200. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  4201. // This can cause error when splitting layers aross the devices, need to keep only 1
  4202. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  4203. vk::PhysicalDeviceProperties2 old_props;
  4204. vk::PhysicalDeviceDriverProperties old_driver;
  4205. old_props.pNext = &old_driver;
  4206. devices[*old_device].getProperties2(&old_props);
  4207. std::map<vk::DriverId, int> driver_priorities {};
  4208. int old_priority = std::numeric_limits<int>::max();
  4209. int new_priority = std::numeric_limits<int>::max();
  4210. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  4211. // Smaller number -> higher priority
  4212. switch (old_props.properties.vendorID) {
  4213. case VK_VENDOR_ID_AMD:
  4214. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  4215. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  4216. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  4217. break;
  4218. case VK_VENDOR_ID_INTEL:
  4219. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  4220. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  4221. break;
  4222. case VK_VENDOR_ID_NVIDIA:
  4223. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  4224. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  4225. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  4226. #endif
  4227. break;
  4228. }
  4229. driver_priorities[vk::DriverId::eMesaDozen] = 100;
  4230. if (driver_priorities.count(old_driver.driverID)) {
  4231. old_priority = driver_priorities[old_driver.driverID];
  4232. }
  4233. if (driver_priorities.count(new_driver.driverID)) {
  4234. new_priority = driver_priorities[new_driver.driverID];
  4235. }
  4236. if (new_priority < old_priority) {
  4237. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  4238. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  4239. vk_instance.device_indices.push_back(i);
  4240. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  4241. }
  4242. else {
  4243. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  4244. }
  4245. }
  4246. }
  4247. }
  4248. // If no GPUs found, fall back to the first non-CPU device.
  4249. // If only CPU devices are available, return without devices.
  4250. if (vk_instance.device_indices.empty()) {
  4251. for (size_t i = 0; i < devices.size(); i++) {
  4252. if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) {
  4253. vk_instance.device_indices.push_back(i);
  4254. break;
  4255. }
  4256. }
  4257. }
  4258. if (vk_instance.device_indices.empty()) {
  4259. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4260. return;
  4261. }
  4262. }
  4263. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  4264. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  4265. vk::PhysicalDevice vkdev = devices[vk_instance.device_indices[i]];
  4266. std::vector<vk::ExtensionProperties> extensionprops = vkdev.enumerateDeviceExtensionProperties();
  4267. bool membudget_supported = false;
  4268. for (const auto & ext : extensionprops) {
  4269. if (strcmp(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, ext.extensionName) == 0) {
  4270. membudget_supported = true;
  4271. break;
  4272. }
  4273. }
  4274. vk_instance.device_supports_membudget.push_back(membudget_supported);
  4275. ggml_vk_print_gpu_info(i);
  4276. }
  4277. }
  4278. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  4279. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  4280. ggml_vk_instance_init();
  4281. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4282. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4283. ctx->device = ggml_vk_get_device(idx);
  4284. ctx->semaphore_idx = 0;
  4285. ctx->event_idx = 0;
  4286. ctx->prealloc_size_x = 0;
  4287. ctx->prealloc_size_y = 0;
  4288. ctx->prealloc_size_split_k = 0;
  4289. ctx->fence = ctx->device->device.createFence({});
  4290. ctx->almost_ready_fence = ctx->device->device.createFence({});
  4291. ctx->compute_cmd_pool.init(ctx->device, &ctx->device->compute_queue);
  4292. ctx->transfer_cmd_pool.init(ctx->device, &ctx->device->transfer_queue);
  4293. #ifdef GGML_VULKAN_CHECK_RESULTS
  4294. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  4295. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  4296. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  4297. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  4298. #endif
  4299. }
  4300. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  4301. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  4302. switch (type) {
  4303. case GGML_TYPE_F32:
  4304. case GGML_TYPE_Q4_0:
  4305. case GGML_TYPE_Q4_1:
  4306. case GGML_TYPE_Q5_0:
  4307. case GGML_TYPE_Q5_1:
  4308. case GGML_TYPE_Q8_0:
  4309. case GGML_TYPE_Q2_K:
  4310. case GGML_TYPE_Q3_K:
  4311. case GGML_TYPE_Q4_K:
  4312. case GGML_TYPE_Q5_K:
  4313. case GGML_TYPE_Q6_K:
  4314. case GGML_TYPE_IQ1_S:
  4315. case GGML_TYPE_IQ1_M:
  4316. case GGML_TYPE_IQ2_XXS:
  4317. case GGML_TYPE_IQ2_XS:
  4318. case GGML_TYPE_IQ2_S:
  4319. case GGML_TYPE_IQ3_XXS:
  4320. case GGML_TYPE_IQ3_S:
  4321. case GGML_TYPE_IQ4_XS:
  4322. case GGML_TYPE_IQ4_NL:
  4323. case GGML_TYPE_MXFP4:
  4324. break;
  4325. default:
  4326. return nullptr;
  4327. }
  4328. return ctx->device->pipeline_dequant[type];
  4329. }
  4330. 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) {
  4331. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ", " << prec << ")");
  4332. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4333. return ctx->device->pipeline_matmul_f32;
  4334. }
  4335. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4336. return ctx->device->pipeline_matmul_f32_f16;
  4337. }
  4338. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4339. return ctx->device->pipeline_matmul_bf16;
  4340. }
  4341. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4342. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4343. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  4344. }
  4345. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4346. return ctx->device->pipeline_matmul_f16.f16acc;
  4347. }
  4348. } else {
  4349. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4350. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  4351. }
  4352. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4353. return ctx->device->pipeline_matmul_f16.f32acc;
  4354. }
  4355. }
  4356. // MMQ
  4357. if (src1_type == GGML_TYPE_Q8_1) {
  4358. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1[src0_type].f32acc;
  4359. if (pipelines->is_empty()) {
  4360. return nullptr;
  4361. }
  4362. return pipelines;
  4363. }
  4364. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  4365. return nullptr;
  4366. }
  4367. switch (src0_type) {
  4368. case GGML_TYPE_Q4_0:
  4369. case GGML_TYPE_Q4_1:
  4370. case GGML_TYPE_Q5_0:
  4371. case GGML_TYPE_Q5_1:
  4372. case GGML_TYPE_Q8_0:
  4373. case GGML_TYPE_Q2_K:
  4374. case GGML_TYPE_Q3_K:
  4375. case GGML_TYPE_Q4_K:
  4376. case GGML_TYPE_Q5_K:
  4377. case GGML_TYPE_Q6_K:
  4378. case GGML_TYPE_IQ1_S:
  4379. case GGML_TYPE_IQ1_M:
  4380. case GGML_TYPE_IQ2_XXS:
  4381. case GGML_TYPE_IQ2_XS:
  4382. case GGML_TYPE_IQ2_S:
  4383. case GGML_TYPE_IQ3_XXS:
  4384. case GGML_TYPE_IQ3_S:
  4385. case GGML_TYPE_IQ4_XS:
  4386. case GGML_TYPE_IQ4_NL:
  4387. case GGML_TYPE_MXFP4:
  4388. break;
  4389. default:
  4390. return nullptr;
  4391. }
  4392. if (ctx->device->coopmat2) {
  4393. assert(src1_type == GGML_TYPE_F16);
  4394. 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;
  4395. }
  4396. if (ctx->device->coopmat_support) {
  4397. 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;
  4398. }
  4399. 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;
  4400. }
  4401. 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) {
  4402. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  4403. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1);
  4404. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  4405. if (b_type == GGML_TYPE_Q8_1) {
  4406. switch (a_type) {
  4407. case GGML_TYPE_Q4_0:
  4408. case GGML_TYPE_Q4_1:
  4409. case GGML_TYPE_Q5_0:
  4410. case GGML_TYPE_Q5_1:
  4411. case GGML_TYPE_Q8_0:
  4412. break;
  4413. default:
  4414. return nullptr;
  4415. }
  4416. }
  4417. switch (a_type) {
  4418. case GGML_TYPE_F32:
  4419. case GGML_TYPE_F16:
  4420. case GGML_TYPE_BF16:
  4421. case GGML_TYPE_Q4_0:
  4422. case GGML_TYPE_Q4_1:
  4423. case GGML_TYPE_Q5_0:
  4424. case GGML_TYPE_Q5_1:
  4425. case GGML_TYPE_Q8_0:
  4426. case GGML_TYPE_Q2_K:
  4427. case GGML_TYPE_Q3_K:
  4428. case GGML_TYPE_Q4_K:
  4429. case GGML_TYPE_Q5_K:
  4430. case GGML_TYPE_Q6_K:
  4431. case GGML_TYPE_IQ1_S:
  4432. case GGML_TYPE_IQ1_M:
  4433. case GGML_TYPE_IQ2_XXS:
  4434. case GGML_TYPE_IQ2_XS:
  4435. case GGML_TYPE_IQ2_S:
  4436. case GGML_TYPE_IQ3_XXS:
  4437. case GGML_TYPE_IQ3_S:
  4438. case GGML_TYPE_IQ4_XS:
  4439. case GGML_TYPE_IQ4_NL:
  4440. case GGML_TYPE_MXFP4:
  4441. break;
  4442. default:
  4443. return nullptr;
  4444. }
  4445. // heuristic to choose workgroup size
  4446. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4447. 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) {
  4448. // Prefer larger workgroups when M is small, to spread the work out more
  4449. // and keep more SMs busy.
  4450. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4451. if (a_type == GGML_TYPE_Q6_K) {
  4452. if (m < 4096 && k >= 1024) {
  4453. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4454. }
  4455. } else {
  4456. if (m <= 8192 && k >= 1024) {
  4457. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4458. }
  4459. }
  4460. }
  4461. if (b_type == GGML_TYPE_Q8_1) {
  4462. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4463. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4464. }
  4465. return ctx->device->pipeline_dequant_mul_mat_vec_q8_1_f32[dmmv_wg][a_type][num_cols-1];
  4466. }
  4467. 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];
  4468. }
  4469. 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) {
  4470. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  4471. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4472. return ctx->device->pipeline_matmul_id_f32;
  4473. }
  4474. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4475. return ctx->device->pipeline_matmul_id_bf16;
  4476. }
  4477. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4478. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4479. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  4480. }
  4481. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4482. return ctx->device->pipeline_matmul_id_f16.f16acc;
  4483. }
  4484. } else {
  4485. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4486. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  4487. }
  4488. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4489. return ctx->device->pipeline_matmul_id_f16.f32acc;
  4490. }
  4491. }
  4492. // MMQ
  4493. if (src1_type == GGML_TYPE_Q8_1) {
  4494. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_id_q8_1[src0_type].f32acc;
  4495. if (pipelines->is_empty()) {
  4496. return nullptr;
  4497. }
  4498. return pipelines;
  4499. }
  4500. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  4501. switch (src0_type) {
  4502. case GGML_TYPE_Q4_0:
  4503. case GGML_TYPE_Q4_1:
  4504. case GGML_TYPE_Q5_0:
  4505. case GGML_TYPE_Q5_1:
  4506. case GGML_TYPE_Q8_0:
  4507. case GGML_TYPE_Q2_K:
  4508. case GGML_TYPE_Q3_K:
  4509. case GGML_TYPE_Q4_K:
  4510. case GGML_TYPE_Q5_K:
  4511. case GGML_TYPE_Q6_K:
  4512. case GGML_TYPE_IQ1_S:
  4513. case GGML_TYPE_IQ1_M:
  4514. case GGML_TYPE_IQ2_XXS:
  4515. case GGML_TYPE_IQ2_XS:
  4516. case GGML_TYPE_IQ2_S:
  4517. case GGML_TYPE_IQ3_XXS:
  4518. case GGML_TYPE_IQ3_S:
  4519. case GGML_TYPE_IQ4_XS:
  4520. case GGML_TYPE_IQ4_NL:
  4521. case GGML_TYPE_MXFP4:
  4522. break;
  4523. default:
  4524. return nullptr;
  4525. }
  4526. vk_matmul_pipeline2& mmp = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type];
  4527. // XXX TODO 'prec' is not actually allowed in mul_mat_id.
  4528. bool prefer_fp16acc = ctx->device->fp16 /*&& prec == GGML_PREC_DEFAULT*/;
  4529. bool support_fp16acc = !mmp.f16acc->is_empty();
  4530. bool support_fp32acc = !mmp.f32acc->is_empty();
  4531. if (support_fp16acc && (prefer_fp16acc || !support_fp32acc)) {
  4532. return mmp.f16acc;
  4533. } else {
  4534. GGML_ASSERT(support_fp32acc);
  4535. return mmp.f32acc;
  4536. }
  4537. }
  4538. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type) {
  4539. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()");
  4540. GGML_ASSERT(b_type == GGML_TYPE_F32);
  4541. switch (a_type) {
  4542. case GGML_TYPE_F32:
  4543. case GGML_TYPE_F16:
  4544. case GGML_TYPE_BF16:
  4545. case GGML_TYPE_Q4_0:
  4546. case GGML_TYPE_Q4_1:
  4547. case GGML_TYPE_Q5_0:
  4548. case GGML_TYPE_Q5_1:
  4549. case GGML_TYPE_Q8_0:
  4550. case GGML_TYPE_Q2_K:
  4551. case GGML_TYPE_Q3_K:
  4552. case GGML_TYPE_Q4_K:
  4553. case GGML_TYPE_Q5_K:
  4554. case GGML_TYPE_Q6_K:
  4555. case GGML_TYPE_IQ1_S:
  4556. case GGML_TYPE_IQ1_M:
  4557. case GGML_TYPE_IQ2_XXS:
  4558. case GGML_TYPE_IQ2_XS:
  4559. case GGML_TYPE_IQ2_S:
  4560. case GGML_TYPE_IQ3_XXS:
  4561. case GGML_TYPE_IQ3_S:
  4562. case GGML_TYPE_IQ4_XS:
  4563. case GGML_TYPE_IQ4_NL:
  4564. case GGML_TYPE_MXFP4:
  4565. break;
  4566. default:
  4567. return nullptr;
  4568. }
  4569. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[a_type];
  4570. }
  4571. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  4572. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  4573. vk_buffer buf = ggml_vk_create_buffer(device, size,
  4574. {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4575. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  4576. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  4577. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  4578. size/1024.0/1024.0);
  4579. device->device.freeMemory(buf->device_memory);
  4580. device->device.destroyBuffer(buf->buffer);
  4581. return nullptr;
  4582. }
  4583. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4584. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  4585. return buf->ptr;
  4586. }
  4587. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  4588. if (ptr == nullptr) {
  4589. return;
  4590. }
  4591. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  4592. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4593. vk_buffer buf;
  4594. size_t index;
  4595. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4596. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4597. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4598. if (ptr >= addr && ptr < endr) {
  4599. buf = std::get<2>(device->pinned_memory[i]);
  4600. index = i;
  4601. break;
  4602. }
  4603. }
  4604. if (buf == nullptr) {
  4605. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  4606. return;
  4607. }
  4608. ggml_vk_destroy_buffer(buf);
  4609. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  4610. }
  4611. static void ggml_vk_host_get(vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  4612. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4613. buf = nullptr;
  4614. buf_offset = 0;
  4615. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4616. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4617. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4618. if (ptr >= addr && ptr < endr) {
  4619. buf = std::get<2>(device->pinned_memory[i]);
  4620. buf_offset = ((const uint8_t *)ptr) - addr;
  4621. break;
  4622. }
  4623. }
  4624. }
  4625. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) {
  4626. vk_submission s;
  4627. s.buffer = ggml_vk_create_cmd_buffer(device, p);
  4628. if (one_time) {
  4629. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  4630. } else {
  4631. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  4632. }
  4633. return s;
  4634. }
  4635. template <typename T> size_t push_constant_size(const T &t) {
  4636. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4637. GGML_UNUSED(t);
  4638. return sizeof(T);
  4639. }
  4640. template <typename T> size_t push_constant_size(const std::vector<T> &t) {
  4641. GGML_UNUSED(t);
  4642. return sizeof(T) * t.size();
  4643. }
  4644. template <typename T, uint32_t N> size_t push_constant_size(const std::array<T, N> &t) {
  4645. GGML_UNUSED(t);
  4646. return sizeof(T) * N;
  4647. }
  4648. template <typename T> const T *push_constant_data(const T &t) {
  4649. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4650. return &t;
  4651. }
  4652. template <typename T> const T *push_constant_data(const std::vector<T> &t) {
  4653. return t.data();
  4654. }
  4655. template <typename T, uint32_t N> const T *push_constant_data(const std::array<T, N> &t) {
  4656. return t.data();
  4657. }
  4658. template <typename T>
  4659. 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) {
  4660. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  4661. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  4662. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  4663. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  4664. for (auto& buffer : descriptor_buffer_infos) {
  4665. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  4666. }
  4667. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  4668. GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size());
  4669. GGML_ASSERT(descriptor_buffer_infos.size() <= MAX_PARAMETER_COUNT);
  4670. GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size());
  4671. vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[ctx->descriptor_set_idx++];
  4672. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  4673. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  4674. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size(push_constants), push_constant_data(push_constants));
  4675. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  4676. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  4677. pipeline->layout,
  4678. 0,
  4679. { descriptor_set },
  4680. {});
  4681. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  4682. }
  4683. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  4684. s.buffer.end();
  4685. s.wait_semaphores = std::move(wait_semaphores);
  4686. s.signal_semaphores = std::move(signal_semaphores);
  4687. }
  4688. static void ggml_vk_ctx_end(vk_context& ctx) {
  4689. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  4690. if (ctx->s == nullptr) {
  4691. return;
  4692. }
  4693. ctx->s->buffer.end();
  4694. ctx->s = nullptr;
  4695. }
  4696. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  4697. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  4698. if (subctx->s != nullptr) {
  4699. ggml_vk_ctx_end(subctx);
  4700. }
  4701. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) });
  4702. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  4703. }
  4704. static size_t ggml_vk_align_size(size_t width, size_t align) {
  4705. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  4706. return CEIL_DIV(width, align) * align;
  4707. }
  4708. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  4709. if (memcpys == nullptr) {
  4710. memcpy(dst, src, size);
  4711. } else {
  4712. memcpys->emplace_back(dst, src, size);
  4713. }
  4714. }
  4715. static void deferred_memset(void * dst, uint32_t val, size_t size, std::vector<vk_staging_memset>* memsets = nullptr) {
  4716. if (memsets == nullptr) {
  4717. memset(dst, val, size);
  4718. } else {
  4719. memsets->emplace_back(dst, val, size);
  4720. }
  4721. }
  4722. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  4723. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  4724. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  4725. ggml_vk_destroy_buffer(device->sync_staging);
  4726. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  4727. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4728. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  4729. }
  4730. }
  4731. 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) {
  4732. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  4733. GGML_ASSERT(!ggml_is_contiguous(tensor));
  4734. // Buffer is already mapped
  4735. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4736. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4737. GGML_ABORT("fatal error");
  4738. }
  4739. // Check if src is pinned memory
  4740. vk_buffer buf = nullptr;
  4741. size_t buf_offset = 0;
  4742. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  4743. const uint64_t ne0 = tensor->ne[0];
  4744. const uint64_t ne1 = tensor->ne[1];
  4745. const uint64_t ne2 = tensor->ne[2];
  4746. const uint64_t ne3 = tensor->ne[3];
  4747. const uint64_t nb0 = tensor->nb[0];
  4748. const uint64_t nb1 = tensor->nb[1];
  4749. const uint64_t nb2 = tensor->nb[2];
  4750. const uint64_t nb3 = tensor->nb[3];
  4751. const ggml_type type = tensor->type;
  4752. const uint64_t ts = ggml_type_size(type);
  4753. const uint64_t bs = ggml_blck_size(type);
  4754. const uint64_t dstnb0 = ts;
  4755. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  4756. const uint64_t dstnb2 = dstnb1*ne1;
  4757. const uint64_t dstnb3 = dstnb2*ne2;
  4758. const uint64_t ne = ggml_nelements(tensor);
  4759. if (buf != nullptr) {
  4760. // Memory is pinned, use as staging buffer
  4761. std::vector<vk::BufferCopy> slices;
  4762. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4763. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4764. // Find longest contiguous slice
  4765. if (ne1*nb1 == dstnb2) {
  4766. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  4767. } else {
  4768. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4769. if (ne0*nb0/bs == dstnb1) {
  4770. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  4771. } else {
  4772. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4773. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4774. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4775. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  4776. }
  4777. }
  4778. }
  4779. }
  4780. }
  4781. }
  4782. ggml_vk_sync_buffers(ctx, subctx);
  4783. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  4784. return;
  4785. }
  4786. if (!sync_staging) {
  4787. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  4788. }
  4789. // Staging buffer required
  4790. vk_buffer& staging = ctx->device->sync_staging;
  4791. const uint64_t copy_size = ts*ne/bs;
  4792. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  4793. VkBufferCopy buf_copy{ 0, offset, copy_size };
  4794. ggml_vk_sync_buffers(ctx, subctx);
  4795. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  4796. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4797. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4798. // Find longest contiguous slice
  4799. if (ne1*nb1 == dstnb2) {
  4800. 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);
  4801. } else {
  4802. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4803. if (ne0*nb0/bs == dstnb1) {
  4804. 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);
  4805. } else {
  4806. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4807. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4808. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4809. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  4810. }
  4811. }
  4812. }
  4813. }
  4814. }
  4815. }
  4816. }
  4817. 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) {
  4818. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  4819. // Buffer is already mapped
  4820. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4821. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4822. GGML_ABORT("fatal error");
  4823. }
  4824. // Check if src is pinned memory
  4825. vk_buffer buf = nullptr;
  4826. size_t buf_offset = 0;
  4827. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  4828. if (buf != nullptr) {
  4829. // Memory is pinned, use as staging buffer
  4830. std::vector<vk::BufferCopy> slices(1);
  4831. if (width == spitch) {
  4832. // Only do single write if stride is equal
  4833. slices[0].srcOffset = buf_offset;
  4834. slices[0].dstOffset = offset;
  4835. slices[0].size = width * height;
  4836. } else {
  4837. slices.resize(height);
  4838. for (size_t i = 0; i < height; i++) {
  4839. slices[i].srcOffset = buf_offset + i * spitch;
  4840. slices[i].dstOffset = offset + i * width;
  4841. slices[i].size = width;
  4842. }
  4843. }
  4844. ggml_vk_sync_buffers(nullptr, subctx);
  4845. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  4846. return;
  4847. }
  4848. VK_LOG_DEBUG("STAGING");
  4849. if (!sync_staging) {
  4850. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  4851. }
  4852. // Staging buffer required
  4853. const size_t copy_size = width*height;
  4854. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  4855. vk_buffer& staging_buffer = dst->device->sync_staging;
  4856. VkBufferCopy buf_copy = {
  4857. 0,
  4858. offset,
  4859. copy_size};
  4860. ggml_vk_sync_buffers(nullptr, subctx);
  4861. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  4862. if (width == spitch) {
  4863. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  4864. } else {
  4865. for (size_t i = 0; i < height; i++) {
  4866. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  4867. }
  4868. }
  4869. }
  4870. 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) {
  4871. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  4872. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  4873. }
  4874. 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) {
  4875. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  4876. // Buffer is already mapped
  4877. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4878. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  4879. for (size_t i = 0; i < height; i++) {
  4880. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  4881. }
  4882. } else {
  4883. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  4884. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  4885. ggml_vk_ctx_begin(dst->device, subctx);
  4886. ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  4887. ggml_vk_ctx_end(subctx);
  4888. for (auto& cpy : subctx->in_memcpys) {
  4889. memcpy(cpy.dst, cpy.src, cpy.n);
  4890. }
  4891. for (auto& mset : subctx->memsets) {
  4892. memset(mset.dst, mset.val, mset.n);
  4893. }
  4894. ggml_vk_submit(subctx, dst->device->fence);
  4895. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  4896. dst->device->device.resetFences({ dst->device->fence });
  4897. ggml_vk_queue_command_pools_cleanup(dst->device);
  4898. }
  4899. }
  4900. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  4901. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  4902. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  4903. }
  4904. static void ggml_vk_buffer_read_2d_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t spitch, size_t dpitch, size_t width, size_t height, bool sync_staging = false) {
  4905. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  4906. GGML_ASSERT(width > 0);
  4907. GGML_ASSERT(height > 0);
  4908. GGML_ASSERT(src != nullptr);
  4909. // TODO: staging_offset is not used
  4910. // Check if dst is pinned memory
  4911. vk_buffer buf = nullptr;
  4912. size_t buf_offset = 0;
  4913. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  4914. std::vector<vk::BufferCopy> slices(1);
  4915. if (width == spitch && width == dpitch) {
  4916. // Only do single write if stride is equal
  4917. slices[0].srcOffset = offset;
  4918. slices[0].dstOffset = buf_offset;
  4919. slices[0].size = width * height;
  4920. } else {
  4921. slices.resize(height);
  4922. for (size_t i = 0; i < height; i++) {
  4923. slices[i].srcOffset = offset + i * spitch;
  4924. slices[i].dstOffset = buf_offset + i * dpitch;
  4925. slices[i].size = width;
  4926. }
  4927. }
  4928. if (buf != nullptr) {
  4929. // Memory is pinned, use as staging buffer
  4930. ggml_vk_sync_buffers(nullptr, subctx);
  4931. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  4932. return;
  4933. }
  4934. VK_LOG_DEBUG("STAGING");
  4935. if (!sync_staging) {
  4936. GGML_ABORT("Asynchronous read from non-pinned memory not supported");
  4937. }
  4938. // Fall back to staging buffer
  4939. const size_t copy_size = dpitch * height;
  4940. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  4941. vk_buffer& staging_buffer = src->device->sync_staging;
  4942. ggml_vk_sync_buffers(nullptr, subctx);
  4943. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  4944. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  4945. }
  4946. static void ggml_vk_buffer_read_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t size, bool sync_staging = false) {
  4947. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  4948. }
  4949. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  4950. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  4951. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  4952. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  4953. // the HW device to host copy path.
  4954. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  4955. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  4956. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  4957. } else {
  4958. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  4959. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  4960. ggml_vk_ctx_begin(src->device, subctx);
  4961. ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  4962. ggml_vk_ctx_end(subctx);
  4963. ggml_vk_submit(subctx, src->device->fence);
  4964. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  4965. src->device->device.resetFences({ src->device->fence });
  4966. ggml_vk_queue_command_pools_cleanup(src->device);
  4967. for (auto& cpy : subctx->out_memcpys) {
  4968. memcpy(cpy.dst, cpy.src, cpy.n);
  4969. }
  4970. }
  4971. }
  4972. 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) {
  4973. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  4974. // Make sure both buffers are on same device
  4975. GGML_ASSERT(src->device == dst->device);
  4976. VkBufferCopy bc{ src_offset, dst_offset, size };
  4977. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  4978. }
  4979. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  4980. if (src->device == dst->device) {
  4981. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  4982. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  4983. // Copy within the device
  4984. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  4985. ggml_vk_ctx_begin(src->device, subctx);
  4986. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  4987. ggml_vk_ctx_end(subctx);
  4988. ggml_vk_submit(subctx, src->device->fence);
  4989. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  4990. src->device->device.resetFences({ src->device->fence });
  4991. ggml_vk_queue_command_pools_cleanup(src->device);
  4992. } else {
  4993. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  4994. // Copy device to device
  4995. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  4996. // Copy to src staging buffer
  4997. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  4998. // Copy to dst buffer
  4999. ggml_vk_buffer_write_2d(dst, dst_offset, src->device->sync_staging->ptr, 0, size, 1);
  5000. }
  5001. }
  5002. static void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5003. VK_LOG_DEBUG("ggml_vk_buffer_memset_async(" << offset << ", " << c << ", " << size << ")");
  5004. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5005. dst->device->uma) {
  5006. deferred_memset((uint8_t*)dst->ptr + offset, c, size, &ctx->memsets);
  5007. return;
  5008. }
  5009. // Fall back to GPU fillBuffer for non-UMA or non-host-visible buffers
  5010. ctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5011. }
  5012. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5013. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  5014. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5015. dst->device->uma) {
  5016. memset((uint8_t*)dst->ptr + offset, c, size);
  5017. return;
  5018. }
  5019. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5020. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5021. ggml_vk_ctx_begin(dst->device, subctx);
  5022. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5023. ggml_vk_ctx_end(subctx);
  5024. ggml_vk_submit(subctx, dst->device->fence);
  5025. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  5026. dst->device->device.resetFences({ dst->device->fence });
  5027. ggml_vk_queue_command_pools_cleanup(dst->device);
  5028. }
  5029. 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) {
  5030. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ", " << disable_split_k << ")");
  5031. if (disable_split_k) {
  5032. return 1;
  5033. }
  5034. uint32_t split_k = 1;
  5035. if (ctx->device->shader_core_count != 0 && m >= pipeline->wg_denoms[0] && n >= pipeline->wg_denoms[1]) {
  5036. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  5037. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  5038. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  5039. if (k >= 2048) {
  5040. if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) {
  5041. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  5042. } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) {
  5043. split_k = 3;
  5044. }
  5045. // Cap the split at 8x. Unless k is huge this is a lot of overhead.
  5046. split_k = std::min(split_k, 8u);
  5047. // ggml_vk_matmul will align the splits to be a multiple of 256.
  5048. // If this rounded up size would cause the last split to be empty,
  5049. // then reduce the split count.
  5050. while (true) {
  5051. if (split_k == 1) {
  5052. break;
  5053. }
  5054. uint32_t k_split = CEIL_DIV(k, split_k);
  5055. k_split = ROUNDUP_POW2(k_split, 256);
  5056. if (k_split * (split_k - 1) < k) {
  5057. break;
  5058. }
  5059. split_k--;
  5060. }
  5061. }
  5062. }
  5063. return split_k;
  5064. }
  5065. 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) {
  5066. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5067. if (ctx->device->coopmat2) {
  5068. const uint32_t shader_core_count = ctx->device->shader_core_count;
  5069. const uint32_t tiles_l = CEIL_DIV(m, mmp->a_l->wg_denoms[0]) * CEIL_DIV(n, mmp->a_l->wg_denoms[1]);
  5070. const uint32_t tiles_m = CEIL_DIV(m, mmp->a_m->wg_denoms[0]) * CEIL_DIV(n, mmp->a_m->wg_denoms[1]);
  5071. // Use large shader when the N dimension is greater than the medium shader's tile size
  5072. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5073. // Prefer large over medium if either:
  5074. // - medium or large tiles would overfill the GPU
  5075. // - large tiles with a split_k==3 fits in the GPU and medium tiles with split_k==2 does not
  5076. // (medium with split_k==2 is probably better if it fits - more workgroups running and less split_k overhead)
  5077. bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count ||
  5078. // split_k==3 with large tiles likely better than medium tiles with no split_k.
  5079. (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2);
  5080. 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])) {
  5081. return aligned ? mmp->a_l : mmp->l;
  5082. }
  5083. // Use medium shader when the N dimension is greater than the small shader's tile size
  5084. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5085. if ((ctx->device->mul_mat_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_s[src0_type]) {
  5086. return aligned ? mmp->a_m : mmp->m;
  5087. }
  5088. return aligned ? mmp->a_s : mmp->s;
  5089. }
  5090. 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])) {
  5091. return aligned ? mmp->a_s : mmp->s;
  5092. }
  5093. if ((ctx->device->mul_mat_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l[src0_type]) {
  5094. return aligned ? mmp->a_m : mmp->m;
  5095. }
  5096. return aligned ? mmp->a_l : mmp->l;
  5097. GGML_UNUSED(src1_type);
  5098. }
  5099. 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) {
  5100. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5101. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, src0_type, src1_type)->align;
  5102. }
  5103. static void ggml_vk_matmul(
  5104. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5105. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  5106. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5107. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5108. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3,
  5109. uint32_t padded_n) {
  5110. 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 << ")");
  5111. if (split_k == 1) {
  5112. 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 };
  5113. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc, { m, n, batch });
  5114. return;
  5115. }
  5116. if (ctx->prealloc_split_k_need_sync) {
  5117. ggml_vk_sync_buffers(ctx, subctx);
  5118. }
  5119. GGML_ASSERT(batch_stride_d == m * n);
  5120. // Round the split size up to a multiple of 256 (k-quant alignment)
  5121. uint32_t k_split = CEIL_DIV(k, split_k);
  5122. k_split = ROUNDUP_POW2(k_split, 256);
  5123. 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 };
  5124. // Make sure enough workgroups get assigned for split k to work
  5125. 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 });
  5126. ggml_vk_sync_buffers(ctx, subctx);
  5127. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  5128. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 });
  5129. ctx->prealloc_split_k_need_sync = true;
  5130. }
  5131. 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) {
  5132. VK_LOG_DEBUG("ggml_vk_guess_matmul_id_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ")");
  5133. if (ctx->device->coopmat2) {
  5134. // Use large shader when the N dimension is greater than the medium shader's tile size
  5135. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5136. 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])) {
  5137. return aligned ? mmp->a_l : mmp->l;
  5138. }
  5139. // Use medium shader when the N dimension is greater than the small shader's tile size
  5140. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5141. if ((ctx->device->mul_mat_id_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_id_s[src0_type]) {
  5142. return aligned ? mmp->a_m : mmp->m;
  5143. }
  5144. return aligned ? mmp->a_s : mmp->s;
  5145. }
  5146. 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])) {
  5147. return aligned ? mmp->a_s : mmp->s;
  5148. }
  5149. if ((ctx->device->mul_mat_id_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l[src0_type]) {
  5150. return aligned ? mmp->a_m : mmp->m;
  5151. }
  5152. return aligned ? mmp->a_l : mmp->l;
  5153. }
  5154. 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) {
  5155. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ")");
  5156. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true, src0_type)->align;
  5157. }
  5158. static void ggml_vk_matmul_id(
  5159. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5160. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  5161. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5162. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5163. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11,
  5164. uint32_t padded_n) {
  5165. 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 << "), " <<
  5166. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  5167. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  5168. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  5169. 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,
  5170. nei0, nei1, nbi1, ne11, padded_n };
  5171. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, pc, { m, nei1, n_as });
  5172. }
  5173. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  5174. return
  5175. tensor->nb[0] == ggml_type_size(tensor->type) &&
  5176. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  5177. (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]);
  5178. }
  5179. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  5180. // Choose "contiguous copy" shader if src/dst are contiguous
  5181. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  5182. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  5183. if (contig) {
  5184. return ctx->device->pipeline_contig_cpy_f32_f32;
  5185. } else {
  5186. return ctx->device->pipeline_cpy_f32_f32;
  5187. }
  5188. }
  5189. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  5190. if (contig) {
  5191. return ctx->device->pipeline_contig_cpy_f32_f16;
  5192. } else {
  5193. return ctx->device->pipeline_cpy_f32_f16;
  5194. }
  5195. }
  5196. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  5197. if (contig) {
  5198. return ctx->device->pipeline_contig_cpy_f16_f16;
  5199. } else {
  5200. return ctx->device->pipeline_cpy_f16_f16;
  5201. }
  5202. }
  5203. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) {
  5204. if (contig) {
  5205. return ctx->device->pipeline_contig_cpy_f16_f32;
  5206. } else {
  5207. return ctx->device->pipeline_cpy_f16_f32;
  5208. }
  5209. }
  5210. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) {
  5211. if (contig) {
  5212. return ctx->device->pipeline_contig_cpy_f32_bf16;
  5213. } else {
  5214. return ctx->device->pipeline_cpy_f32_bf16;
  5215. }
  5216. }
  5217. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
  5218. if (contig) {
  5219. return ctx->device->pipeline_contig_cpy_f32_i32;
  5220. } else {
  5221. return ctx->device->pipeline_cpy_f32_i32;
  5222. }
  5223. }
  5224. if (src->type == GGML_TYPE_I32 && to == GGML_TYPE_F32) {
  5225. if (contig) {
  5226. return ctx->device->pipeline_contig_cpy_i32_f32;
  5227. } else {
  5228. return ctx->device->pipeline_cpy_i32_f32;
  5229. }
  5230. }
  5231. if (src->type == GGML_TYPE_F32) {
  5232. switch (to) {
  5233. case GGML_TYPE_Q4_0:
  5234. case GGML_TYPE_Q4_1:
  5235. case GGML_TYPE_Q5_0:
  5236. case GGML_TYPE_Q5_1:
  5237. case GGML_TYPE_Q8_0:
  5238. case GGML_TYPE_IQ4_NL:
  5239. return ctx->device->pipeline_cpy_f32_quant[to];
  5240. default:
  5241. break;
  5242. }
  5243. }
  5244. if (to == GGML_TYPE_F32) {
  5245. switch (src->type) {
  5246. case GGML_TYPE_Q4_0:
  5247. case GGML_TYPE_Q4_1:
  5248. case GGML_TYPE_Q5_0:
  5249. case GGML_TYPE_Q5_1:
  5250. case GGML_TYPE_Q8_0:
  5251. case GGML_TYPE_IQ4_NL:
  5252. return ctx->device->pipeline_cpy_quant_f32[src->type];
  5253. default:
  5254. break;
  5255. }
  5256. }
  5257. if (src->type == to) {
  5258. // Copy two or four bytes at a time, depending on block size.
  5259. // For quantized types, we scale by block size/type size. But
  5260. // this path is also used for bf16->bf16 for example, where the
  5261. // type size must be exactly 2 or 4.
  5262. GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4);
  5263. if ((ggml_type_size(src->type) % 4) == 0) {
  5264. if (contig) {
  5265. return ctx->device->pipeline_contig_cpy_f32_f32;
  5266. } else {
  5267. return ctx->device->pipeline_cpy_f32_f32;
  5268. }
  5269. } else {
  5270. if (contig) {
  5271. return ctx->device->pipeline_contig_cpy_f16_f16;
  5272. } else {
  5273. return ctx->device->pipeline_cpy_f16_f16;
  5274. }
  5275. }
  5276. }
  5277. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  5278. GGML_ABORT("fatal error");
  5279. }
  5280. static void ggml_vk_cpy_to_contiguous(ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline pipeline, const ggml_tensor * tensor, vk_subbuffer&& in, vk_subbuffer&& out) {
  5281. 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] << "), ";
  5282. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  5283. const int tensor_type_size = ggml_type_size(tensor->type);
  5284. const uint32_t ne = ggml_nelements(tensor);
  5285. std::array<uint32_t, 3> elements;
  5286. if (ne > 262144) {
  5287. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  5288. } else if (ne > 512) {
  5289. elements = { 512, CEIL_DIV(ne, 512), 1 };
  5290. } else {
  5291. elements = { ne, 1, 1 };
  5292. }
  5293. vk_op_unary_push_constants pc = {
  5294. (uint32_t)ne,
  5295. (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,
  5296. (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]),
  5297. 0,
  5298. 0.0f, 0.0f,
  5299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5300. };
  5301. init_pushconst_fastdiv(pc);
  5302. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements);
  5303. ggml_vk_sync_buffers(ctx, subctx);
  5304. }
  5305. static vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type, bool use_x4_blocks) {
  5306. switch(type) {
  5307. case GGML_TYPE_Q8_1:
  5308. return use_x4_blocks ? ctx->device->pipeline_quantize_q8_1_x4 : ctx->device->pipeline_quantize_q8_1;
  5309. default:
  5310. std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl;
  5311. GGML_ABORT("fatal error");
  5312. }
  5313. }
  5314. static void ggml_vk_quantize_q8_1(ggml_backend_vk_context * ctx, vk_context& subctx, vk_subbuffer&& in, vk_subbuffer&& out, uint32_t ne, bool use_x4_blocks = false) {
  5315. VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")");
  5316. vk_pipeline pipeline = use_x4_blocks ? ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true) : ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, false);
  5317. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, std::array<uint32_t, 1>{ne}, { ne, 1, 1 });
  5318. ggml_vk_sync_buffers(ctx, subctx);
  5319. }
  5320. 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, bool dryrun = false) {
  5321. 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];
  5322. 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];
  5323. 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];
  5324. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5325. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5326. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5327. const uint64_t ne00 = src0->ne[0];
  5328. const uint64_t ne01 = src0->ne[1];
  5329. const uint64_t ne02 = src0->ne[2];
  5330. const uint64_t ne03 = src0->ne[3];
  5331. const uint64_t ne10 = src1->ne[0];
  5332. const uint64_t ne11 = src1->ne[1];
  5333. const uint64_t ne12 = src1->ne[2];
  5334. const uint64_t ne13 = src1->ne[3];
  5335. const uint64_t ne21 = dst->ne[1];
  5336. const uint32_t stride_d = dst->nb[1] / ggml_type_size(dst->type);
  5337. const uint32_t stride_batch_d = stride_d*ne21;
  5338. const uint64_t r2 = ne12 / ne02;
  5339. const uint64_t r3 = ne13 / ne03;
  5340. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5341. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5342. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5343. vk_buffer d_Qx = nullptr;
  5344. size_t qx_buf_offset = 0;
  5345. vk_buffer d_Qy = nullptr;
  5346. size_t qy_buf_offset = 0;
  5347. bool src0_uma = false;
  5348. bool src1_uma = false;
  5349. if (ctx->device->uma) {
  5350. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5351. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5352. src0_uma = d_Qx != nullptr;
  5353. src1_uma = d_Qy != nullptr;
  5354. }
  5355. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5356. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5357. !ggml_vk_dim01_contiguous(src0);
  5358. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5359. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5360. !ggml_vk_dim01_contiguous(src1);
  5361. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5362. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5363. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5364. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0;
  5365. // Check for mmq first
  5366. 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;
  5367. if (mmp == nullptr) {
  5368. // Fall back to f16 dequant mul mat
  5369. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  5370. quantize_y = false;
  5371. }
  5372. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5373. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  5374. if (qx_needs_dequant) {
  5375. // Fall back to dequant + f16 mulmat
  5376. 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]);
  5377. }
  5378. // Not implemented
  5379. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5380. 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)));
  5381. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8;
  5382. 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));
  5383. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  5384. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11;
  5385. const int x_ne = ne01 * ne00;
  5386. const int y_ne = padded_n * ne10;
  5387. const int d_ne = ne11 * ne01;
  5388. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline);
  5389. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  5390. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5391. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  5392. const uint64_t y_sz = quantize_y ? (y_ne * 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);
  5393. const uint64_t d_sz = sizeof(float) * d_ne;
  5394. vk_pipeline to_fp16_vk_0 = nullptr;
  5395. vk_pipeline to_fp16_vk_1 = nullptr;
  5396. vk_pipeline to_q8_1 = nullptr;
  5397. if (x_non_contig) {
  5398. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  5399. } else {
  5400. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  5401. }
  5402. if (y_non_contig) {
  5403. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  5404. } else {
  5405. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5406. }
  5407. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5408. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5409. if (quantize_y) {
  5410. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true);
  5411. }
  5412. if (dryrun) {
  5413. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  5414. uint64_t y_sz_upd = y_sz * ne12 * ne13;
  5415. if (quantize_y) {
  5416. y_sz_upd = CEIL_DIV(y_sz_upd, 144) * 144;
  5417. }
  5418. const uint64_t split_k_size = split_k > 1 ? d_sz * ne12 * ne13 * split_k : 0;
  5419. if (
  5420. (qx_needs_dequant && x_sz_upd > ctx->device->properties.limits.maxStorageBufferRange) ||
  5421. (qy_needs_dequant && y_sz_upd > ctx->device->properties.limits.maxStorageBufferRange) ||
  5422. (split_k > 1 && split_k_size > ctx->device->properties.limits.maxStorageBufferRange)) {
  5423. GGML_ABORT("Requested preallocation size is too large");
  5424. }
  5425. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  5426. ctx->prealloc_size_x = x_sz_upd;
  5427. }
  5428. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz_upd) {
  5429. ctx->prealloc_size_y = y_sz_upd;
  5430. }
  5431. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  5432. ctx->prealloc_size_split_k = split_k_size;
  5433. }
  5434. // Request descriptor sets
  5435. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  5436. if (qx_needs_dequant) {
  5437. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5438. }
  5439. if (qy_needs_dequant) {
  5440. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5441. }
  5442. if (quantize_y) {
  5443. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5444. }
  5445. if (split_k > 1) {
  5446. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  5447. }
  5448. return;
  5449. }
  5450. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5451. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5452. GGML_ASSERT(d_D != nullptr);
  5453. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz * ne02 * ne03);
  5454. vk_buffer d_X;
  5455. uint64_t x_buf_offset = 0;
  5456. vk_buffer d_Y;
  5457. uint64_t y_buf_offset = 0;
  5458. if (!src0_uma) {
  5459. d_Qx = src0_buf_ctx->dev_buffer;
  5460. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5461. GGML_ASSERT(d_Qx != nullptr);
  5462. }
  5463. if (!src1_uma) {
  5464. d_Qy = src1_buf_ctx->dev_buffer;
  5465. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5466. GGML_ASSERT(d_Qy != nullptr);
  5467. }
  5468. if (qx_needs_dequant) {
  5469. d_X = ctx->prealloc_x;
  5470. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  5471. } else {
  5472. d_X = d_Qx;
  5473. x_buf_offset = qx_buf_offset;
  5474. GGML_ASSERT(qx_sz == x_sz);
  5475. }
  5476. if (qy_needs_dequant) {
  5477. d_Y = ctx->prealloc_y;
  5478. GGML_ASSERT(d_Y->size >= y_sz * ne12 * ne13);
  5479. } else if (quantize_y) {
  5480. d_Y = ctx->prealloc_y;
  5481. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz * ne12 * ne13, 144) * 144);
  5482. } else {
  5483. d_Y = d_Qy;
  5484. y_buf_offset = qy_buf_offset;
  5485. GGML_ASSERT(qy_sz == y_sz);
  5486. }
  5487. if (x_non_contig || qx_needs_dequant) {
  5488. if (ctx->prealloc_x_need_sync) {
  5489. ggml_vk_sync_buffers(ctx, subctx);
  5490. }
  5491. }
  5492. if (x_non_contig) {
  5493. 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));
  5494. } else if (qx_needs_dequant) {
  5495. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  5496. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, vk_subbuffer{ d_X, 0, x_sz * ne02 * ne03 } }, pc, { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  5497. ggml_vk_sync_buffers(ctx, subctx);
  5498. }
  5499. if (y_non_contig) {
  5500. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5501. ctx->prealloc_y_last_tensor_used != src1) {
  5502. if (ctx->prealloc_y_need_sync) {
  5503. ggml_vk_sync_buffers(ctx, subctx);
  5504. }
  5505. 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));
  5506. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5507. ctx->prealloc_y_last_tensor_used = src1;
  5508. }
  5509. }
  5510. if (quantize_y) {
  5511. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5512. ctx->prealloc_y_last_tensor_used != src1) {
  5513. if (ctx->prealloc_y_need_sync) {
  5514. ggml_vk_sync_buffers(ctx, subctx);
  5515. }
  5516. 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 * ne12 * ne13, true);
  5517. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5518. ctx->prealloc_y_last_tensor_used = src1;
  5519. }
  5520. }
  5521. uint32_t stride_batch_x = ne00*ne01;
  5522. uint32_t stride_batch_y = ne10*ne11;
  5523. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5524. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5525. }
  5526. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  5527. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5528. }
  5529. uint32_t y_sz_total = y_sz * ne12 * ne13;
  5530. if (quantize_y) {
  5531. y_sz_total = CEIL_DIV(y_sz_total, 144) * 144;
  5532. }
  5533. // compute
  5534. ggml_vk_matmul(
  5535. ctx, subctx, pipeline,
  5536. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz_total },
  5537. ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, d_sz * ne12 * ne13 * split_k },
  5538. ne01, ne11, ne10,
  5539. ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d,
  5540. split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n
  5541. ); // NOLINT
  5542. if (x_non_contig || qx_needs_dequant) {
  5543. ctx->prealloc_x_need_sync = true;
  5544. }
  5545. if (y_non_contig || quantize_y) {
  5546. ctx->prealloc_y_need_sync = true;
  5547. }
  5548. }
  5549. // Device tuning
  5550. static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_t n, uint32_t k, ggml_type src0_type) {
  5551. if (device->mmvq_mode == 1) {
  5552. return true;
  5553. } else if (device->mmvq_mode == -1) {
  5554. return false;
  5555. }
  5556. // MMVQ is generally good for batches
  5557. if (n > 1) {
  5558. return true;
  5559. }
  5560. switch (device->vendor_id) {
  5561. case VK_VENDOR_ID_NVIDIA:
  5562. switch (src0_type) {
  5563. case GGML_TYPE_Q8_0:
  5564. return device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  5565. default:
  5566. return true;
  5567. }
  5568. case VK_VENDOR_ID_AMD:
  5569. switch (src0_type) {
  5570. case GGML_TYPE_Q8_0:
  5571. return device->architecture == vk_device_architecture::AMD_GCN;
  5572. default:
  5573. return true;
  5574. }
  5575. case VK_VENDOR_ID_INTEL:
  5576. switch (src0_type) {
  5577. // From tests on A770 Linux, may need more tuning
  5578. case GGML_TYPE_Q4_0:
  5579. case GGML_TYPE_Q5_1:
  5580. return false;
  5581. default:
  5582. return true;
  5583. }
  5584. default:
  5585. return true;
  5586. }
  5587. GGML_UNUSED(m);
  5588. GGML_UNUSED(k);
  5589. }
  5590. static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  5591. 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];
  5592. 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];
  5593. 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];
  5594. std::cerr << "), " << (dryrun ? "dryrun" : "") << "),)");
  5595. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5596. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5597. const uint64_t ne00 = src0->ne[0];
  5598. const uint64_t ne01 = src0->ne[1];
  5599. const uint64_t ne02 = src0->ne[2];
  5600. const uint64_t ne03 = src0->ne[3];
  5601. const uint64_t ne10 = src1->ne[0];
  5602. const uint64_t ne11 = src1->ne[1];
  5603. const uint64_t ne12 = src1->ne[2];
  5604. const uint64_t ne13 = src1->ne[3];
  5605. const uint64_t ne20 = dst->ne[0];
  5606. const uint64_t ne21 = dst->ne[1];
  5607. const uint64_t ne22 = dst->ne[2];
  5608. const uint64_t ne23 = dst->ne[3];
  5609. const uint64_t r2 = ne12 / ne02;
  5610. const uint64_t r3 = ne13 / ne03;
  5611. // batch_n indicates that we need to compute a few vector results, and this assumes
  5612. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  5613. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  5614. bool batch_n = ne11 > 1;
  5615. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5616. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5617. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5618. vk_buffer d_Qx = nullptr;
  5619. size_t qx_buf_offset = 0;
  5620. vk_buffer d_Qy = nullptr;
  5621. size_t qy_buf_offset = 0;
  5622. bool src0_uma = false;
  5623. bool src1_uma = false;
  5624. if (ctx->device->uma) {
  5625. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5626. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5627. src0_uma = d_Qx != nullptr;
  5628. src1_uma = d_Qy != nullptr;
  5629. }
  5630. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  5631. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  5632. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  5633. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0 && ggml_vk_should_use_mmvq(ctx->device, ne01, ne11, ne10, src0->type);
  5634. vk_pipeline to_fp16_vk_0 = nullptr;
  5635. vk_pipeline to_fp16_vk_1 = nullptr;
  5636. if (x_non_contig) {
  5637. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  5638. }
  5639. if (y_non_contig) {
  5640. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  5641. } else {
  5642. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5643. }
  5644. // Check for mmq first
  5645. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr;
  5646. vk_pipeline to_q8_1 = nullptr;
  5647. if (dmmv == nullptr) {
  5648. // Fall back to f16 dequant mul mat
  5649. dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11, ne20, ne00);
  5650. quantize_y = false;
  5651. }
  5652. if (quantize_y) {
  5653. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true);
  5654. }
  5655. const bool qx_needs_dequant = x_non_contig;
  5656. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  5657. // Not implemented
  5658. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5659. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5660. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5661. GGML_ASSERT(dmmv != nullptr);
  5662. const uint64_t x_ne = ne01 * ne00;
  5663. const uint64_t y_ne = ne11 * ne10;
  5664. const uint64_t d_ne = ne11 * ne01;
  5665. 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);
  5666. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5667. 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;
  5668. const uint64_t y_sz = quantize_y ? (y_ne * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  5669. const uint64_t d_sz = sizeof(float) * d_ne;
  5670. if (dryrun) {
  5671. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  5672. uint64_t y_sz_upd = y_sz * ne12 * ne13;
  5673. if (quantize_y) {
  5674. y_sz_upd = CEIL_DIV(y_sz_upd, 144) * 144;
  5675. }
  5676. if (
  5677. (qx_needs_dequant && x_sz_upd > ctx->device->properties.limits.maxStorageBufferRange) ||
  5678. (qy_needs_dequant && y_sz_upd > ctx->device->properties.limits.maxStorageBufferRange)) {
  5679. GGML_ABORT("Requested preallocation size is too large");
  5680. }
  5681. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  5682. ctx->prealloc_size_x = x_sz_upd;
  5683. }
  5684. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz_upd) {
  5685. ctx->prealloc_size_y = y_sz_upd;
  5686. }
  5687. // Request descriptor sets
  5688. if (qx_needs_dequant) {
  5689. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5690. }
  5691. if (qy_needs_dequant) {
  5692. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5693. }
  5694. if (quantize_y) {
  5695. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5696. }
  5697. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  5698. return;
  5699. }
  5700. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5701. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5702. GGML_ASSERT(d_D != nullptr);
  5703. vk_buffer d_X;
  5704. uint64_t x_buf_offset = 0;
  5705. vk_buffer d_Y;
  5706. uint64_t y_buf_offset = 0;
  5707. if(!src0_uma) {
  5708. d_Qx = src0_buf_ctx->dev_buffer;
  5709. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5710. GGML_ASSERT(d_Qx != nullptr);
  5711. }
  5712. if(!src1_uma) {
  5713. d_Qy = src1_buf_ctx->dev_buffer;
  5714. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5715. GGML_ASSERT(d_Qy != nullptr);
  5716. }
  5717. if (qx_needs_dequant) {
  5718. d_X = ctx->prealloc_x;
  5719. } else {
  5720. d_X = d_Qx;
  5721. x_buf_offset = qx_buf_offset;
  5722. GGML_ASSERT(qx_sz == x_sz);
  5723. }
  5724. if (qy_needs_dequant) {
  5725. d_Y = ctx->prealloc_y;
  5726. } else if (quantize_y) {
  5727. d_Y = ctx->prealloc_y;
  5728. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz * ne12 * ne13, 144) * 144);
  5729. } else {
  5730. d_Y = d_Qy;
  5731. y_buf_offset = qy_buf_offset;
  5732. GGML_ASSERT(qy_sz == y_sz);
  5733. }
  5734. if (x_non_contig) {
  5735. if (ctx->prealloc_x_need_sync) {
  5736. ggml_vk_sync_buffers(ctx, subctx);
  5737. }
  5738. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  5739. 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));
  5740. }
  5741. if (y_non_contig) {
  5742. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  5743. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5744. ctx->prealloc_y_last_tensor_used != src1) {
  5745. if (ctx->prealloc_y_need_sync) {
  5746. ggml_vk_sync_buffers(ctx, subctx);
  5747. }
  5748. 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));
  5749. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5750. ctx->prealloc_y_last_tensor_used = src1;
  5751. }
  5752. }
  5753. if (quantize_y) {
  5754. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5755. ctx->prealloc_y_last_tensor_used != src1) {
  5756. if (ctx->prealloc_y_need_sync) {
  5757. ggml_vk_sync_buffers(ctx, subctx);
  5758. }
  5759. 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 * ne12 * ne13, true);
  5760. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5761. ctx->prealloc_y_last_tensor_used = src1;
  5762. }
  5763. }
  5764. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  5765. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  5766. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  5767. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  5768. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5769. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5770. }
  5771. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  5772. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5773. }
  5774. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  5775. uint32_t groups_x = ne01;
  5776. uint32_t groups_z = 1;
  5777. if (ne01 > max_groups_x) {
  5778. groups_z = 64;
  5779. groups_x = CEIL_DIV(groups_x, groups_z);
  5780. }
  5781. // TODO: Clean up this whole sz * ne_2 * ne_3 thing, it hasn't been necessary for a long time
  5782. uint32_t y_sz_total = y_sz * ne12 * ne13;
  5783. if (quantize_y) {
  5784. y_sz_total = CEIL_DIV(y_sz_total, 144) * 144;
  5785. }
  5786. // compute
  5787. const vk_mat_vec_push_constants pc = {
  5788. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  5789. stride_batch_x, stride_batch_y, stride_batch_d,
  5790. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  5791. };
  5792. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  5793. { vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 }, vk_subbuffer{ d_Y, y_buf_offset, y_sz_total }, vk_subbuffer{ d_D, d_buf_offset, d_sz * ne22 * ne23} },
  5794. pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  5795. if (x_non_contig) {
  5796. ctx->prealloc_x_need_sync = true;
  5797. }
  5798. if (y_non_contig || quantize_y) {
  5799. ctx->prealloc_y_need_sync = true;
  5800. }
  5801. }
  5802. static void ggml_vk_mul_mat_vec_p021_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  5803. 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];
  5804. 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];
  5805. 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];
  5806. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5807. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  5808. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  5809. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  5810. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  5811. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  5812. const uint64_t ne00 = src0->ne[0];
  5813. const uint64_t ne01 = src0->ne[1];
  5814. const uint64_t ne02 = src0->ne[2];
  5815. // const uint64_t ne03 = src0->ne[3];
  5816. const uint64_t ne10 = src1->ne[0];
  5817. const uint64_t ne11 = src1->ne[1];
  5818. const uint64_t ne12 = src1->ne[2];
  5819. // const uint64_t ne13 = src1->ne[3];
  5820. GGML_ASSERT(ne11 == 1);
  5821. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5822. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5823. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5824. vk_buffer d_Qy = nullptr;
  5825. size_t qy_buf_offset = 0;
  5826. bool src1_uma = false;
  5827. if (ctx->device->uma) {
  5828. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5829. src1_uma = d_Qy != nullptr;
  5830. }
  5831. const uint64_t x_ne = ne00 * ne01 * ne02;
  5832. const uint64_t y_ne = ne10 * ne11 * ne12;
  5833. const uint64_t d_ne = ne01 * ne11 * ne12;
  5834. 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);
  5835. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5836. const uint64_t d_sz = sizeof(float) * d_ne;
  5837. // With grouped query attention there are > 1 Q matrices per K, V matrix.
  5838. uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02;
  5839. if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) {
  5840. gqa_ratio = 1;
  5841. }
  5842. if (dryrun) {
  5843. // Request descriptor sets
  5844. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], 1);
  5845. return;
  5846. }
  5847. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5848. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5849. GGML_ASSERT(d_D != nullptr);
  5850. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  5851. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5852. GGML_ASSERT(d_Qx != nullptr);
  5853. if (!src1_uma) {
  5854. d_Qy = src1_buf_ctx->dev_buffer;
  5855. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5856. GGML_ASSERT(d_Qx != nullptr);
  5857. }
  5858. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5859. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  5860. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5861. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  5862. // compute
  5863. const std::array<uint32_t, 6> pc = { (uint32_t)ne00, (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne12, (uint32_t)(qy_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type)) };
  5864. uint32_t workgroups_z = (uint32_t)ne12;
  5865. // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups
  5866. if (gqa_ratio > 1) {
  5867. workgroups_z /= gqa_ratio;
  5868. }
  5869. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset }, vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset } }, pc, { 1, (uint32_t)ne01, workgroups_z });
  5870. }
  5871. static void ggml_vk_mul_mat_vec_nc_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  5872. 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];
  5873. 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];
  5874. 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];
  5875. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5876. GGML_ASSERT(!ggml_is_transposed(src0));
  5877. GGML_ASSERT(!ggml_is_transposed(src1));
  5878. GGML_ASSERT(!ggml_is_permuted(src0));
  5879. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  5880. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  5881. const uint64_t ne00 = src0->ne[0];
  5882. const uint64_t ne01 = src0->ne[1];
  5883. const uint64_t ne02 = src0->ne[2];
  5884. const uint64_t ne03 = src0->ne[3];
  5885. const uint64_t nb01 = src0->nb[1];
  5886. const uint64_t nb02 = src0->nb[2];
  5887. const uint64_t nb12 = src1->nb[2];
  5888. // const uint64_t ne10 = src1->ne[0];
  5889. const uint64_t ne11 = src1->ne[1];
  5890. const uint64_t ne12 = src1->ne[2];
  5891. // const uint64_t ne13 = src1->ne[3];
  5892. const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t));
  5893. const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float));
  5894. const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float));
  5895. GGML_ASSERT(ne11 == 1);
  5896. GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in supports_op
  5897. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5898. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5899. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5900. vk_buffer d_Qy = nullptr;
  5901. size_t qy_buf_offset = 0;
  5902. bool src1_uma = false;
  5903. if (ctx->device->uma) {
  5904. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5905. src1_uma = d_Qy != nullptr;
  5906. }
  5907. const uint64_t d_ne = ne01 * ne11 * ne12 * ne03;
  5908. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  5909. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  5910. const uint32_t channel_stride_y = nb12 / sizeof(float);
  5911. const uint64_t qx_sz = ggml_nbytes(src0);
  5912. const uint64_t qy_sz = ggml_nbytes(src1);
  5913. const uint64_t d_sz = sizeof(float) * d_ne;
  5914. if (dryrun) {
  5915. // Request descriptor sets
  5916. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  5917. return;
  5918. }
  5919. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5920. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5921. GGML_ASSERT(d_D != nullptr);
  5922. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  5923. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5924. GGML_ASSERT(d_Qx != nullptr);
  5925. if (!src1_uma) {
  5926. d_Qy = src1_buf_ctx->dev_buffer;
  5927. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5928. GGML_ASSERT(d_Qx != nullptr);
  5929. }
  5930. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5931. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  5932. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5933. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  5934. // compute
  5935. const std::array<uint32_t, 12> pc = { (uint32_t)ne00, (uint32_t)ne01, row_stride_x, channel_stride_x, channel_stride_y, (uint32_t)(ne12 / ne02), (uint32_t)ne12, (uint32_t)(qy_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type)), nb03, nb13, nb23 };
  5936. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  5937. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset }, vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset } }, pc, { (uint32_t)ne03, (uint32_t)ne01, (uint32_t)ne12 });
  5938. }
  5939. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * src0, ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  5940. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  5941. // Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases
  5942. // where the M dimension is very large.
  5943. // Split_k doesn't work with M splitting.
  5944. const size_t nbytes = ggml_nbytes(src0);
  5945. const bool needs_split = nbytes > ctx->device->properties.limits.maxStorageBufferRange;
  5946. if (needs_split) {
  5947. // Choose the number of rows that can fit (and divide by two, to allow for any additional offsets)
  5948. const uint32_t M_split = ctx->device->properties.limits.maxStorageBufferRange / (2 * src0->nb[1]);
  5949. uint32_t m_offset = 0;
  5950. while (m_offset < dst->ne[0]) {
  5951. const uint32_t cur_M_size = std::min(M_split, (uint32_t)(dst->ne[0] - m_offset));
  5952. ggml_tensor dst2 = *dst;
  5953. ggml_tensor src02 = *src0;
  5954. dst2.view_src = dst->view_src ? dst->view_src : dst;
  5955. src02.view_src = src0->view_src ? src0->view_src : src0;
  5956. dst2.view_offs += m_offset * dst->nb[0];
  5957. src02.view_offs += m_offset * src0->nb[1];
  5958. dst2.ne[0] = cur_M_size;
  5959. src02.ne[1] = cur_M_size;
  5960. ggml_vk_mul_mat_q_f16(ctx, subctx, &src02, src1, &dst2, true, dryrun);
  5961. m_offset += cur_M_size;
  5962. }
  5963. } else if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  5964. // detect 0213 permutation, and batch size of 1
  5965. src0->nb[0] <= src0->nb[2] &&
  5966. src0->nb[2] <= src0->nb[1] &&
  5967. src0->nb[1] <= src0->nb[3] &&
  5968. src1->nb[0] <= src1->nb[2] &&
  5969. src1->nb[2] <= src1->nb[1] &&
  5970. src1->nb[1] <= src1->nb[3] &&
  5971. src0->ne[3] == 1 &&
  5972. src1->ne[3] == 1) {
  5973. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  5974. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  5975. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  5976. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  5977. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  5978. // when ne12 and ne13 are one.
  5979. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  5980. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
  5981. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, src0, src1, dst, dryrun);
  5982. } else {
  5983. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false, dryrun);
  5984. }
  5985. }
  5986. 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, bool dryrun = false) {
  5987. 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];
  5988. 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];
  5989. 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];
  5990. 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] << "),)");
  5991. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5992. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  5993. const uint64_t ne00 = src0->ne[0];
  5994. const uint64_t ne01 = src0->ne[1];
  5995. const uint64_t ne02 = src0->ne[2];
  5996. const uint64_t ne03 = src0->ne[3];
  5997. const uint64_t ne10 = src1->ne[0];
  5998. const uint64_t ne11 = src1->ne[1];
  5999. const uint64_t ne12 = src1->ne[2];
  6000. const uint64_t ne13 = src1->ne[3];
  6001. const uint64_t nei0 = ids->ne[0];
  6002. const uint64_t nei1 = ids->ne[1];
  6003. const uint32_t nbi1 = ids->nb[1];
  6004. const uint32_t nbi2 = ids->nb[2];
  6005. const uint64_t ne20 = dst->ne[0];
  6006. const uint64_t ne21 = dst->ne[1];
  6007. const uint64_t ne22 = dst->ne[2];
  6008. const uint64_t ne23 = dst->ne[3];
  6009. const uint64_t n_as = ne02;
  6010. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6011. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6012. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6013. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6014. vk_buffer d_Qx = nullptr;
  6015. size_t qx_buf_offset = 0;
  6016. vk_buffer d_Qy = nullptr;
  6017. size_t qy_buf_offset = 0;
  6018. vk_buffer d_ids = nullptr;
  6019. size_t ids_buf_offset = 0;
  6020. bool src0_uma = false;
  6021. bool src1_uma = false;
  6022. bool ids_uma = false;
  6023. if (ctx->device->uma) {
  6024. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6025. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6026. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6027. src0_uma = d_Qx != nullptr;
  6028. src1_uma = d_Qy != nullptr;
  6029. ids_uma = d_ids != nullptr;
  6030. }
  6031. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  6032. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  6033. !ggml_vk_dim01_contiguous(src0);
  6034. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  6035. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  6036. !ggml_vk_dim01_contiguous(src1);
  6037. // If src0 is BF16, try to use a BF16 x BF16 multiply
  6038. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  6039. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  6040. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0;
  6041. // Check for mmq first
  6042. 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;
  6043. if (mmp == nullptr) {
  6044. // Fall back to f16 dequant mul mat
  6045. 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]);
  6046. quantize_y = false;
  6047. }
  6048. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  6049. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  6050. if (qx_needs_dequant) {
  6051. // Fall back to dequant + f16 mulmat
  6052. 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]);
  6053. }
  6054. // Not implemented
  6055. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6056. 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));
  6057. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && nei1 > 8;
  6058. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned, qx_needs_dequant ? f16_type : src0->type);
  6059. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  6060. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) :ne11;
  6061. const uint64_t x_ne = ne01 * ne00;
  6062. const uint64_t y_ne = padded_n * ne10;
  6063. const uint64_t d_ne = ne21 * ne20;
  6064. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  6065. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6066. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  6067. const uint64_t y_sz = quantize_y ? (y_ne * 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);
  6068. const uint64_t ids_sz = nbi2;
  6069. const uint64_t d_sz = sizeof(float) * d_ne;
  6070. vk_pipeline to_fp16_vk_0 = nullptr;
  6071. vk_pipeline to_fp16_vk_1 = nullptr;
  6072. vk_pipeline to_q8_1 = nullptr;
  6073. if (x_non_contig) {
  6074. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  6075. } else {
  6076. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  6077. }
  6078. if (y_non_contig) {
  6079. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  6080. } else {
  6081. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6082. }
  6083. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6084. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6085. if (quantize_y) {
  6086. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true);
  6087. }
  6088. if (dryrun) {
  6089. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  6090. uint64_t y_sz_upd = y_sz * ne12 * ne13;
  6091. if (quantize_y) {
  6092. y_sz_upd = CEIL_DIV(y_sz_upd, 144) * 144;
  6093. }
  6094. if (
  6095. (qx_needs_dequant && x_sz_upd > ctx->device->properties.limits.maxStorageBufferRange) ||
  6096. (qy_needs_dequant && y_sz_upd > ctx->device->properties.limits.maxStorageBufferRange)) {
  6097. GGML_ABORT("Requested preallocation size is too large");
  6098. }
  6099. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  6100. ctx->prealloc_size_x = x_sz_upd;
  6101. }
  6102. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz_upd) {
  6103. ctx->prealloc_size_y = y_sz_upd;
  6104. }
  6105. // Request descriptor sets
  6106. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6107. if (qx_needs_dequant) {
  6108. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6109. }
  6110. if (qy_needs_dequant) {
  6111. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6112. }
  6113. if (quantize_y) {
  6114. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6115. }
  6116. return;
  6117. }
  6118. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6119. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6120. GGML_ASSERT(d_D != nullptr);
  6121. vk_buffer d_X;
  6122. uint64_t x_buf_offset = 0;
  6123. vk_buffer d_Y;
  6124. uint64_t y_buf_offset = 0;
  6125. if (!src0_uma) {
  6126. d_Qx = src0_buf_ctx->dev_buffer;
  6127. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6128. GGML_ASSERT(d_Qx != nullptr);
  6129. }
  6130. if (!src1_uma) {
  6131. d_Qy = src1_buf_ctx->dev_buffer;
  6132. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6133. GGML_ASSERT(d_Qy != nullptr);
  6134. }
  6135. if (!ids_uma) {
  6136. d_ids = ids_buf_ctx->dev_buffer;
  6137. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6138. GGML_ASSERT(d_ids != nullptr);
  6139. }
  6140. if (qx_needs_dequant) {
  6141. d_X = ctx->prealloc_x;
  6142. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  6143. } else {
  6144. d_X = d_Qx;
  6145. x_buf_offset = qx_buf_offset;
  6146. GGML_ASSERT(qx_sz == x_sz);
  6147. }
  6148. if (qy_needs_dequant) {
  6149. d_Y = ctx->prealloc_y;
  6150. GGML_ASSERT(d_Y->size >= y_sz * ne12 * ne13);
  6151. } else if (quantize_y) {
  6152. d_Y = ctx->prealloc_y;
  6153. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz * ne12 * ne13, 144) * 144);
  6154. } else {
  6155. d_Y = d_Qy;
  6156. y_buf_offset = qy_buf_offset;
  6157. GGML_ASSERT(qy_sz == y_sz);
  6158. }
  6159. if (x_non_contig || qx_needs_dequant) {
  6160. if (ctx->prealloc_x_need_sync) {
  6161. ggml_vk_sync_buffers(ctx, subctx);
  6162. }
  6163. }
  6164. if (x_non_contig) {
  6165. 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));
  6166. } else if (qx_needs_dequant) {
  6167. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6168. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  6169. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, vk_subbuffer{ d_X, 0, x_sz * ne02 * ne03 } }, pc, { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  6170. ggml_vk_sync_buffers(ctx, subctx);
  6171. }
  6172. if (y_non_contig) {
  6173. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6174. ctx->prealloc_y_last_tensor_used != src1) {
  6175. if (ctx->prealloc_y_need_sync) {
  6176. ggml_vk_sync_buffers(ctx, subctx);
  6177. }
  6178. 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));
  6179. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6180. ctx->prealloc_y_last_tensor_used = src1;
  6181. }
  6182. }
  6183. if (quantize_y) {
  6184. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6185. ctx->prealloc_y_last_tensor_used != src1) {
  6186. if (ctx->prealloc_y_need_sync) {
  6187. ggml_vk_sync_buffers(ctx, subctx);
  6188. }
  6189. 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 * ne12 * ne13, true);
  6190. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6191. ctx->prealloc_y_last_tensor_used = src1;
  6192. }
  6193. }
  6194. uint32_t stride_batch_x = ne00*ne01;
  6195. uint32_t stride_batch_y = ne10*ne11;
  6196. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6197. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6198. }
  6199. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  6200. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6201. }
  6202. uint32_t y_sz_total = y_sz * ne12 * ne13;
  6203. if (quantize_y) {
  6204. y_sz_total = CEIL_DIV(y_sz_total, 144) * 144;
  6205. }
  6206. // compute
  6207. ggml_vk_matmul_id(
  6208. ctx, subctx, pipeline,
  6209. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz_total },
  6210. { d_D, d_buf_offset, d_sz * ne22 * ne23 }, { d_ids, ids_buf_offset, ids_sz },
  6211. ne01, ne21, ne10, ne10, ne10, ne01,
  6212. stride_batch_x, stride_batch_y, ne20*ne21,
  6213. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, padded_n
  6214. ); // NOLINT
  6215. if (x_non_contig || qx_needs_dequant) {
  6216. ctx->prealloc_x_need_sync = true;
  6217. }
  6218. if (y_non_contig) {
  6219. ctx->prealloc_y_need_sync = true;
  6220. }
  6221. }
  6222. static void ggml_vk_mul_mat_vec_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, bool dryrun = false) {
  6223. 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];
  6224. 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];
  6225. 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];
  6226. 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];
  6227. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  6228. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6229. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6230. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6231. const uint64_t ne00 = src0->ne[0];
  6232. const uint64_t ne01 = src0->ne[1];
  6233. const uint64_t ne02 = src0->ne[2];
  6234. const uint64_t ne03 = src0->ne[3];
  6235. const uint64_t ne10 = src1->ne[0];
  6236. const uint64_t ne11 = src1->ne[1];
  6237. const uint64_t ne12 = src1->ne[2];
  6238. const uint64_t ne13 = src1->ne[3];
  6239. const uint64_t nei0 = ids->ne[0];
  6240. const uint64_t nei1 = ids->ne[1];
  6241. const uint64_t nbi2 = ids->nb[2];
  6242. GGML_ASSERT(nei1 == 1);
  6243. const uint64_t ne20 = dst->ne[0];
  6244. const uint64_t ne21 = dst->ne[1];
  6245. const uint64_t ne22 = dst->ne[2];
  6246. const uint64_t ne23 = dst->ne[3];
  6247. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6248. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6249. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6250. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6251. vk_buffer d_Qx = nullptr;
  6252. size_t qx_buf_offset = 0;
  6253. vk_buffer d_Qy = nullptr;
  6254. size_t qy_buf_offset = 0;
  6255. vk_buffer d_ids = nullptr;
  6256. size_t ids_buf_offset = 0;
  6257. bool src0_uma = false;
  6258. bool src1_uma = false;
  6259. bool ids_uma = false;
  6260. if (ctx->device->uma) {
  6261. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6262. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6263. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6264. src0_uma = d_Qx != nullptr;
  6265. src1_uma = d_Qy != nullptr;
  6266. ids_uma = d_ids != nullptr;
  6267. }
  6268. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6269. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6270. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6271. const bool qx_needs_dequant = x_non_contig;
  6272. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  6273. // Not implemented
  6274. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6275. const uint64_t x_ne = ne01 * ne00;
  6276. const uint64_t y_ne = ne11 * ne10;
  6277. const uint64_t d_ne = ne21 * ne20;
  6278. 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);
  6279. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6280. 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;
  6281. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  6282. const uint64_t ids_sz = nbi2;
  6283. const uint64_t d_sz = sizeof(float) * d_ne;
  6284. vk_pipeline to_fp16_vk_0 = nullptr;
  6285. vk_pipeline to_fp16_vk_1 = nullptr;
  6286. if (x_non_contig) {
  6287. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6288. }
  6289. if (y_non_contig) {
  6290. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6291. } else {
  6292. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6293. }
  6294. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type);
  6295. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6296. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6297. GGML_ASSERT(dmmv != nullptr);
  6298. if (dryrun) {
  6299. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  6300. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  6301. if (
  6302. (qx_needs_dequant && x_sz_upd > ctx->device->properties.limits.maxStorageBufferRange) ||
  6303. (qy_needs_dequant && y_sz_upd > ctx->device->properties.limits.maxStorageBufferRange)) {
  6304. GGML_ABORT("Requested preallocation size is too large");
  6305. }
  6306. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  6307. ctx->prealloc_size_x = x_sz_upd;
  6308. }
  6309. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  6310. ctx->prealloc_size_y = y_sz_upd;
  6311. }
  6312. // Request descriptor sets
  6313. if (qx_needs_dequant) {
  6314. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6315. }
  6316. if (qy_needs_dequant) {
  6317. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6318. }
  6319. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6320. return;
  6321. }
  6322. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6323. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6324. GGML_ASSERT(d_D != nullptr);
  6325. vk_buffer d_X;
  6326. uint64_t x_buf_offset = 0;
  6327. vk_buffer d_Y;
  6328. uint64_t y_buf_offset = 0;
  6329. if(!src0_uma) {
  6330. d_Qx = src0_buf_ctx->dev_buffer;
  6331. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6332. GGML_ASSERT(d_Qx != nullptr);
  6333. }
  6334. if(!src1_uma) {
  6335. d_Qy = src1_buf_ctx->dev_buffer;
  6336. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6337. GGML_ASSERT(d_Qy != nullptr);
  6338. }
  6339. if(!ids_uma) {
  6340. d_ids = ids_buf_ctx->dev_buffer;
  6341. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6342. GGML_ASSERT(d_ids != nullptr);
  6343. }
  6344. if (qx_needs_dequant) {
  6345. d_X = ctx->prealloc_x;
  6346. } else {
  6347. d_X = d_Qx;
  6348. x_buf_offset = qx_buf_offset;
  6349. GGML_ASSERT(qx_sz == x_sz);
  6350. }
  6351. if (qy_needs_dequant) {
  6352. d_Y = ctx->prealloc_y;
  6353. } else {
  6354. d_Y = d_Qy;
  6355. y_buf_offset = qy_buf_offset;
  6356. GGML_ASSERT(qy_sz == y_sz);
  6357. }
  6358. if (x_non_contig) {
  6359. if (ctx->prealloc_x_need_sync) {
  6360. ggml_vk_sync_buffers(ctx, subctx);
  6361. }
  6362. }
  6363. if (x_non_contig) {
  6364. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6365. 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));
  6366. }
  6367. if (y_non_contig) {
  6368. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6369. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6370. ctx->prealloc_y_last_tensor_used != src1) {
  6371. if (ctx->prealloc_y_need_sync) {
  6372. ggml_vk_sync_buffers(ctx, subctx);
  6373. }
  6374. 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));
  6375. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6376. ctx->prealloc_y_last_tensor_used = src1;
  6377. }
  6378. }
  6379. uint32_t stride_batch_y = ne10*ne11;
  6380. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6381. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6382. }
  6383. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6384. uint32_t groups_x = ne01;
  6385. uint32_t groups_z = 1;
  6386. if (ne01 > max_groups_x) {
  6387. groups_z = 64;
  6388. groups_x = CEIL_DIV(groups_x, groups_z);
  6389. }
  6390. // compute
  6391. const vk_mat_vec_id_push_constants pc = {
  6392. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6393. (uint32_t)x_ne, stride_batch_y, (uint32_t)(ne20*ne21),
  6394. (uint32_t)nei0, (uint32_t)ne11,
  6395. };
  6396. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6397. { vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 },
  6398. vk_subbuffer{ d_Y, y_buf_offset, y_sz * ne12 * ne13 }, vk_subbuffer{ d_D, d_buf_offset, d_sz * ne22 * ne23}, vk_subbuffer{ d_ids, ids_buf_offset, ids_sz } },
  6399. pc, { groups_x, (uint32_t)nei0, groups_z });
  6400. if (x_non_contig) {
  6401. ctx->prealloc_x_need_sync = true;
  6402. }
  6403. if (y_non_contig) {
  6404. ctx->prealloc_y_need_sync = true;
  6405. }
  6406. }
  6407. static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, bool dryrun = false) {
  6408. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  6409. if (src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type))) {
  6410. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  6411. } else {
  6412. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  6413. }
  6414. }
  6415. static bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv) {
  6416. // Needs to be kept up to date on shader changes
  6417. GGML_UNUSED(hsv);
  6418. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6419. const uint32_t Br = get_fa_scalar_num_large_rows(hsv);
  6420. const uint32_t Bc = scalar_flash_attention_Bc;
  6421. const uint32_t tmpsh = wg_size * sizeof(float);
  6422. const uint32_t tmpshv4 = wg_size * 4 * sizeof(float);
  6423. const uint32_t masksh = Bc * Br * sizeof(float);
  6424. const uint32_t Qf = Br * (hsk / 4 + 2) * 4 * sizeof(float);
  6425. const uint32_t total_size = tmpsh + tmpshv4 + masksh + Qf;
  6426. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6427. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported);
  6428. return supported;
  6429. }
  6430. static bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool f32acc) {
  6431. // Needs to be kept up to date on shader changes
  6432. GGML_UNUSED(hsv);
  6433. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6434. const uint32_t Br = coopmat1_flash_attention_num_large_rows;
  6435. const uint32_t Bc = scalar_flash_attention_Bc;
  6436. const uint32_t hsk_pad = ROUNDUP_POW2(hsk, 16);
  6437. const uint32_t acctype = f32acc ? 4 : 2;
  6438. const uint32_t f16vec4 = 8;
  6439. const uint32_t tmpsh = wg_size * sizeof(float);
  6440. const uint32_t tmpshv4 = wg_size * 4 * acctype;
  6441. const uint32_t qstride = hsk_pad / 4 + 2;
  6442. const uint32_t Qf = Br * qstride * f16vec4;
  6443. const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br;
  6444. const uint32_t sfsh = Bc * sfshstride * acctype;
  6445. const uint32_t kshstride = hsk_pad / 4 + 2;
  6446. const uint32_t ksh = Bc * kshstride * f16vec4;
  6447. const uint32_t slope = Br * sizeof(float);
  6448. const uint32_t total_size = tmpsh + tmpshv4 + Qf + sfsh + ksh + slope;
  6449. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6450. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported);
  6451. return supported;
  6452. }
  6453. 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, bool dryrun = false) {
  6454. 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];
  6455. 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];
  6456. 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];
  6457. 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];
  6458. if (sinks) {
  6459. 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];
  6460. }
  6461. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  6462. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  6463. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  6464. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  6465. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  6466. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  6467. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  6468. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  6469. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  6470. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  6471. const uint32_t nem2 = mask ? mask->ne[2] : 0;
  6472. const uint32_t nem3 = mask ? mask->ne[3] : 0;
  6473. const uint32_t HSK = nek0;
  6474. const uint32_t HSV = nev0;
  6475. uint32_t N = neq1;
  6476. const uint32_t KV = nek1;
  6477. GGML_ASSERT(ne0 == HSV);
  6478. GGML_ASSERT(ne2 == N);
  6479. // input tensor rows must be contiguous
  6480. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  6481. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  6482. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  6483. GGML_ASSERT(neq0 == HSK);
  6484. GGML_ASSERT(neq1 == N);
  6485. GGML_ASSERT(nev1 == nek1);
  6486. // dst cannot be transposed or permuted
  6487. GGML_ASSERT(nb0 == sizeof(float));
  6488. GGML_ASSERT(nb0 <= nb1);
  6489. GGML_ASSERT(nb1 <= nb2);
  6490. GGML_ASSERT(nb2 <= nb3);
  6491. assert(dst->type == GGML_TYPE_F32);
  6492. assert(q->type == GGML_TYPE_F32);
  6493. assert(k->type == v->type);
  6494. FaCodePath path = ctx->device->coopmat2 ? FA_COOPMAT2 :
  6495. ctx->device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;
  6496. if (path == FA_COOPMAT1) {
  6497. const bool coopmat_shape_supported = (dst->op_params[3] == GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f32acc) ||
  6498. (dst->op_params[3] != GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f16acc);
  6499. const bool coopmat_shmem_supported = ggml_vk_flash_attn_coopmat_shmem_support(ctx->device, HSK, HSV, dst->op_params[3] == GGML_PREC_F32);
  6500. if (!coopmat_shape_supported || !coopmat_shmem_supported) {
  6501. path = FA_SCALAR;
  6502. }
  6503. }
  6504. uint32_t gqa_ratio = 1;
  6505. uint32_t qk_ratio = neq2 / nek2;
  6506. uint32_t workgroups_x = (uint32_t)neq1;
  6507. uint32_t workgroups_y = (uint32_t)neq2;
  6508. uint32_t workgroups_z = (uint32_t)neq3;
  6509. // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga.
  6510. // For coopmat2 FA, we always use the small size (which is still pretty large for gqa).
  6511. uint32_t max_gqa;
  6512. switch (path) {
  6513. case FA_SCALAR:
  6514. case FA_COOPMAT1:
  6515. // We may switch from coopmat1 to scalar, so use the scalar limit for both
  6516. max_gqa = get_fa_scalar_num_large_rows(HSV);
  6517. break;
  6518. case FA_COOPMAT2:
  6519. max_gqa = get_fa_num_small_rows(FA_COOPMAT2);
  6520. break;
  6521. default:
  6522. GGML_ASSERT(0);
  6523. }
  6524. if (N == 1 && qk_ratio > 1 && qk_ratio <= max_gqa &&
  6525. qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) {
  6526. // grouped query attention - make the N dimension equal to gqa_ratio, reduce
  6527. // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1
  6528. // and change addressing calculations to index Q's dimension 2.
  6529. gqa_ratio = qk_ratio;
  6530. N = gqa_ratio;
  6531. workgroups_y /= N;
  6532. }
  6533. bool small_rows = N <= get_fa_num_small_rows(path);
  6534. // coopmat1 does not actually support "small rows" (it needs 16 rows).
  6535. // So use scalar instead.
  6536. if (small_rows && path == FA_COOPMAT1) {
  6537. path = FA_SCALAR;
  6538. }
  6539. // scalar is faster than coopmat2 when N==1
  6540. if (N == 1 && path == FA_COOPMAT2) {
  6541. path = FA_SCALAR;
  6542. }
  6543. // with large hsk/hsv, scalar path may need to use small_rows to fit in shared memory
  6544. if (path == FA_SCALAR &&
  6545. !ggml_vk_flash_attn_scalar_shmem_support(ctx->device, HSK, HSV)) {
  6546. small_rows = true;
  6547. }
  6548. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  6549. uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  6550. uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  6551. // For F32, the shader treats it as a block of size 4 (for vec4 loads)
  6552. if (k->type == GGML_TYPE_F32) {
  6553. k_stride /= 4;
  6554. }
  6555. if (v->type == GGML_TYPE_F32) {
  6556. v_stride /= 4;
  6557. }
  6558. uint32_t alignment = fa_align(path, HSK, HSV, k->type, small_rows);
  6559. bool aligned = (KV % alignment) == 0 &&
  6560. // the "aligned" shader variant will forcibly align strides, for performance
  6561. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  6562. // Need to use the coopmat2 variant that clamps loads when HSK/HSV aren't sufficiently aligned.
  6563. if (((HSK | HSV) % 16) != 0 && path == FA_COOPMAT2) {
  6564. aligned = false;
  6565. }
  6566. bool f32acc = path == FA_SCALAR || dst->op_params[3] == GGML_PREC_F32;
  6567. vk_fa_pipeline_state fa_pipeline_state(HSK, HSV, small_rows, path, aligned, f32acc);
  6568. vk_pipeline pipeline = nullptr;
  6569. auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16[k->type];
  6570. auto it = pipelines.find(fa_pipeline_state);
  6571. if (it != pipelines.end()) {
  6572. pipeline = it->second;
  6573. } else {
  6574. pipelines[fa_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  6575. }
  6576. assert(pipeline);
  6577. uint32_t split_kv = KV;
  6578. uint32_t split_k = 1;
  6579. // Use a placeholder core count if one isn't available. split_k is a big help for perf.
  6580. const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count : 16;
  6581. // Try to use split_k when KV is large enough to be worth the overhead
  6582. if (workgroups_x == 1 && shader_core_count > 0) {
  6583. // Try to run two workgroups per SM.
  6584. split_k = shader_core_count * 2 / (workgroups_y * workgroups_z);
  6585. if (split_k > 1) {
  6586. // Try to evenly split KV into split_k chunks, but it needs to be a multiple
  6587. // of "align", so recompute split_k based on that.
  6588. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment);
  6589. split_k = CEIL_DIV(KV, split_kv);
  6590. workgroups_x = split_k;
  6591. }
  6592. }
  6593. // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1)
  6594. // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows.
  6595. const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne3 : 0;
  6596. if (split_k_size > ctx->device->properties.limits.maxStorageBufferRange) {
  6597. GGML_ABORT("Requested preallocation size is too large");
  6598. }
  6599. if (ctx->prealloc_size_split_k < split_k_size) {
  6600. ctx->prealloc_size_split_k = split_k_size;
  6601. }
  6602. if (dryrun) {
  6603. // Request descriptor sets
  6604. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6605. if (split_k > 1) {
  6606. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1);
  6607. }
  6608. return;
  6609. }
  6610. float scale = 1.0f;
  6611. float max_bias = 0.0f;
  6612. float logit_softcap = 0.0f;
  6613. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  6614. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  6615. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  6616. if (logit_softcap != 0) {
  6617. scale /= logit_softcap;
  6618. }
  6619. const uint32_t n_head_kv = neq2;
  6620. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  6621. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  6622. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  6623. vk_buffer d_Q = nullptr, d_K = nullptr, d_V = nullptr, d_D = nullptr, d_M = nullptr, d_S = nullptr;
  6624. size_t q_buf_offset = 0, k_buf_offset = 0, v_buf_offset = 0, d_buf_offset = 0, m_buf_offset = 0, s_buf_offset = 0;
  6625. bool Q_uma = false, K_uma = false, V_uma = false, D_uma = false, M_uma = false, S_uma = false;
  6626. if (ctx->device->uma) {
  6627. ggml_vk_host_get(ctx->device, q->data, d_Q, q_buf_offset);
  6628. ggml_vk_host_get(ctx->device, k->data, d_K, k_buf_offset);
  6629. ggml_vk_host_get(ctx->device, v->data, d_V, v_buf_offset);
  6630. ggml_vk_host_get(ctx->device, dst->data, d_D, d_buf_offset);
  6631. Q_uma = d_Q != nullptr;
  6632. K_uma = d_K != nullptr;
  6633. V_uma = d_V != nullptr;
  6634. D_uma = d_D != nullptr;
  6635. if (mask) {
  6636. ggml_vk_host_get(ctx->device, mask->data, d_M, m_buf_offset);
  6637. M_uma = d_M != nullptr;
  6638. }
  6639. if (sinks) {
  6640. ggml_vk_host_get(ctx->device, sinks->data, d_S, s_buf_offset);
  6641. S_uma = d_S != nullptr;
  6642. }
  6643. }
  6644. ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6645. ggml_backend_vk_buffer_context * q_buf_ctx = (ggml_backend_vk_buffer_context *)q->buffer->context;
  6646. ggml_backend_vk_buffer_context * k_buf_ctx = (ggml_backend_vk_buffer_context *)k->buffer->context;
  6647. ggml_backend_vk_buffer_context * v_buf_ctx = (ggml_backend_vk_buffer_context *)v->buffer->context;
  6648. if (!Q_uma) {
  6649. d_Q = q_buf_ctx->dev_buffer;
  6650. q_buf_offset = vk_tensor_offset(q) + q->view_offs;
  6651. }
  6652. if (!K_uma) {
  6653. d_K = k_buf_ctx->dev_buffer;
  6654. k_buf_offset = vk_tensor_offset(k) + k->view_offs;
  6655. }
  6656. if (!V_uma) {
  6657. d_V = v_buf_ctx->dev_buffer;
  6658. v_buf_offset = vk_tensor_offset(v) + v->view_offs;
  6659. }
  6660. if (!D_uma) {
  6661. d_D = d_buf_ctx->dev_buffer;
  6662. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6663. }
  6664. if (!M_uma) {
  6665. d_M = d_Q;
  6666. m_buf_offset = q_buf_offset;
  6667. if (mask) {
  6668. ggml_backend_vk_buffer_context * m_buf_ctx = (ggml_backend_vk_buffer_context*)mask->buffer->context;
  6669. d_M = m_buf_ctx->dev_buffer;
  6670. m_buf_offset = vk_tensor_offset(mask) + mask->view_offs;
  6671. }
  6672. }
  6673. if (!S_uma) {
  6674. d_S = d_Q;
  6675. s_buf_offset = q_buf_offset;
  6676. if (sinks) {
  6677. ggml_backend_vk_buffer_context * s_buf_ctx = (ggml_backend_vk_buffer_context*)sinks->buffer->context;
  6678. d_S = s_buf_ctx->dev_buffer;
  6679. s_buf_offset = vk_tensor_offset(sinks) + sinks->view_offs;
  6680. }
  6681. }
  6682. uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | ((mask != nullptr) << 16) | n_head_log2;
  6683. const vk_flash_attn_push_constants pc = { N, KV,
  6684. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  6685. (uint32_t)neq2, (uint32_t)neq3,
  6686. (uint32_t)nek2, (uint32_t)nek3,
  6687. (uint32_t)nev2, (uint32_t)nev3,
  6688. nem1, nem2, nem3,
  6689. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  6690. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  6691. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  6692. scale, max_bias, logit_softcap,
  6693. mask_n_head_log2, m0, m1,
  6694. gqa_ratio, split_kv, split_k };
  6695. if (split_k > 1) {
  6696. if (ctx->prealloc_split_k_need_sync) {
  6697. ggml_vk_sync_buffers(ctx, subctx);
  6698. }
  6699. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6700. {
  6701. ggml_vk_subbuffer(ctx, d_Q, q_buf_offset),
  6702. ggml_vk_subbuffer(ctx, d_K, k_buf_offset),
  6703. ggml_vk_subbuffer(ctx, d_V, v_buf_offset),
  6704. ggml_vk_subbuffer(ctx, d_M, m_buf_offset),
  6705. ggml_vk_subbuffer(ctx, d_S, s_buf_offset),
  6706. ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0),
  6707. },
  6708. // We only use split_k when group query attention is enabled, which means
  6709. // there's no more than one tile of rows (i.e. workgroups_x would have been
  6710. // one). We reuse workgroups_x to mean the number of splits, so we need to
  6711. // cancel out the divide by wg_denoms[0].
  6712. pc, { workgroups_x * pipeline->wg_denoms[0], workgroups_y, workgroups_z });
  6713. ggml_vk_sync_buffers(ctx, subctx);
  6714. const std::array<uint32_t, 5> pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne3, split_k, (sinks != nullptr) };
  6715. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce,
  6716. {
  6717. ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0),
  6718. ggml_vk_subbuffer(ctx, d_S, s_buf_offset),
  6719. ggml_vk_subbuffer(ctx, d_D, d_buf_offset),
  6720. },
  6721. pc2, { (uint32_t)ne1, HSV, (uint32_t)ne3 });
  6722. ctx->prealloc_split_k_need_sync = true;
  6723. } else {
  6724. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6725. {
  6726. ggml_vk_subbuffer(ctx, d_Q, q_buf_offset),
  6727. ggml_vk_subbuffer(ctx, d_K, k_buf_offset),
  6728. ggml_vk_subbuffer(ctx, d_V, v_buf_offset),
  6729. ggml_vk_subbuffer(ctx, d_M, m_buf_offset),
  6730. ggml_vk_subbuffer(ctx, d_S, s_buf_offset),
  6731. ggml_vk_subbuffer(ctx, d_D, d_buf_offset),
  6732. },
  6733. pc, { workgroups_x, workgroups_y, workgroups_z });
  6734. }
  6735. }
  6736. static std::array<uint32_t, 3> ggml_vk_get_conv_elements(const ggml_tensor *dst) {
  6737. const ggml_tensor *src0 = dst->src[0];
  6738. const ggml_tensor *src1 = dst->src[1];
  6739. // src0 - kernel: [KW, KH, Cin, Cout]
  6740. // src1 - input: [W, H, Cin, N]
  6741. // dst - result: [OW, OH, Cout, N]
  6742. // Copied from ggml.c: int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d)
  6743. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6744. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  6745. };
  6746. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6747. int64_t W = src1->ne[0];
  6748. int64_t H = src1->ne[1];
  6749. int64_t KW = src0->ne[0];
  6750. int64_t KH = src0->ne[1];
  6751. int64_t Cout = src0->ne[3];
  6752. int64_t N = src1->ne[3];
  6753. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[1], dst->op_params[3], dst->op_params[5]);
  6754. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], dst->op_params[2], dst->op_params[4]);
  6755. int64_t NPQ = N * OW * OH;
  6756. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6757. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6758. return elements;
  6759. }
  6760. static std::array<uint32_t, 3> ggml_vk_get_conv_transpose_2d_elements(const ggml_tensor *dst) {
  6761. const ggml_tensor *src0 = dst->src[0];
  6762. const ggml_tensor *src1 = dst->src[1];
  6763. // src0 - kernel: [KW, KH, Cout, Cin]
  6764. // src1 - input: [W, H, Cin, N]
  6765. // dst - result: [OW, OH, Cout, N]
  6766. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6767. return (ins - 1) * s - 2 * p + (ks - 1) * d + 1;
  6768. };
  6769. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6770. int64_t W = src1->ne[0];
  6771. int64_t H = src1->ne[1];
  6772. int64_t KW = src0->ne[0];
  6773. int64_t KH = src0->ne[1];
  6774. int64_t Cout = src0->ne[2];
  6775. int64_t N = src1->ne[3];
  6776. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[0], 0, 1);
  6777. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], 0, 1);
  6778. int64_t NPQ = N * OW * OH;
  6779. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6780. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6781. return elements;
  6782. }
  6783. 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) {
  6784. switch (op) {
  6785. case GGML_OP_GET_ROWS:
  6786. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  6787. if (dst->type == GGML_TYPE_F16) {
  6788. return ctx->device->pipeline_get_rows[src0->type];
  6789. }
  6790. if (dst->type == GGML_TYPE_F32) {
  6791. return ctx->device->pipeline_get_rows_f32[src0->type];
  6792. }
  6793. return nullptr;
  6794. case GGML_OP_ACC:
  6795. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6796. return ctx->device->pipeline_acc_f32;
  6797. }
  6798. return nullptr;
  6799. case GGML_OP_ADD:
  6800. case GGML_OP_SUB:
  6801. case GGML_OP_MUL:
  6802. case GGML_OP_DIV:
  6803. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  6804. (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
  6805. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
  6806. return nullptr;
  6807. }
  6808. switch (op) {
  6809. case GGML_OP_ADD:
  6810. {
  6811. if (ctx->num_additional_fused_ops > 0) {
  6812. if (ctx->do_add_rms_partials) {
  6813. return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops];
  6814. } else {
  6815. return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  6816. }
  6817. }
  6818. if (ctx->do_add_rms_partials) {
  6819. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_rms_norepeat : ctx->device->pipeline_add_rms;
  6820. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6821. } else {
  6822. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add;
  6823. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6824. }
  6825. }
  6826. case GGML_OP_SUB:
  6827. {
  6828. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub;
  6829. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6830. }
  6831. case GGML_OP_MUL:
  6832. {
  6833. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul;
  6834. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6835. }
  6836. case GGML_OP_DIV:
  6837. {
  6838. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div;
  6839. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6840. }
  6841. default:
  6842. break;
  6843. }
  6844. return nullptr;
  6845. case GGML_OP_ADD_ID:
  6846. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) {
  6847. return ctx->device->pipeline_add_id_f32;
  6848. }
  6849. return nullptr;
  6850. case GGML_OP_CONCAT:
  6851. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6852. return ctx->device->pipeline_concat_f32;
  6853. }
  6854. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6855. return ctx->device->pipeline_concat_f16;
  6856. }
  6857. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  6858. return ctx->device->pipeline_concat_i32;
  6859. }
  6860. return nullptr;
  6861. case GGML_OP_UPSCALE:
  6862. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6863. ggml_scale_mode mode = (ggml_scale_mode)(ggml_get_op_params_i32(dst, 0) & 0xFF);
  6864. switch (mode) {
  6865. case GGML_SCALE_MODE_NEAREST:
  6866. return ctx->device->pipeline_upscale_nearest_f32;
  6867. case GGML_SCALE_MODE_BILINEAR:
  6868. return ctx->device->pipeline_upscale_bilinear_f32;
  6869. default:
  6870. return nullptr;
  6871. }
  6872. }
  6873. return nullptr;
  6874. case GGML_OP_SCALE:
  6875. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6876. return ctx->device->pipeline_scale_f32;
  6877. }
  6878. return nullptr;
  6879. case GGML_OP_SQR:
  6880. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6881. return ctx->device->pipeline_sqr_f32;
  6882. }
  6883. return nullptr;
  6884. case GGML_OP_SQRT:
  6885. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6886. return ctx->device->pipeline_sqrt_f32;
  6887. }
  6888. return nullptr;
  6889. case GGML_OP_SIN:
  6890. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6891. return ctx->device->pipeline_sin_f32;
  6892. }
  6893. return nullptr;
  6894. case GGML_OP_COS:
  6895. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6896. return ctx->device->pipeline_cos_f32;
  6897. }
  6898. return nullptr;
  6899. case GGML_OP_CLAMP:
  6900. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6901. return ctx->device->pipeline_clamp_f32;
  6902. }
  6903. return nullptr;
  6904. case GGML_OP_PAD:
  6905. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6906. return ctx->device->pipeline_pad_f32;
  6907. }
  6908. return nullptr;
  6909. case GGML_OP_ROLL:
  6910. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6911. return ctx->device->pipeline_roll_f32;
  6912. }
  6913. return nullptr;
  6914. case GGML_OP_REPEAT:
  6915. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  6916. return ctx->device->pipeline_repeat_f32;
  6917. }
  6918. return nullptr;
  6919. case GGML_OP_REPEAT_BACK:
  6920. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6921. return ctx->device->pipeline_repeat_back_f32;
  6922. }
  6923. return nullptr;
  6924. case GGML_OP_CPY:
  6925. case GGML_OP_CONT:
  6926. case GGML_OP_DUP:
  6927. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  6928. case GGML_OP_SET_ROWS:
  6929. if (src1->type == GGML_TYPE_I64) {
  6930. return ctx->device->pipeline_set_rows_i64[dst->type];
  6931. } else {
  6932. return ctx->device->pipeline_set_rows_i32[dst->type];
  6933. }
  6934. case GGML_OP_SILU_BACK:
  6935. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6936. return ctx->device->pipeline_silu_back_f32;
  6937. }
  6938. return nullptr;
  6939. case GGML_OP_NORM:
  6940. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6941. return ctx->device->pipeline_norm_f32;
  6942. }
  6943. return nullptr;
  6944. case GGML_OP_GROUP_NORM:
  6945. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6946. return ctx->device->pipeline_group_norm_f32;
  6947. }
  6948. return nullptr;
  6949. case GGML_OP_RMS_NORM:
  6950. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6951. if (ctx->do_add_rms_partials) {
  6952. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32;
  6953. } else {
  6954. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32;
  6955. }
  6956. }
  6957. return nullptr;
  6958. case GGML_OP_RMS_NORM_BACK:
  6959. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6960. return ctx->device->pipeline_rms_norm_back_f32;
  6961. }
  6962. return nullptr;
  6963. case GGML_OP_L2_NORM:
  6964. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6965. return ctx->device->pipeline_l2_norm_f32;
  6966. }
  6967. return nullptr;
  6968. case GGML_OP_UNARY:
  6969. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  6970. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  6971. (src0->type != dst->type)) {
  6972. return nullptr;
  6973. }
  6974. switch (ggml_get_unary_op(dst)) {
  6975. case GGML_UNARY_OP_EXP:
  6976. return ctx->device->pipeline_exp[dst->type == GGML_TYPE_F16];
  6977. case GGML_UNARY_OP_SILU:
  6978. return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16];
  6979. case GGML_UNARY_OP_GELU:
  6980. return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16];
  6981. case GGML_UNARY_OP_GELU_ERF:
  6982. return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16];
  6983. case GGML_UNARY_OP_GELU_QUICK:
  6984. return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16];
  6985. case GGML_UNARY_OP_RELU:
  6986. return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16];
  6987. case GGML_UNARY_OP_TANH:
  6988. return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16];
  6989. case GGML_UNARY_OP_SIGMOID:
  6990. return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16];
  6991. case GGML_UNARY_OP_HARDSIGMOID:
  6992. return ctx->device->pipeline_hardsigmoid[dst->type == GGML_TYPE_F16];
  6993. case GGML_UNARY_OP_HARDSWISH:
  6994. return ctx->device->pipeline_hardswish[dst->type == GGML_TYPE_F16];
  6995. default:
  6996. break;
  6997. }
  6998. return nullptr;
  6999. case GGML_OP_GLU:
  7000. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7001. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7002. (src0->type != dst->type)) {
  7003. return nullptr;
  7004. }
  7005. switch (ggml_get_glu_op(dst)) {
  7006. case GGML_GLU_OP_GEGLU:
  7007. return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16];
  7008. case GGML_GLU_OP_REGLU:
  7009. return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16];
  7010. case GGML_GLU_OP_SWIGLU:
  7011. return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16];
  7012. case GGML_GLU_OP_SWIGLU_OAI:
  7013. return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16];
  7014. case GGML_GLU_OP_GEGLU_ERF:
  7015. return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16];
  7016. case GGML_GLU_OP_GEGLU_QUICK:
  7017. return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16];
  7018. default:
  7019. break;
  7020. }
  7021. return nullptr;
  7022. case GGML_OP_DIAG_MASK_INF:
  7023. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7024. return ctx->device->pipeline_diag_mask_inf_f32;
  7025. }
  7026. return nullptr;
  7027. case GGML_OP_SOFT_MAX:
  7028. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  7029. GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32);
  7030. if (ctx->num_additional_fused_ops) {
  7031. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7032. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7033. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  7034. return ctx->device->pipeline_topk_moe[idx][mode];
  7035. }
  7036. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  7037. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  7038. }
  7039. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7040. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  7041. }
  7042. return nullptr;
  7043. case GGML_OP_SOFT_MAX_BACK:
  7044. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7045. return ctx->device->pipeline_soft_max_back_f32;
  7046. }
  7047. return nullptr;
  7048. case GGML_OP_ROPE:
  7049. case GGML_OP_ROPE_BACK:
  7050. {
  7051. const ggml_tensor *rope = ctx->num_additional_fused_ops == 2 ? dst->src[0]->src[0] : dst;
  7052. const int mode = ((const int32_t *) rope->op_params)[2];
  7053. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  7054. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  7055. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  7056. if (is_neox) {
  7057. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7058. return ctx->device->pipeline_rope_neox_f32;
  7059. }
  7060. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7061. return ctx->device->pipeline_rope_neox_f32_f16;
  7062. }
  7063. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7064. return ctx->device->pipeline_rope_neox_f16;
  7065. }
  7066. } else if (is_mrope && !is_vision) {
  7067. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7068. return ctx->device->pipeline_rope_multi_f32;
  7069. }
  7070. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7071. return ctx->device->pipeline_rope_multi_f16;
  7072. }
  7073. } else if (is_vision) {
  7074. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7075. return ctx->device->pipeline_rope_vision_f32;
  7076. }
  7077. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7078. return ctx->device->pipeline_rope_vision_f16;
  7079. }
  7080. } else {
  7081. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7082. return ctx->device->pipeline_rope_norm_f32;
  7083. }
  7084. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7085. return ctx->device->pipeline_rope_norm_f32_f16;
  7086. }
  7087. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7088. return ctx->device->pipeline_rope_norm_f16;
  7089. }
  7090. }
  7091. return nullptr;
  7092. }
  7093. case GGML_OP_ARGSORT:
  7094. if (ctx->num_additional_fused_ops) {
  7095. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7096. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7097. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  7098. return ctx->device->pipeline_topk_moe[idx][mode];
  7099. }
  7100. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7101. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7102. return ctx->device->pipeline_argsort_f32[idx];
  7103. }
  7104. return nullptr;
  7105. case GGML_OP_SUM:
  7106. case GGML_OP_SUM_ROWS:
  7107. case GGML_OP_MEAN:
  7108. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7109. return ctx->device->pipeline_sum_rows_f32;
  7110. }
  7111. return nullptr;
  7112. case GGML_OP_ARGMAX:
  7113. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7114. return ctx->device->pipeline_argmax_f32;
  7115. }
  7116. return nullptr;
  7117. case GGML_OP_COUNT_EQUAL:
  7118. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) {
  7119. return ctx->device->pipeline_count_equal_i32;
  7120. }
  7121. return nullptr;
  7122. case GGML_OP_IM2COL:
  7123. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7124. return ctx->device->pipeline_im2col_f32;
  7125. }
  7126. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7127. return ctx->device->pipeline_im2col_f32_f16;
  7128. }
  7129. return nullptr;
  7130. case GGML_OP_IM2COL_3D:
  7131. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7132. return ctx->device->pipeline_im2col_3d_f32;
  7133. }
  7134. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7135. return ctx->device->pipeline_im2col_3d_f32_f16;
  7136. }
  7137. return nullptr;
  7138. case GGML_OP_TIMESTEP_EMBEDDING:
  7139. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7140. return ctx->device->pipeline_timestep_embedding_f32;
  7141. }
  7142. return nullptr;
  7143. case GGML_OP_CONV_TRANSPOSE_1D:
  7144. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7145. return ctx->device->pipeline_conv_transpose_1d_f32;
  7146. }
  7147. return nullptr;
  7148. case GGML_OP_POOL_2D:
  7149. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7150. return ctx->device->pipeline_pool2d_f32;
  7151. }
  7152. return nullptr;
  7153. case GGML_OP_RWKV_WKV6:
  7154. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7155. return ctx->device->pipeline_rwkv_wkv6_f32;
  7156. }
  7157. return nullptr;
  7158. case GGML_OP_RWKV_WKV7:
  7159. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7160. return ctx->device->pipeline_rwkv_wkv7_f32;
  7161. }
  7162. return nullptr;
  7163. case GGML_OP_SSM_SCAN:
  7164. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7165. const uint32_t d_state = src0->ne[0];
  7166. if (d_state == 128) {
  7167. return ctx->device->pipeline_ssm_scan_f32_d128;
  7168. } else if (d_state == 256) {
  7169. return ctx->device->pipeline_ssm_scan_f32_d256;
  7170. }
  7171. }
  7172. return nullptr;
  7173. case GGML_OP_SSM_CONV:
  7174. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7175. return ctx->device->pipeline_ssm_conv_f32;
  7176. }
  7177. return nullptr;
  7178. case GGML_OP_OPT_STEP_ADAMW:
  7179. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7180. return ctx->device->pipeline_opt_step_adamw_f32;
  7181. }
  7182. return nullptr;
  7183. case GGML_OP_OPT_STEP_SGD:
  7184. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7185. return ctx->device->pipeline_opt_step_sgd_f32;
  7186. }
  7187. return nullptr;
  7188. case GGML_OP_LEAKY_RELU:
  7189. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7190. return ctx->device->pipeline_leaky_relu_f32;
  7191. }
  7192. return nullptr;
  7193. case GGML_OP_CONV_2D:
  7194. case GGML_OP_CONV_TRANSPOSE_2D:
  7195. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 &&
  7196. ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst)) {
  7197. std::array<uint32_t, 3> elements;
  7198. if (op == GGML_OP_CONV_2D) elements = ggml_vk_get_conv_elements(dst);
  7199. else if (op == GGML_OP_CONV_TRANSPOSE_2D) elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  7200. vk_conv_shapes shape;
  7201. uint32_t tiles[CONV_SHAPE_COUNT];
  7202. for (uint32_t i = 0; i < CONV_SHAPE_COUNT; ++i) {
  7203. tiles[i] = CEIL_DIV(elements[0], ctx->device->pipeline_conv2d_f32[i]->wg_denoms[0]) * CEIL_DIV(elements[1], ctx->device->pipeline_conv2d_f32[i]->wg_denoms[1]);
  7204. }
  7205. // We can't query number of shader cores on Intel, use 32 as a placeholder
  7206. // so small convolutions will still choose a smaller tile.
  7207. const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32;
  7208. if (elements[0] > 64 && tiles[CONV_SHAPE_128x128] >= shader_core_count * 2) {
  7209. shape = CONV_SHAPE_128x128;
  7210. } else if (elements[0] <= 32 && tiles[CONV_SHAPE_32x256] >= shader_core_count * 2) {
  7211. shape = CONV_SHAPE_32x256;
  7212. } else {
  7213. shape = CONV_SHAPE_64x32;
  7214. }
  7215. if (op == GGML_OP_CONV_2D) {
  7216. if (src0->type == GGML_TYPE_F32) {
  7217. return ctx->device->pipeline_conv2d_f32[shape];
  7218. } else if (src0->type == GGML_TYPE_F16) {
  7219. return ctx->device->pipeline_conv2d_f16_f32[shape];
  7220. }
  7221. } else if (op == GGML_OP_CONV_TRANSPOSE_2D) {
  7222. if (src0->type == GGML_TYPE_F32) {
  7223. return ctx->device->pipeline_conv_transpose_2d_f32[shape];
  7224. } else if (src0->type == GGML_TYPE_F16) {
  7225. return ctx->device->pipeline_conv_transpose_2d_f16_f32[shape];
  7226. }
  7227. }
  7228. }
  7229. return nullptr;
  7230. case GGML_OP_CONV_2D_DW:
  7231. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7232. if (ggml_is_contiguous(src1)) {
  7233. return ctx->device->pipeline_conv2d_dw_whcn_f32;
  7234. } else if (ggml_is_contiguous_channels(src1)) {
  7235. return ctx->device->pipeline_conv2d_dw_cwhn_f32;
  7236. }
  7237. } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7238. if (ggml_is_contiguous(src1)) {
  7239. return ctx->device->pipeline_conv2d_dw_whcn_f16_f32;
  7240. } else if (ggml_is_contiguous_channels(src1)) {
  7241. return ctx->device->pipeline_conv2d_dw_cwhn_f16_f32;
  7242. }
  7243. }
  7244. return nullptr;
  7245. default:
  7246. return nullptr;
  7247. }
  7248. GGML_UNUSED(src2);
  7249. }
  7250. static bool ggml_vk_op_supports_incontiguous(ggml_op op) {
  7251. switch (op) {
  7252. case GGML_OP_CPY:
  7253. case GGML_OP_GET_ROWS:
  7254. case GGML_OP_ADD:
  7255. case GGML_OP_SUB:
  7256. case GGML_OP_MUL:
  7257. case GGML_OP_DIV:
  7258. case GGML_OP_ADD_ID:
  7259. case GGML_OP_CONCAT:
  7260. case GGML_OP_UPSCALE:
  7261. case GGML_OP_SQR:
  7262. case GGML_OP_SQRT:
  7263. case GGML_OP_SIN:
  7264. case GGML_OP_COS:
  7265. case GGML_OP_CLAMP:
  7266. case GGML_OP_PAD:
  7267. case GGML_OP_REPEAT:
  7268. case GGML_OP_REPEAT_BACK:
  7269. case GGML_OP_ROPE:
  7270. case GGML_OP_RMS_NORM:
  7271. case GGML_OP_CONV_2D_DW:
  7272. case GGML_OP_IM2COL:
  7273. case GGML_OP_IM2COL_3D:
  7274. case GGML_OP_SET_ROWS:
  7275. case GGML_OP_SUM:
  7276. case GGML_OP_SUM_ROWS:
  7277. case GGML_OP_MEAN:
  7278. return true;
  7279. default:
  7280. return false;
  7281. }
  7282. }
  7283. static uint32_t get_misalign_bytes(ggml_backend_vk_context * ctx, const ggml_tensor * t)
  7284. {
  7285. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  7286. }
  7287. 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) {
  7288. GGML_UNUSED(p);
  7289. GGML_UNUSED(src0);
  7290. GGML_UNUSED(src1);
  7291. GGML_UNUSED(src2);
  7292. GGML_UNUSED(src3);
  7293. GGML_UNUSED(dst);
  7294. static_assert(!std::is_const<T>::value, "unexpected type");
  7295. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  7296. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  7297. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  7298. GGML_ASSERT(!src3 || get_misalign_bytes(ctx, src3) == 0);
  7299. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  7300. }
  7301. 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) {
  7302. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7303. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7304. p.misalign_offsets = (a_offset << 16) | d_offset;
  7305. GGML_UNUSED(src1);
  7306. GGML_UNUSED(src2);
  7307. GGML_UNUSED(src3);
  7308. }
  7309. 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) {
  7310. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7311. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7312. p.misalign_offsets = (a_offset << 16) | d_offset;
  7313. GGML_UNUSED(src1);
  7314. GGML_UNUSED(src2);
  7315. GGML_UNUSED(src3);
  7316. }
  7317. 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) {
  7318. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7319. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7320. p.misalign_offsets = (a_offset << 16) | d_offset;
  7321. GGML_UNUSED(src1);
  7322. GGML_UNUSED(src2);
  7323. GGML_UNUSED(src3);
  7324. }
  7325. 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) {
  7326. const uint32_t a_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7327. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7328. p.misalign_offsets = (a_offset << 16) | d_offset;
  7329. GGML_UNUSED(src0);
  7330. GGML_UNUSED(src2);
  7331. GGML_UNUSED(src3);
  7332. }
  7333. 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) {
  7334. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7335. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7336. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7337. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  7338. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  7339. GGML_UNUSED(src2);
  7340. GGML_UNUSED(src3);
  7341. }
  7342. 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) {
  7343. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7344. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7345. p.a_offset = a_offset;
  7346. p.d_offset = d_offset;
  7347. GGML_UNUSED(src1);
  7348. GGML_UNUSED(src2);
  7349. GGML_UNUSED(src3);
  7350. }
  7351. template<typename PC>
  7352. 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, bool dryrun = false) {
  7353. 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];
  7354. if (src1 != nullptr) {
  7355. 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];
  7356. }
  7357. if (src2 != nullptr) {
  7358. 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];
  7359. }
  7360. if (src3 != nullptr) {
  7361. 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];
  7362. }
  7363. 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];
  7364. std::cerr << "), " << ggml_op_name(op) << ", " << (dryrun ? "dryrun" : "") << ")");
  7365. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  7366. GGML_ASSERT(ggml_vk_op_supports_incontiguous(op) || ggml_vk_dim01_contiguous(src0)); // NOLINT
  7367. GGML_ASSERT(dst->buffer != nullptr);
  7368. const uint64_t ne00 = src0->ne[0];
  7369. const uint64_t ne01 = src0->ne[1];
  7370. const uint64_t ne02 = src0->ne[2];
  7371. const uint64_t ne03 = src0->ne[3];
  7372. const uint64_t ne0 = ne00 * ne01;
  7373. const bool use_src1 = src1 != nullptr;
  7374. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  7375. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  7376. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  7377. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  7378. const uint64_t ne1 = ne10 * ne11;
  7379. // const uint64_t nb10 = use_src1 ? src1->nb[0] : 0;
  7380. const bool use_src2 = src2 != nullptr;
  7381. const uint64_t ne20 = use_src2 ? src2->ne[0] : 0;
  7382. const uint64_t ne21 = use_src2 ? src2->ne[1] : 0;
  7383. const uint64_t ne22 = use_src2 ? src2->ne[2] : 0;
  7384. const uint64_t ne23 = use_src2 ? src2->ne[3] : 0;
  7385. const uint64_t ne2 = ne20 * ne21;
  7386. const bool use_src3 = src3 != nullptr;
  7387. const uint64_t ne30 = use_src3 ? src3->ne[0] : 0;
  7388. const uint64_t ne31 = use_src3 ? src3->ne[1] : 0;
  7389. const uint64_t ne32 = use_src3 ? src3->ne[2] : 0;
  7390. const uint64_t ne33 = use_src3 ? src3->ne[3] : 0;
  7391. const uint64_t ne3 = ne30 * ne31;
  7392. const uint64_t ned0 = dst->ne[0];
  7393. const uint64_t ned1 = dst->ne[1];
  7394. const uint64_t ned2 = dst->ne[2];
  7395. const uint64_t ned3 = dst->ne[3];
  7396. const uint64_t ned = ned0 * ned1;
  7397. init_pushconst_fastdiv(pc);
  7398. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  7399. if (pipeline == nullptr) {
  7400. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  7401. if (src1 != nullptr) {
  7402. std::cerr << " and " << ggml_type_name(src1->type);
  7403. }
  7404. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  7405. GGML_ABORT("fatal error");
  7406. }
  7407. if (dryrun) {
  7408. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7409. return;
  7410. }
  7411. const bool op_supports_incontiguous = ggml_vk_op_supports_incontiguous(op);
  7412. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  7413. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  7414. ggml_backend_vk_buffer_context * src1_buf_ctx = use_src1 ? (ggml_backend_vk_buffer_context *)src1->buffer->context : nullptr;
  7415. ggml_backend_vk_buffer_context * src2_buf_ctx = use_src2 ? (ggml_backend_vk_buffer_context *)src2->buffer->context : nullptr;
  7416. ggml_backend_vk_buffer_context * src3_buf_ctx = use_src3 ? (ggml_backend_vk_buffer_context *)src3->buffer->context : nullptr;
  7417. vk_buffer d_X = nullptr;
  7418. size_t x_buf_offset = 0;
  7419. vk_buffer d_Y = nullptr;
  7420. size_t y_buf_offset = 0;
  7421. vk_buffer d_Z = nullptr;
  7422. size_t z_buf_offset = 0;
  7423. vk_buffer d_W = nullptr;
  7424. size_t w_buf_offset = 0;
  7425. bool src0_uma = false;
  7426. bool src1_uma = false;
  7427. bool src2_uma = false;
  7428. bool src3_uma = false;
  7429. if (ctx->device->uma) {
  7430. ggml_vk_host_get(ctx->device, src0->data, d_X, x_buf_offset);
  7431. src0_uma = d_X != nullptr;
  7432. if (use_src1) {
  7433. ggml_vk_host_get(ctx->device, src1->data, d_Y, y_buf_offset);
  7434. src1_uma = d_Y != nullptr;
  7435. }
  7436. if (use_src2) {
  7437. ggml_vk_host_get(ctx->device, src2->data, d_Z, z_buf_offset);
  7438. src2_uma = d_Z != nullptr;
  7439. }
  7440. if (use_src3) {
  7441. ggml_vk_host_get(ctx->device, src3->data, d_W, w_buf_offset);
  7442. src3_uma = d_W != nullptr;
  7443. }
  7444. }
  7445. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  7446. GGML_ASSERT(d_D != nullptr);
  7447. uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  7448. if(!src0_uma) {
  7449. d_X = src0_buf_ctx->dev_buffer;
  7450. x_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  7451. GGML_ASSERT(d_X != nullptr);
  7452. }
  7453. if (use_src1 && !src1_uma) {
  7454. d_Y = src1_buf_ctx->dev_buffer;
  7455. y_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  7456. GGML_ASSERT(d_Y != nullptr);
  7457. }
  7458. if (use_src2 && !src2_uma) {
  7459. d_Z = src2_buf_ctx->dev_buffer;
  7460. z_buf_offset = vk_tensor_offset(src2) + src2->view_offs;
  7461. GGML_ASSERT(d_Z != nullptr);
  7462. }
  7463. if (use_src3 && !src3_uma) {
  7464. d_W = src3_buf_ctx->dev_buffer;
  7465. w_buf_offset = vk_tensor_offset(src3) + src3->view_offs;
  7466. GGML_ASSERT(d_W != nullptr);
  7467. }
  7468. // Compute misalignment offset for descriptors and store it in in push constants, then align the descriptor offsets.
  7469. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, src3, dst);
  7470. x_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7471. y_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7472. z_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7473. w_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7474. d_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7475. std::array<uint32_t, 3> elements;
  7476. // Single call if dimension 2 is contiguous
  7477. GGML_ASSERT(op_supports_incontiguous || (ggml_is_contiguous(src0) && (src1 == nullptr || ggml_is_contiguous(src1))));
  7478. switch (op) {
  7479. case GGML_OP_NORM:
  7480. case GGML_OP_RMS_NORM_BACK:
  7481. case GGML_OP_L2_NORM:
  7482. case GGML_OP_SOFT_MAX:
  7483. case GGML_OP_SOFT_MAX_BACK:
  7484. case GGML_OP_SUM_ROWS:
  7485. case GGML_OP_MEAN:
  7486. case GGML_OP_ARGMAX:
  7487. {
  7488. const uint32_t nr = ggml_nrows(src0);
  7489. if (nr > 262144) {
  7490. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7491. } else if (nr > 512) {
  7492. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7493. } else {
  7494. elements = { nr, 1, 1 };
  7495. }
  7496. } break;
  7497. case GGML_OP_RMS_NORM:
  7498. if (ctx->do_add_rms_partials) {
  7499. // Run one element per thread, 128 threads per workgroup
  7500. elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 };
  7501. } else {
  7502. elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 };
  7503. }
  7504. break;
  7505. case GGML_OP_SUM:
  7506. // We use GGML_OP_SUM_ROWS with 1 row.
  7507. elements = { 1, 1, 1 };
  7508. break;
  7509. case GGML_OP_GROUP_NORM:
  7510. {
  7511. const uint32_t num_groups = dst->op_params[0];
  7512. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  7513. } break;
  7514. case GGML_OP_DIAG_MASK_INF:
  7515. case GGML_OP_ROPE:
  7516. case GGML_OP_ROPE_BACK:
  7517. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  7518. break;
  7519. case GGML_OP_GET_ROWS:
  7520. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  7521. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7522. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7523. break;
  7524. case GGML_OP_ARGSORT:
  7525. elements = { (uint32_t)ne00, (uint32_t)ggml_nrows(src0), 1 };
  7526. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7527. break;
  7528. case GGML_OP_IM2COL:
  7529. {
  7530. const bool is_2D = dst->op_params[6] == 1;
  7531. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  7532. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  7533. const uint32_t KW = src0->ne[0];
  7534. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  7535. const uint32_t OW = dst->ne[1];
  7536. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  7537. elements = { OW * KW * KH, OH, batch * IC };
  7538. } break;
  7539. case GGML_OP_IM2COL_3D:
  7540. {
  7541. const uint32_t IC = ((const uint32_t *)(dst->op_params))[9];
  7542. const uint32_t N = ne13 / IC;
  7543. const uint32_t KD = ne02;
  7544. const uint32_t KH = ne01;
  7545. const uint32_t KW = ne00;
  7546. const uint32_t OD = ned3 / N;
  7547. const uint32_t OH = ned2;
  7548. const uint32_t OW = ned1;
  7549. const uint32_t IC_KD_KH_KW = IC*KD*KH*KW;
  7550. const uint32_t N_OD_OH = N*OD*OH;
  7551. elements = { IC_KD_KH_KW, OW, N_OD_OH };
  7552. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7553. } break;
  7554. case GGML_OP_TIMESTEP_EMBEDDING:
  7555. {
  7556. const uint32_t dim = dst->op_params[0];
  7557. uint32_t half_ceil = (dim + 1) / 2;
  7558. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  7559. } break;
  7560. case GGML_OP_CONV_TRANSPOSE_1D:
  7561. {
  7562. elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1}
  7563. } break;
  7564. case GGML_OP_POOL_2D:
  7565. {
  7566. const uint32_t N = dst->ne[3];
  7567. const uint32_t OC = dst->ne[2];
  7568. const uint32_t OH = dst->ne[1];
  7569. const uint32_t OW = dst->ne[0];
  7570. elements = { N * OC * OH * OW, 1, 1};
  7571. } break;
  7572. case GGML_OP_CONV_2D:
  7573. {
  7574. elements = ggml_vk_get_conv_elements(dst);
  7575. } break;
  7576. case GGML_OP_CONV_TRANSPOSE_2D:
  7577. {
  7578. elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  7579. } break;
  7580. case GGML_OP_ADD:
  7581. case GGML_OP_SUB:
  7582. case GGML_OP_DIV:
  7583. case GGML_OP_MUL:
  7584. case GGML_OP_SCALE:
  7585. case GGML_OP_SQR:
  7586. case GGML_OP_SQRT:
  7587. case GGML_OP_SIN:
  7588. case GGML_OP_COS:
  7589. case GGML_OP_CLAMP:
  7590. case GGML_OP_PAD:
  7591. case GGML_OP_ROLL:
  7592. case GGML_OP_REPEAT:
  7593. case GGML_OP_REPEAT_BACK:
  7594. case GGML_OP_CPY:
  7595. case GGML_OP_CONCAT:
  7596. case GGML_OP_UPSCALE:
  7597. case GGML_OP_UNARY:
  7598. case GGML_OP_GLU:
  7599. case GGML_OP_CONV_2D_DW:
  7600. {
  7601. uint32_t ne = ggml_nelements(dst);
  7602. if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7603. // Convert from number of logical elements to 2- or 4-byte units.
  7604. ne /= ggml_blck_size(src0->type);
  7605. if ((ggml_type_size(src0->type) % 4) == 0) {
  7606. ne *= ggml_type_size(src0->type) / 4;
  7607. } else {
  7608. ne *= ggml_type_size(src0->type) / 2;
  7609. }
  7610. }
  7611. // copy_to_quant has block size of 32, and each thread does QUANT_K elements.
  7612. // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements.
  7613. // So divide by block size here before splitting into 512x512 groups.
  7614. if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7615. ne = CEIL_DIV(ne, ggml_blck_size(dst->type));
  7616. }
  7617. if (ne > 262144) {
  7618. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7619. } else if (ne > 512) {
  7620. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7621. } else {
  7622. elements = { ne, 1, 1 };
  7623. }
  7624. } break;
  7625. case GGML_OP_ADD_ID:
  7626. {
  7627. elements = { (uint32_t)ne01, (uint32_t)ne02, 1 };
  7628. } break;
  7629. case GGML_OP_SET_ROWS:
  7630. {
  7631. uint32_t ne = ggml_nelements(src0);
  7632. if (ggml_is_quantized(dst->type)) {
  7633. // quants run 32 threads each doing QUANT_K elements
  7634. ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type));
  7635. } else {
  7636. // scalar types do one element per thread, running 512 threads
  7637. ne = CEIL_DIV(ne, 512);
  7638. }
  7639. if (ne > 262144) {
  7640. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7641. } else if (ne > 512) {
  7642. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7643. } else {
  7644. elements = { ne, 1, 1 };
  7645. }
  7646. }
  7647. break;
  7648. case GGML_OP_SSM_CONV:
  7649. {
  7650. const uint32_t nr = src0->ne[1];
  7651. const uint32_t n_t = dst->ne[1];
  7652. const uint32_t n_s = dst->ne[2];
  7653. elements = { nr, n_t, n_s };
  7654. }
  7655. break;
  7656. default:
  7657. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  7658. break;
  7659. }
  7660. uint64_t x_sz, y_sz, z_sz, w_sz, d_sz;
  7661. if (op_supports_incontiguous) {
  7662. x_sz = ggml_nbytes(src0) + get_misalign_bytes(ctx, src0);
  7663. y_sz = use_src1 ? ggml_nbytes(src1) + get_misalign_bytes(ctx, src1) : 0;
  7664. z_sz = use_src2 ? ggml_nbytes(src2) + get_misalign_bytes(ctx, src2) : 0;
  7665. w_sz = use_src3 ? ggml_nbytes(src3) + get_misalign_bytes(ctx, src3) : 0;
  7666. d_sz = ggml_nbytes(dst) + get_misalign_bytes(ctx, dst);
  7667. if (x_buf_offset + x_sz >= d_X->size) {
  7668. x_sz = ggml_vk_get_max_buffer_range(ctx, d_X, x_buf_offset);
  7669. }
  7670. if (use_src1 && y_buf_offset + y_sz >= d_Y->size) {
  7671. y_sz = ggml_vk_get_max_buffer_range(ctx, d_Y, y_buf_offset);
  7672. }
  7673. if (use_src2 && z_buf_offset + z_sz >= d_Z->size) {
  7674. z_sz = ggml_vk_get_max_buffer_range(ctx, d_Z, z_buf_offset);
  7675. }
  7676. if (use_src3 && w_buf_offset + w_sz >= d_W->size) {
  7677. w_sz = ggml_vk_get_max_buffer_range(ctx, d_W, w_buf_offset);
  7678. }
  7679. if (d_buf_offset + d_sz >= d_D->size) {
  7680. d_sz = ggml_vk_get_max_buffer_range(ctx, d_D, d_buf_offset);
  7681. }
  7682. } else {
  7683. x_sz = ggml_type_size(src0->type)/ggml_blck_size(src0->type) * ne0 * ne02 * ne03;
  7684. y_sz = use_src1 ? ggml_type_size(src1->type) * ne1 * ne12 * ne13 : 0;
  7685. z_sz = use_src2 ? ggml_type_size(src2->type) * ne2 * ne22 * ne23 : 0;
  7686. w_sz = use_src3 ? ggml_type_size(src3->type) * ne3 * ne32 * ne33 : 0;
  7687. d_sz = ggml_type_size(dst->type) * ned * ned2 * ned3;
  7688. }
  7689. if (op == GGML_OP_ADD || op == GGML_OP_RMS_NORM) {
  7690. vk_buffer d_A = ctx->do_add_rms_partials ? ctx->prealloc_add_rms_partials : d_X;
  7691. size_t a_buf_offset = ctx->do_add_rms_partials ? ctx->prealloc_size_add_rms_partials_offset : 0;
  7692. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7693. { vk_subbuffer{ d_X, x_buf_offset, x_sz },
  7694. vk_subbuffer{ d_Y, y_buf_offset, y_sz },
  7695. vk_subbuffer{ d_D, d_buf_offset, d_sz },
  7696. ggml_vk_subbuffer(ctx, d_A, a_buf_offset),
  7697. }, pc, elements);
  7698. } else if (op == GGML_OP_GLU) {
  7699. // Empty src1 is possible in glu, but the shader needs a buffer
  7700. vk_subbuffer subbuf_y;
  7701. if (use_src1) {
  7702. subbuf_y = { d_Y, y_buf_offset, y_sz };
  7703. } else {
  7704. subbuf_y = { d_X, 0, x_sz };
  7705. }
  7706. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, subbuf_y, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7707. } else if (op == GGML_OP_SOFT_MAX) {
  7708. // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer
  7709. vk_subbuffer subbuf_y;
  7710. if (use_src1) {
  7711. subbuf_y = { d_Y, y_buf_offset, y_sz };
  7712. } else {
  7713. subbuf_y = { d_X, 0, x_sz };
  7714. }
  7715. vk_subbuffer subbuf_z;
  7716. if (use_src2) {
  7717. subbuf_z = { d_Z, z_buf_offset, z_sz };
  7718. } else {
  7719. subbuf_z = { d_X, 0, x_sz };
  7720. }
  7721. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, subbuf_y, subbuf_z, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7722. } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) {
  7723. // Empty src2 is possible in rope, but the shader needs a buffer
  7724. vk_subbuffer subbuf_z, subbuf_w;
  7725. if (use_src2) {
  7726. subbuf_z = { d_Z, z_buf_offset, z_sz };
  7727. } else {
  7728. subbuf_z = { d_X, 0, x_sz };
  7729. }
  7730. if (use_src3) {
  7731. subbuf_w = { d_W, w_buf_offset, w_sz };
  7732. } else {
  7733. subbuf_w = { d_X, 0, x_sz };
  7734. }
  7735. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, subbuf_z, vk_subbuffer{ d_D, d_buf_offset, d_sz }, subbuf_w }, pc, elements);
  7736. } else if (op == GGML_OP_IM2COL || op == GGML_OP_IM2COL_3D) {
  7737. if (ctx->device->shader_int64 && ctx->device->buffer_device_address) {
  7738. // buffer device address path doesn't use dst buffer
  7739. d_sz = 1;
  7740. }
  7741. // im2col uses only src1 and dst buffers
  7742. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7743. } else if (op == GGML_OP_COUNT_EQUAL) {
  7744. // count_equal assumes that destination buffer is initialized with zeroes
  7745. ggml_vk_buffer_memset_async(subctx, d_D, d_buf_offset, 0, d_sz);
  7746. ggml_vk_sync_buffers(ctx, subctx);
  7747. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7748. } else if (op == GGML_OP_OPT_STEP_SGD) {
  7749. // OPT_STEP_SGD works on src0, it does not need dst
  7750. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_Z, z_buf_offset, z_sz } }, pc, elements);
  7751. } else if (use_src3) {
  7752. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_Z, z_buf_offset, z_sz }, vk_subbuffer{ d_W, w_buf_offset, w_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7753. } else if (use_src2) {
  7754. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_Z, z_buf_offset, z_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7755. } else if (use_src1) {
  7756. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7757. } else {
  7758. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7759. }
  7760. }
  7761. 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, bool dryrun = false) {
  7762. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7763. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7764. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7765. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GET_ROWS, {
  7766. (uint32_t)ggml_nelements(src0),
  7767. (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,
  7768. (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,
  7769. (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,
  7770. 0,
  7771. 0.0f, 0.0f, 0,
  7772. }, dryrun);
  7773. }
  7774. static void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  7775. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7776. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7777. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7778. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  7779. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  7780. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  7781. int offset = dst->op_params[3] / 4; // offset in bytes
  7782. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ACC, {
  7783. (uint32_t)ggml_nelements(src0),
  7784. (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,
  7785. (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,
  7786. (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,
  7787. 0,
  7788. 0.0f, 0.0f, offset,
  7789. }, dryrun);
  7790. }
  7791. static void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx, bool dryrun = false) {
  7792. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  7793. const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  7794. // Make a list of all the tensors used by the op.
  7795. // Last element of the list is the dest tensor.
  7796. const ggml_tensor *tensors[MAX_PARAMETER_COUNT];
  7797. uint32_t num_srcs = ctx->num_additional_fused_ops + 2;
  7798. uint32_t num_tensors = num_srcs + 1;
  7799. GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT);
  7800. tensors[0] = first_node->src[0];
  7801. tensors[1] = first_node->src[1];
  7802. for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) {
  7803. // check whether the previous result is src[0] or src[1]
  7804. if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) {
  7805. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1];
  7806. } else {
  7807. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0];
  7808. }
  7809. }
  7810. tensors[num_srcs] = dst;
  7811. vk_op_multi_add_push_constants pc;
  7812. pc.ne20 = (uint32_t)dst->ne[0];
  7813. pc.ne21 = (uint32_t)dst->ne[1];
  7814. pc.ne22 = (uint32_t)dst->ne[2];
  7815. pc.ne23 = (uint32_t)dst->ne[3];
  7816. for (uint32_t i = 0; i < num_tensors; ++i) {
  7817. const ggml_tensor *t = tensors[i];
  7818. pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float);
  7819. pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float);
  7820. pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float);
  7821. pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float);
  7822. }
  7823. pc.rms_partials = ctx->do_add_rms_partials;
  7824. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, tensors[0], tensors[1], nullptr, dst, dst->op);
  7825. if (pipeline == nullptr) {
  7826. std::cerr << "ggml_vulkan: Error: Missing multi_add";
  7827. GGML_ABORT("fatal error");
  7828. }
  7829. if (dryrun) {
  7830. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7831. return;
  7832. }
  7833. ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT];
  7834. vk_buffer buf[MAX_PARAMETER_COUNT];
  7835. size_t offset[MAX_PARAMETER_COUNT];
  7836. bool uma[MAX_PARAMETER_COUNT];
  7837. for (uint32_t i = 0; i < num_tensors; ++i) {
  7838. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  7839. buf[i] = nullptr;
  7840. offset[i] = 0;
  7841. uma[i] = false;
  7842. if (ctx->device->uma) {
  7843. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  7844. uma[i] = buf[i] != nullptr;
  7845. }
  7846. if (!uma[i]) {
  7847. buf[i] = buf_ctx[i]->dev_buffer;
  7848. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  7849. }
  7850. GGML_ASSERT(buf[i] != nullptr);
  7851. }
  7852. // If any remaining descriptors are unused, just point them at src[0]
  7853. for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) {
  7854. buf[i] = buf[0];
  7855. offset[i] = 0;
  7856. }
  7857. if (ctx->do_add_rms_partials) {
  7858. buf[num_tensors] = ctx->prealloc_add_rms_partials;
  7859. offset[num_tensors] = ctx->prealloc_size_add_rms_partials_offset;
  7860. }
  7861. std::array<uint32_t, 3> elements;
  7862. uint32_t ne = ggml_nelements(dst);
  7863. if (ne > 262144) {
  7864. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7865. } else if (ne > 512) {
  7866. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7867. } else {
  7868. elements = { ne, 1, 1 };
  7869. }
  7870. static_assert(MAX_PARAMETER_COUNT == 12);
  7871. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7872. {
  7873. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  7874. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  7875. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  7876. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  7877. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  7878. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  7879. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  7880. ggml_vk_subbuffer(ctx, buf[7], offset[7]),
  7881. ggml_vk_subbuffer(ctx, buf[8], offset[8]),
  7882. ggml_vk_subbuffer(ctx, buf[9], offset[9]),
  7883. ggml_vk_subbuffer(ctx, buf[10], offset[10]),
  7884. ggml_vk_subbuffer(ctx, buf[11], offset[11]),
  7885. }, pc, elements);
  7886. }
  7887. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  7888. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7889. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7890. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7891. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD, {
  7892. (uint32_t)ggml_nelements(src0),
  7893. (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,
  7894. (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,
  7895. (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,
  7896. 0,
  7897. 0.0f, 0.0f, ctx->do_add_rms_partials,
  7898. }, dryrun);
  7899. }
  7900. static void ggml_vk_sub(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  7901. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7902. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7903. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7904. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SUB, {
  7905. (uint32_t)ggml_nelements(src0),
  7906. (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,
  7907. (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,
  7908. (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,
  7909. 0,
  7910. 0.0f, 0.0f, 0,
  7911. }, dryrun);
  7912. }
  7913. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  7914. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7915. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7916. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7917. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_MUL, {
  7918. (uint32_t)ggml_nelements(src0),
  7919. (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,
  7920. (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,
  7921. (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,
  7922. 0,
  7923. 0.0f, 0.0f, 0,
  7924. }, dryrun);
  7925. }
  7926. static void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  7927. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7928. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7929. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7930. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_DIV, {
  7931. (uint32_t)ggml_nelements(src0),
  7932. (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,
  7933. (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,
  7934. (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,
  7935. 0,
  7936. 0.0f, 0.0f, 0,
  7937. }, dryrun);
  7938. }
  7939. 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, bool dryrun = false) {
  7940. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7941. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7942. const uint32_t src2_type_size = ggml_type_size(src2->type);
  7943. ggml_vk_op_f32<vk_op_add_id_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_ADD_ID, {
  7944. (uint32_t)dst->ne[0],
  7945. (uint32_t)dst->ne[1],
  7946. (uint32_t)src0->nb[1] / src0_type_size,
  7947. (uint32_t)src0->nb[2] / src0_type_size,
  7948. (uint32_t)src1->nb[1] / src1_type_size,
  7949. (uint32_t)src2->nb[1] / src2_type_size,
  7950. }, dryrun);
  7951. }
  7952. 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, bool dryrun = false) {
  7953. GGML_ASSERT(version == 6 || version == 7);
  7954. int num_srcs = version == 6 ? 6 : 7;
  7955. for (int i = 0; i < num_srcs; i++) {
  7956. GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type));
  7957. }
  7958. GGML_ASSERT(dst->buffer != nullptr);
  7959. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op);
  7960. GGML_ASSERT(pipeline != nullptr);
  7961. if (dryrun) {
  7962. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7963. return;
  7964. }
  7965. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  7966. ggml_backend_vk_buffer_context * src_buf_ctxs[7] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
  7967. for (int i = 0; i < num_srcs; i++) {
  7968. src_buf_ctxs[i] = (ggml_backend_vk_buffer_context *)dst->src[i]->buffer->context;
  7969. }
  7970. vk_buffer d_D = nullptr, d_srcs[7] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
  7971. size_t dst_offset = 0, src_offsets[7] = { 0, 0, 0, 0, 0, 0, 0 };
  7972. bool dst_uma = false, srcs_uma[7] = { false, false, false, false, false, false, false };
  7973. if (ctx->device->uma) {
  7974. for (int i = 0; i < num_srcs; i++) {
  7975. ggml_vk_host_get(ctx->device, dst->src[i]->data, d_srcs[i], src_offsets[i]);
  7976. srcs_uma[i] = d_srcs[i] != nullptr;
  7977. }
  7978. ggml_vk_host_get(ctx->device, dst->data, d_D, dst_offset);
  7979. dst_uma = d_D != nullptr;
  7980. }
  7981. uint64_t src_sizes[7] = { 0, 0, 0, 0, 0, 0, 0 };
  7982. for (int i = 0; i < num_srcs; i++) {
  7983. src_sizes[i] = ggml_nbytes(dst->src[i]);
  7984. if (!srcs_uma[i]) {
  7985. d_srcs[i] = src_buf_ctxs[i]->dev_buffer;
  7986. src_offsets[i] = vk_tensor_offset(dst->src[i]) + dst->src[i]->view_offs;
  7987. }
  7988. }
  7989. const uint64_t dst_size = ggml_nbytes(dst);
  7990. if (!dst_uma) {
  7991. d_D = dst_buf_ctx->dev_buffer;
  7992. dst_offset = vk_tensor_offset(dst) + dst->view_offs;
  7993. }
  7994. std::array<uint32_t, 3> elements = {
  7995. (uint32_t)(pc.B * pc.H),
  7996. 1,
  7997. 1
  7998. };
  7999. if (version == 6) {
  8000. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  8001. vk_subbuffer{ d_srcs[0], src_offsets[0], src_sizes[0] },
  8002. vk_subbuffer{ d_srcs[1], src_offsets[1], src_sizes[1] },
  8003. vk_subbuffer{ d_srcs[2], src_offsets[2], src_sizes[2] },
  8004. vk_subbuffer{ d_srcs[3], src_offsets[3], src_sizes[3] },
  8005. vk_subbuffer{ d_srcs[4], src_offsets[4], src_sizes[4] },
  8006. vk_subbuffer{ d_srcs[5], src_offsets[5], src_sizes[5] },
  8007. vk_subbuffer{ d_D, dst_offset, dst_size }
  8008. }, pc, elements);
  8009. } else if (version == 7) {
  8010. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  8011. vk_subbuffer{ d_srcs[0], src_offsets[0], src_sizes[0] },
  8012. vk_subbuffer{ d_srcs[1], src_offsets[1], src_sizes[1] },
  8013. vk_subbuffer{ d_srcs[2], src_offsets[2], src_sizes[2] },
  8014. vk_subbuffer{ d_srcs[3], src_offsets[3], src_sizes[3] },
  8015. vk_subbuffer{ d_srcs[4], src_offsets[4], src_sizes[4] },
  8016. vk_subbuffer{ d_srcs[5], src_offsets[5], src_sizes[5] },
  8017. vk_subbuffer{ d_srcs[6], src_offsets[6], src_sizes[6] },
  8018. vk_subbuffer{ d_D, dst_offset, dst_size }
  8019. }, pc, elements);
  8020. } else {
  8021. // shouldn't happen
  8022. GGML_ASSERT(false);
  8023. }
  8024. }
  8025. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  8026. const size_t seq_length = dst->src[0]->ne[2];
  8027. const size_t n_embed = dst->ne[0];
  8028. const size_t n_heads = dst->src[0]->ne[1];
  8029. const size_t n_seqs = dst->src[5]->ne[1];
  8030. ggml_vk_op_f32_wkv(
  8031. ctx, subctx, dst,
  8032. {
  8033. (uint32_t)n_seqs,
  8034. (uint32_t)seq_length,
  8035. (uint32_t)n_embed,
  8036. (uint32_t)n_heads,
  8037. },
  8038. 6,
  8039. dryrun
  8040. );
  8041. }
  8042. static void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  8043. const size_t seq_length = dst->src[0]->ne[2];
  8044. const size_t n_embed = dst->ne[0];
  8045. const size_t n_heads = dst->src[0]->ne[1];
  8046. const size_t n_seqs = dst->src[6]->ne[1];
  8047. ggml_vk_op_f32_wkv(
  8048. ctx, subctx, dst,
  8049. {
  8050. (uint32_t)n_seqs,
  8051. (uint32_t)seq_length,
  8052. (uint32_t)n_embed,
  8053. (uint32_t)n_heads,
  8054. },
  8055. 7,
  8056. dryrun
  8057. );
  8058. }
  8059. static void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  8060. const ggml_tensor * src0 = dst->src[0];
  8061. const ggml_tensor * src1 = dst->src[1];
  8062. const ggml_tensor * src2 = dst->src[2];
  8063. const ggml_tensor * src3 = dst->src[3];
  8064. const ggml_tensor * src4 = dst->src[4];
  8065. const ggml_tensor * src5 = dst->src[5];
  8066. GGML_ASSERT(dst->buffer != nullptr);
  8067. const uint32_t head_dim = src0->ne[1];
  8068. const uint32_t n_head = src1->ne[1];
  8069. const uint32_t n_group = src4->ne[1];
  8070. const uint32_t n_tok = src1->ne[2];
  8071. const uint32_t n_seq = src1->ne[3];
  8072. bool is_mamba2 = (src3->nb[1] == sizeof(float));
  8073. GGML_ASSERT(is_mamba2);
  8074. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op);
  8075. GGML_ASSERT(pipeline != nullptr);
  8076. if (dryrun) {
  8077. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8078. return;
  8079. }
  8080. const int64_t s_off = ggml_nelements(src1) * sizeof(float);
  8081. const vk_op_ssm_scan_push_constants pc = {
  8082. (uint32_t)src0->nb[2], (uint32_t)src0->nb[3],
  8083. (uint32_t)src1->nb[2], (uint32_t)src1->nb[3],
  8084. (uint32_t)src2->nb[1], (uint32_t)src2->nb[2],
  8085. (uint32_t)src3->nb[1],
  8086. (uint32_t)src4->nb[2], (uint32_t)src4->nb[3],
  8087. (uint32_t)src5->nb[2], (uint32_t)src5->nb[3],
  8088. (uint32_t)s_off,
  8089. n_head, head_dim, n_group, n_tok
  8090. };
  8091. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8092. ggml_backend_vk_buffer_context * src_buf_ctxs[GGML_MAX_SRC];
  8093. for (int i = 0; i < GGML_MAX_SRC && dst->src[i] != nullptr; i++) {
  8094. src_buf_ctxs[i] = (ggml_backend_vk_buffer_context *)dst->src[i]->buffer->context;
  8095. }
  8096. vk_buffer d_D = nullptr, d_srcs[GGML_MAX_SRC] = { nullptr };
  8097. size_t dst_offset = 0, src_offsets[GGML_MAX_SRC] = { 0 };
  8098. bool dst_uma = false, srcs_uma[GGML_MAX_SRC] = { false };
  8099. if (ctx->device->uma) {
  8100. for (int i = 0; i < GGML_MAX_SRC && dst->src[i] != nullptr; i++) {
  8101. ggml_vk_host_get(ctx->device, dst->src[i]->data, d_srcs[i], src_offsets[i]);
  8102. srcs_uma[i] = d_srcs[i] != nullptr;
  8103. }
  8104. ggml_vk_host_get(ctx->device, dst->data, d_D, dst_offset);
  8105. dst_uma = d_D != nullptr;
  8106. }
  8107. if (!dst_uma) {
  8108. d_D = dst_buf_ctx->dev_buffer;
  8109. dst_offset = vk_tensor_offset(dst) + dst->view_offs;
  8110. }
  8111. for (int i = 0; i < GGML_MAX_SRC && dst->src[i] != nullptr; i++) {
  8112. if (!srcs_uma[i]) {
  8113. d_srcs[i] = src_buf_ctxs[i]->dev_buffer;
  8114. src_offsets[i] = vk_tensor_offset(dst->src[i]) + dst->src[i]->view_offs;
  8115. }
  8116. }
  8117. size_t dst_size = ggml_nbytes(dst);
  8118. size_t src_sizes[GGML_MAX_SRC];
  8119. for (int i = 0; i < GGML_MAX_SRC && dst->src[i] != nullptr; i++) {
  8120. src_sizes[i] = ggml_nbytes(dst->src[i]);
  8121. }
  8122. std::array<uint32_t, 3> elements;
  8123. const int splitH = 16;
  8124. const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, splitH);
  8125. const uint32_t num_workgroups_y = n_seq;
  8126. elements = { num_workgroups_x, num_workgroups_y, 1 };
  8127. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  8128. vk_subbuffer{ d_srcs[0], src_offsets[0], src_sizes[0] },
  8129. vk_subbuffer{ d_srcs[1], src_offsets[1], src_sizes[1] },
  8130. vk_subbuffer{ d_srcs[2], src_offsets[2], src_sizes[2] },
  8131. vk_subbuffer{ d_srcs[3], src_offsets[3], src_sizes[3] },
  8132. vk_subbuffer{ d_srcs[4], src_offsets[4], src_sizes[4] },
  8133. vk_subbuffer{ d_srcs[5], src_offsets[5], src_sizes[5] },
  8134. vk_subbuffer{ d_srcs[6], src_offsets[6], src_sizes[6] },
  8135. vk_subbuffer{ d_D, dst_offset, dst_size }
  8136. }, pc, elements);
  8137. }
  8138. static void ggml_vk_ssm_conv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  8139. const ggml_tensor * src0 = dst->src[0];
  8140. const ggml_tensor * src1 = dst->src[1];
  8141. ggml_vk_op_f32<vk_op_ssm_conv_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SSM_CONV, {
  8142. (uint32_t)src0->nb[1], (uint32_t)src0->nb[2],
  8143. (uint32_t)src1->nb[1],
  8144. (uint32_t)dst->nb[0], (uint32_t)dst->nb[1], (uint32_t)dst->nb[2],
  8145. (uint32_t)src1->ne[0],
  8146. (uint32_t)src0->ne[0],
  8147. (uint32_t)src0->ne[1],
  8148. (uint32_t)dst->ne[1],
  8149. (uint32_t)dst->ne[2],
  8150. }, dryrun);
  8151. }
  8152. 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, bool dryrun = false) {
  8153. const ggml_tensor * x = dst->src[0];
  8154. const ggml_tensor * g = dst->src[1];
  8155. const ggml_tensor * gm = dst->src[2];
  8156. const ggml_tensor * gv = dst->src[3];
  8157. const ggml_tensor * p = dst->src[4];
  8158. GGML_ASSERT(x->type == GGML_TYPE_F32);
  8159. GGML_ASSERT(g->type == GGML_TYPE_F32);
  8160. GGML_ASSERT(gm->type == GGML_TYPE_F32);
  8161. GGML_ASSERT(gv->type == GGML_TYPE_F32);
  8162. GGML_ASSERT(p->type == GGML_TYPE_F32);
  8163. GGML_ASSERT(dst->buffer != nullptr);
  8164. GGML_ASSERT(ggml_is_contiguous(x));
  8165. GGML_ASSERT(ggml_is_contiguous(g));
  8166. GGML_ASSERT(ggml_is_contiguous(gm));
  8167. GGML_ASSERT(ggml_is_contiguous(gv));
  8168. GGML_ASSERT(ggml_is_contiguous(p));
  8169. GGML_ASSERT(ggml_are_same_shape(x, g));
  8170. GGML_ASSERT(ggml_are_same_shape(x, gm));
  8171. GGML_ASSERT(ggml_are_same_shape(x, gv));
  8172. GGML_ASSERT(ggml_nelements(p) == 7);
  8173. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW);
  8174. GGML_ASSERT(pipeline != nullptr);
  8175. if (dryrun) {
  8176. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8177. return;
  8178. }
  8179. ggml_backend_vk_buffer_context * x_buf_ctx = (ggml_backend_vk_buffer_context *)x->buffer->context;
  8180. ggml_backend_vk_buffer_context * g_buf_ctx = (ggml_backend_vk_buffer_context *)g->buffer->context;
  8181. ggml_backend_vk_buffer_context * gm_buf_ctx = (ggml_backend_vk_buffer_context *)gm->buffer->context;
  8182. ggml_backend_vk_buffer_context * gv_buf_ctx = (ggml_backend_vk_buffer_context *)gv->buffer->context;
  8183. ggml_backend_vk_buffer_context * p_buf_ctx = (ggml_backend_vk_buffer_context *)p->buffer->context;
  8184. vk_buffer d_X = nullptr, d_G = nullptr, d_GM = nullptr, d_GV = nullptr, d_P = nullptr;
  8185. size_t x_offset = 0, g_offset = 0, gm_offset = 0, gv_offset = 0, p_offset = 0;
  8186. bool X_uma = false, G_uma = false, GM_uma = false, GV_uma = false, P_uma = false;
  8187. if (ctx->device->uma) {
  8188. ggml_vk_host_get(ctx->device, x->data, d_X, x_offset);
  8189. ggml_vk_host_get(ctx->device, g->data, d_G, g_offset);
  8190. ggml_vk_host_get(ctx->device, gm->data, d_GM, gm_offset);
  8191. ggml_vk_host_get(ctx->device, gv->data, d_GV, gv_offset);
  8192. ggml_vk_host_get(ctx->device, p->data, d_P, p_offset);
  8193. X_uma = d_X != nullptr;
  8194. G_uma = d_G != nullptr;
  8195. GM_uma = d_GM != nullptr;
  8196. GV_uma = d_GV != nullptr;
  8197. P_uma = d_P != nullptr;
  8198. }
  8199. if (!X_uma) {
  8200. d_X = x_buf_ctx->dev_buffer;
  8201. x_offset = vk_tensor_offset(x) + x->view_offs;
  8202. }
  8203. if (!G_uma) {
  8204. d_G = g_buf_ctx->dev_buffer;
  8205. g_offset = vk_tensor_offset(g) + g->view_offs;
  8206. }
  8207. if (!GM_uma) {
  8208. d_GM = gm_buf_ctx->dev_buffer;
  8209. gm_offset = vk_tensor_offset(gm) + gm->view_offs;
  8210. }
  8211. if (!GV_uma) {
  8212. d_GV = gv_buf_ctx->dev_buffer;
  8213. gv_offset = vk_tensor_offset(gv) + gv->view_offs;
  8214. }
  8215. if (!P_uma) {
  8216. d_P = p_buf_ctx->dev_buffer;
  8217. p_offset = vk_tensor_offset(p) + p->view_offs;
  8218. }
  8219. const uint64_t x_size = ggml_nbytes(x);
  8220. const uint64_t g_size = ggml_nbytes(g);
  8221. const uint64_t gm_size = ggml_nbytes(gm);
  8222. const uint64_t gv_size = ggml_nbytes(gv);
  8223. const uint64_t p_size = ggml_nbytes(p);
  8224. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(x), 1, 1 };
  8225. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  8226. vk_subbuffer{ d_X, x_offset, x_size },
  8227. vk_subbuffer{ d_G, g_offset, g_size },
  8228. vk_subbuffer{ d_GM, gm_offset, gm_size },
  8229. vk_subbuffer{ d_GV, gv_offset, gv_size },
  8230. vk_subbuffer{ d_P, p_offset, p_size },
  8231. }, pc, elements);
  8232. }
  8233. static void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  8234. const size_t n = ggml_nelements(dst->src[0]);
  8235. ggml_vk_op_f32_opt_step_adamw(
  8236. ctx, subctx, dst,
  8237. { (uint32_t)n, 0, 0.0f, 0.0f },
  8238. dryrun
  8239. );
  8240. }
  8241. 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, bool dryrun = false) {
  8242. const size_t n = ggml_nelements(dst->src[0]);
  8243. 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 }, dryrun);
  8244. }
  8245. static void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8246. int * op_params = (int *)dst->op_params;
  8247. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8248. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8249. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8250. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONCAT, {
  8251. (uint32_t)ggml_nelements(dst),
  8252. (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,
  8253. (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,
  8254. (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,
  8255. 0,
  8256. 0.0f, 0.0f, op_params[0],
  8257. }, dryrun);
  8258. }
  8259. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8260. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8261. const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0);
  8262. GGML_TENSOR_UNARY_OP_LOCALS
  8263. float sf0 = (float)ne0 / ne00;
  8264. float sf1 = (float)ne1 / ne01;
  8265. float sf2 = (float)ne2 / ne02;
  8266. float sf3 = (float)ne3 / ne03;
  8267. float pixel_offset = 0.5f;
  8268. if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) {
  8269. sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0;
  8270. sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1;
  8271. pixel_offset = 0.0f;
  8272. }
  8273. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  8274. (uint32_t)ggml_nelements(dst), 0, 0,
  8275. (uint32_t)ne00, (uint32_t)ne01,
  8276. (uint32_t)nb00 / src0_type_size, (uint32_t)nb01 / src0_type_size, (uint32_t)nb02 / src0_type_size, (uint32_t)nb03 / src0_type_size,
  8277. (uint32_t)ne0, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  8278. sf0, sf1, sf2, sf3, pixel_offset
  8279. }, dryrun);
  8280. }
  8281. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8282. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8283. p.param1 = ggml_get_op_params_f32(dst, 0);
  8284. p.param2 = ggml_get_op_params_f32(dst, 1);
  8285. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p), dryrun);
  8286. }
  8287. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8288. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst), dryrun);
  8289. }
  8290. static void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8291. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst), dryrun);
  8292. }
  8293. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8294. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst), dryrun);
  8295. }
  8296. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8297. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst), dryrun);
  8298. }
  8299. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8300. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8301. p.param1 = ggml_get_op_params_f32(dst, 0);
  8302. p.param2 = ggml_get_op_params_f32(dst, 1);
  8303. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p), dryrun);
  8304. }
  8305. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8306. vk_op_pad_push_constants p = vk_op_pad_push_constants_init(src0, dst);
  8307. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p), dryrun);
  8308. }
  8309. static void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8310. const int32_t s0 = ggml_get_op_params_i32(dst, 0);
  8311. const int32_t s1 = ggml_get_op_params_i32(dst, 1);
  8312. const int32_t s2 = ggml_get_op_params_i32(dst, 2);
  8313. const int32_t s3 = ggml_get_op_params_i32(dst, 3);
  8314. const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
  8315. const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
  8316. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8317. memcpy(&p.param1, &s01_packed, sizeof(float));
  8318. memcpy(&p.param2, &s23_packed, sizeof(float));
  8319. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p), dryrun);
  8320. }
  8321. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8322. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8323. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p), dryrun);
  8324. }
  8325. static void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8326. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8327. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p), dryrun);
  8328. }
  8329. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8330. uint32_t ne = (uint32_t)ggml_nelements(src0);
  8331. if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8332. // Convert from number of logical elements to 2- or 4-byte units.
  8333. ne /= ggml_blck_size(src0->type);
  8334. if ((ggml_type_size(src0->type) % 4) == 0) {
  8335. ne *= ggml_type_size(src0->type) / 4;
  8336. } else {
  8337. ne *= ggml_type_size(src0->type) / 2;
  8338. }
  8339. }
  8340. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne);
  8341. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p), dryrun);
  8342. }
  8343. 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, bool dryrun = false) {
  8344. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8345. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8346. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8347. // Skip empty skip_rows operations. For most ops the empty check at the start
  8348. // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst
  8349. // with empty srcs.
  8350. if (ggml_is_empty(src0) || ggml_is_empty(src1)) {
  8351. return;
  8352. }
  8353. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SET_ROWS, {
  8354. (uint32_t)ggml_nelements(src0),
  8355. (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,
  8356. (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,
  8357. (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,
  8358. 0,
  8359. 0.0f, 0.0f, 0,
  8360. }, dryrun);
  8361. }
  8362. 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, bool dryrun = false) {
  8363. 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 }, dryrun);
  8364. }
  8365. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8366. float * op_params = (float *)dst->op_params;
  8367. 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 }, dryrun);
  8368. }
  8369. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8370. const int * int_op_params = (const int *)dst->op_params;
  8371. const float * float_op_params = (const float *)dst->op_params;
  8372. const uint32_t num_groups = int_op_params[0];
  8373. const float eps = float_op_params[1];
  8374. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  8375. 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 }, dryrun);
  8376. }
  8377. static uint32_t ggml_vk_rms_num_partials(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8378. const uint32_t ne = (uint32_t)node->ne[0];
  8379. const uint32_t denom = ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0];
  8380. const uint32_t num_partials = CEIL_DIV(ne, denom);
  8381. return num_partials;
  8382. }
  8383. static uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8384. const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node);
  8385. const uint32_t num_bytes = ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment);
  8386. return num_bytes;
  8387. }
  8388. static void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, float * op_params, bool dryrun = false) {
  8389. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8390. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8391. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8392. uint32_t param3 = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0;
  8393. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM, {
  8394. (uint32_t)ggml_nelements(src0),
  8395. (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,
  8396. (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,
  8397. (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,
  8398. 0,
  8399. op_params[0], 0.0f, (int32_t)param3,
  8400. }, dryrun);
  8401. if (ctx->do_add_rms_partials) {
  8402. ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0);
  8403. ctx->do_add_rms_partials = false;
  8404. }
  8405. }
  8406. 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, bool dryrun = false) {
  8407. float * op_params = (float *)dst->op_params;
  8408. 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 }, dryrun);
  8409. }
  8410. static void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8411. float * op_params = (float *)dst->op_params;
  8412. 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 }, dryrun);
  8413. }
  8414. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8415. 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 }, dryrun);
  8416. }
  8417. static void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8418. const float * op_params_f = (const float *)dst->op_params;
  8419. const bool swapped = (bool)dst->op_params[1];
  8420. const bool split = src1 != nullptr;
  8421. const float alpha = op_params_f[2];
  8422. const float limit = op_params_f[3];
  8423. GGML_ASSERT(ggml_is_contiguous(src0));
  8424. if (!split) {
  8425. GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]);
  8426. } else {
  8427. GGML_ASSERT(src0->ne[0] == src1->ne[0]);
  8428. GGML_ASSERT(src0->ne[0] == dst->ne[0]);
  8429. GGML_ASSERT(src0->type == src1->type);
  8430. }
  8431. const uint32_t mode = split ? 2 : (swapped ? 1 : 0);
  8432. ggml_vk_op_f32<vk_op_glu_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GLU,
  8433. {
  8434. (uint32_t)ggml_nelements(dst),
  8435. (uint32_t)src0->ne[0],
  8436. (uint32_t)dst->ne[0],
  8437. mode,
  8438. alpha,
  8439. limit
  8440. }, dryrun);
  8441. }
  8442. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8443. int32_t * op_params = (int32_t *)dst->op_params;
  8444. 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] }, dryrun);
  8445. }
  8446. 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, bool dryrun = false) {
  8447. float * op_params = (float *)dst->op_params;
  8448. float scale = op_params[0];
  8449. float max_bias = op_params[1];
  8450. const uint32_t ncols = (uint32_t)src0->ne[0];
  8451. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  8452. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  8453. const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u;
  8454. const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u;
  8455. const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u;
  8456. const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u;
  8457. const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u;
  8458. const uint32_t n_head_kv = src0->ne[2];
  8459. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  8460. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  8461. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  8462. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_SOFT_MAX, {
  8463. ncols,
  8464. src1 != nullptr ? nrows_y : (uint32_t)0,
  8465. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],
  8466. ne12, ne13,
  8467. nb11, nb12, nb13,
  8468. scale, max_bias,
  8469. m0, m1,
  8470. n_head_log2,
  8471. nrows_x,
  8472. src2 != nullptr
  8473. }, dryrun);
  8474. }
  8475. 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, bool dryrun = false) {
  8476. float * op_params = (float *)dst->op_params;
  8477. 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] }, dryrun);
  8478. }
  8479. static void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx, bool dryrun = false) {
  8480. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  8481. ggml_tensor * logits = cgraph->nodes[node_idx + 0]->src[0];
  8482. ggml_tensor * weights = (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) ? cgraph->nodes[node_idx + 9] :
  8483. (mode == TOPK_MOE_EARLY_SOFTMAX) ? cgraph->nodes[node_idx + 4] :
  8484. cgraph->nodes[node_idx + 5];
  8485. ggml_tensor * ids = (mode == TOPK_MOE_LATE_SOFTMAX) ? cgraph->nodes[node_idx + 1] : cgraph->nodes[node_idx + 3];
  8486. GGML_ASSERT(logits->type == GGML_TYPE_F32);
  8487. GGML_ASSERT(weights->type == GGML_TYPE_F32);
  8488. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  8489. const int n_experts = logits->ne[0];
  8490. const int n_rows = logits->ne[1];
  8491. const int n_expert_used = weights->ne[1];
  8492. GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) n_experts);
  8493. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, cgraph->nodes[node_idx], GGML_OP_SOFT_MAX);
  8494. if (dryrun) {
  8495. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8496. return;
  8497. }
  8498. ggml_backend_vk_buffer_context * logits_buf_ctx = (ggml_backend_vk_buffer_context *)logits->buffer->context;
  8499. ggml_backend_vk_buffer_context * weights_buf_ctx = (ggml_backend_vk_buffer_context *)weights->buffer->context;
  8500. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  8501. vk_buffer d_logits = nullptr;
  8502. size_t logits_buf_offset = 0;
  8503. vk_buffer d_weights = nullptr;
  8504. size_t weights_buf_offset = 0;
  8505. vk_buffer d_ids = nullptr;
  8506. size_t ids_buf_offset = 0;
  8507. bool logits_uma = false;
  8508. bool weights_uma = false;
  8509. bool ids_uma = false;
  8510. if (ctx->device->uma) {
  8511. ggml_vk_host_get(ctx->device, logits->data, d_logits, logits_buf_offset);
  8512. ggml_vk_host_get(ctx->device, weights->data, d_weights, weights_buf_offset);
  8513. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  8514. logits_uma = d_logits != nullptr;
  8515. weights_uma = d_weights != nullptr;
  8516. ids_uma = d_ids != nullptr;
  8517. }
  8518. if (!logits_uma) {
  8519. d_logits = logits_buf_ctx->dev_buffer;
  8520. logits_buf_offset = vk_tensor_offset(logits) + logits->view_offs;
  8521. GGML_ASSERT(d_logits != nullptr);
  8522. }
  8523. if (!weights_uma) {
  8524. d_weights = weights_buf_ctx->dev_buffer;
  8525. weights_buf_offset = vk_tensor_offset(weights) + weights->view_offs;
  8526. GGML_ASSERT(d_weights != nullptr);
  8527. }
  8528. if (!ids_uma) {
  8529. d_ids = ids_buf_ctx->dev_buffer;
  8530. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  8531. GGML_ASSERT(d_ids != nullptr);
  8532. }
  8533. vk_op_topk_moe_push_constants pc {};
  8534. pc.n_rows = n_rows;
  8535. pc.n_expert_used = n_expert_used;
  8536. if (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) {
  8537. ggml_tensor * clamp = cgraph->nodes[node_idx + 7];
  8538. pc.clamp_min = ggml_get_op_params_f32(clamp, 0);
  8539. pc.clamp_max = ggml_get_op_params_f32(clamp, 1);
  8540. }
  8541. GGML_ASSERT(n_expert_used <= n_experts);
  8542. const uint32_t rows_per_block = 4;
  8543. std::array<uint32_t, 3> elements = { CEIL_DIV(n_rows, rows_per_block), 1, 1 };
  8544. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8545. {
  8546. ggml_vk_subbuffer(ctx, d_logits, logits_buf_offset),
  8547. ggml_vk_subbuffer(ctx, d_weights, weights_buf_offset),
  8548. ggml_vk_subbuffer(ctx, d_ids, ids_buf_offset),
  8549. }, pc, elements);
  8550. }
  8551. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_cgraph * cgraph, int node_idx, bool backprop, bool dryrun = false) {
  8552. ggml_tensor * dst = cgraph->nodes[node_idx];
  8553. const ggml_tensor * src0 = dst->src[0];
  8554. const ggml_tensor * src1 = dst->src[1];
  8555. const ggml_tensor * src2 = dst->src[2];
  8556. const ggml_tensor * src3 = nullptr;
  8557. const int n_dims = ((int32_t *) dst->op_params)[1];
  8558. const int mode = ((int32_t *) dst->op_params)[2];
  8559. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  8560. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  8561. const float freq_base = ((float *) dst->op_params)[5];
  8562. const float freq_scale = ((float *) dst->op_params)[6];
  8563. const float ext_factor = ((float *) dst->op_params)[7];
  8564. const float attn_factor = ((float *) dst->op_params)[8];
  8565. const float beta_fast = ((float *) dst->op_params)[9];
  8566. const float beta_slow = ((float *) dst->op_params)[10];
  8567. int sections[4] {};
  8568. if (mode & GGML_ROPE_TYPE_MROPE) {
  8569. memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4);
  8570. }
  8571. const bool is_imrope = mode == GGML_ROPE_TYPE_IMROPE;
  8572. float corr_dims[2];
  8573. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8574. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  8575. uint32_t s1 = src0->nb[1] / ggml_type_size(src0->type);
  8576. uint32_t s2 = src0->nb[2] / ggml_type_size(src0->type);
  8577. uint32_t set_rows_stride = 0;
  8578. // Fused rope + view + set_rows passes the set_rows destination stride in set_rows_stride
  8579. // and overrides the dst and sets src3=row_indices
  8580. if (ctx->num_additional_fused_ops > 0) {
  8581. set_rows_stride = cgraph->nodes[node_idx + 2]->nb[1] / ggml_type_size(cgraph->nodes[node_idx + 2]->type);
  8582. src3 = cgraph->nodes[node_idx + 2]->src[1];
  8583. dst = cgraph->nodes[node_idx + 2];
  8584. }
  8585. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, src3, dst, GGML_OP_ROPE, {
  8586. (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  8587. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  8588. src2 != nullptr, (uint32_t)src0->ne[2], s1, s2,
  8589. { sections[0], sections[1], sections[2], sections[3] }, is_imrope, backprop, set_rows_stride,
  8590. }, dryrun);
  8591. }
  8592. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8593. int32_t * op_params = (int32_t *)dst->op_params;
  8594. uint32_t ncols = src0->ne[0];
  8595. uint32_t nrows = ggml_nrows(src0);
  8596. ggml_vk_op_f32<vk_op_argsort_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ARGSORT, {
  8597. ncols,
  8598. nrows,
  8599. op_params[0],
  8600. }, dryrun);
  8601. }
  8602. static void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8603. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, ggml_nelements(src0));
  8604. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM, p, dryrun);
  8605. }
  8606. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8607. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8608. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, p, dryrun);
  8609. }
  8610. static void ggml_vk_mean(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8611. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8612. p.weight = 1.0f / (float)src0->ne[0];
  8613. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_MEAN, p, dryrun);
  8614. }
  8615. static void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8616. 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 }, dryrun);
  8617. }
  8618. 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, bool dryrun = false) {
  8619. 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 }, dryrun);
  8620. }
  8621. static void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8622. const int32_t s0 = dst->op_params[0];
  8623. const int32_t s1 = dst->op_params[1];
  8624. const int32_t p0 = dst->op_params[2];
  8625. const int32_t p1 = dst->op_params[3];
  8626. const int32_t d0 = dst->op_params[4];
  8627. const int32_t d1 = dst->op_params[5];
  8628. const bool is_2D = dst->op_params[6] == 1;
  8629. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  8630. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  8631. const uint32_t IW = src1->ne[0];
  8632. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  8633. const uint32_t KW = src0->ne[0];
  8634. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  8635. const uint32_t OW = dst->ne[1];
  8636. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  8637. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  8638. const uint32_t pelements = OW * KW * KH;
  8639. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8640. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  8641. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  8642. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL, {
  8643. dst_addr,
  8644. batch_offset, offset_delta,
  8645. IC, IW, IH, OW, OH, KW, KH,
  8646. pelements,
  8647. IC * KH * KW,
  8648. s0, s1, p0, p1, d0, d1,
  8649. }, dryrun);
  8650. }
  8651. 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, bool dryrun = false) {
  8652. GGML_TENSOR_BINARY_OP_LOCALS
  8653. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  8654. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  8655. const int32_t s2 = ((const int32_t *)(dst->op_params))[2];
  8656. const int32_t p0 = ((const int32_t *)(dst->op_params))[3];
  8657. const int32_t p1 = ((const int32_t *)(dst->op_params))[4];
  8658. const int32_t p2 = ((const int32_t *)(dst->op_params))[5];
  8659. const int32_t d0 = ((const int32_t *)(dst->op_params))[6];
  8660. const int32_t d1 = ((const int32_t *)(dst->op_params))[7];
  8661. const int32_t d2 = ((const int32_t *)(dst->op_params))[8];
  8662. const int32_t IC = ((const int32_t *)(dst->op_params))[9];
  8663. const int64_t N = ne13 / IC;
  8664. const int64_t ID = ne12;
  8665. const int64_t IH = ne11;
  8666. const int64_t IW = ne10;
  8667. const int64_t KD = ne02;
  8668. const int64_t KH = ne01;
  8669. const int64_t KW = ne00;
  8670. const int64_t OD = ne3 / N;
  8671. const int64_t OH = ne2;
  8672. const int64_t OW = ne1;
  8673. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8674. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  8675. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  8676. vk_op_im2col_3d_push_constants pc {};
  8677. pc.dst_addr = dst_addr;
  8678. pc.nb10 = nb10 / ggml_type_size(src1->type);
  8679. pc.nb11 = nb11 / ggml_type_size(src1->type);
  8680. pc.nb12 = nb12 / ggml_type_size(src1->type);
  8681. pc.nb13 = nb13 / ggml_type_size(src1->type);
  8682. pc.s0 = s0;
  8683. pc.s1 = s1;
  8684. pc.s2 = s2;
  8685. pc.p0 = p0;
  8686. pc.p1 = p1;
  8687. pc.p2 = p2;
  8688. pc.d0 = d0;
  8689. pc.d1 = d1;
  8690. pc.d2 = d2;
  8691. pc.IW = IW;
  8692. pc.IH = IH;
  8693. pc.ID = ID;
  8694. pc.IC = IC;
  8695. pc.KW = KW;
  8696. pc.OH = OH;
  8697. pc.KD_KH_KW = KD*KH*KW;
  8698. pc.KH_KW = KH*KW;
  8699. pc.IC_KD_KH_KW = IC*KD*KH*KW;
  8700. pc.N_OD_OH = N*OD*OH;
  8701. pc.OD_OH = OD*OH;
  8702. pc.OD_OH_OW_IC_KD_KH_KW = OD*OH*OW*IC*KD*KH*KW;
  8703. pc.OH_OW_IC_KD_KH_KW = OH*OW*IC*KD*KH*KW;
  8704. pc.OW_IC_KD_KH_KW = OW*IC*KD*KH*KW;
  8705. ggml_vk_op_f32<vk_op_im2col_3d_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL_3D, std::move(pc), dryrun);
  8706. }
  8707. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8708. const uint32_t dim = dst->op_params[0];
  8709. const uint32_t max_period = dst->op_params[1];
  8710. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  8711. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  8712. nb1, dim, max_period,
  8713. }, dryrun);
  8714. }
  8715. 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, bool dryrun = false) {
  8716. // src0: (K, Cout, Cin, 1) -- kernel
  8717. // src1: (L, Cin, 1, 1) -- input
  8718. // dst: (*, Cout, 1, 1)
  8719. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  8720. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8721. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  8722. GGML_TENSOR_BINARY_OP_LOCALS
  8723. GGML_ASSERT(nb00 == sizeof(float));
  8724. GGML_ASSERT(nb10 == sizeof(float));
  8725. const int32_t s0 = dst->op_params[0];
  8726. vk_op_conv_transpose_1d_push_constants p{};
  8727. p.Cout = static_cast<uint32_t>(ne01);
  8728. p.Cin = static_cast<uint32_t>(ne02);
  8729. p.K = static_cast<uint32_t>(ne00);
  8730. p.L = static_cast<uint32_t>(ne10);
  8731. p.KL = static_cast<uint32_t>(ne0);
  8732. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8733. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8734. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8735. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8736. p.s0 = static_cast<uint32_t>(s0);
  8737. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p), dryrun);
  8738. }
  8739. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8740. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  8741. const int32_t k1 = dst->op_params[1];
  8742. const int32_t k0 = dst->op_params[2];
  8743. const int32_t s1 = dst->op_params[3];
  8744. const int32_t s0 = dst->op_params[4];
  8745. const int32_t p1 = dst->op_params[5];
  8746. const int32_t p0 = dst->op_params[6];
  8747. const uint32_t IH = src0->ne[1];
  8748. const uint32_t IW = src0->ne[0];
  8749. const uint32_t N = dst->ne[3];
  8750. const uint32_t OC = dst->ne[2];
  8751. const uint32_t OH = dst->ne[1];
  8752. const uint32_t OW = dst->ne[0];
  8753. const uint32_t parallel_elements = N * OC * OH * OW;
  8754. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  8755. IW, IH, OW, OH, OC,
  8756. parallel_elements,
  8757. op,
  8758. k0, k1, s0, s1, p0, p1,
  8759. }, dryrun);
  8760. }
  8761. static void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8762. const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8763. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8764. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8765. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8766. GGML_TENSOR_BINARY_OP_LOCALS
  8767. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8768. GGML_ASSERT(nb10 == sizeof(float));
  8769. GGML_ASSERT(nb0 == sizeof(float));
  8770. vk_op_conv2d_push_constants p{};
  8771. p.Cout = static_cast<uint32_t>(ne03);
  8772. p.Cin = static_cast<uint32_t>(ne02);
  8773. p.N = static_cast<uint32_t>(ne13);
  8774. p.KW = static_cast<uint32_t>(ne00);
  8775. p.KH = static_cast<uint32_t>(ne01);
  8776. p.W = static_cast<uint32_t>(ne10);
  8777. p.H = static_cast<uint32_t>(ne11);
  8778. p.OW = static_cast<uint32_t>(ne0);
  8779. p.OH = static_cast<uint32_t>(ne1);
  8780. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8781. p.s1 = static_cast<uint32_t>(dst->op_params[1]);
  8782. p.p0 = static_cast<uint32_t>(dst->op_params[2]);
  8783. p.p1 = static_cast<uint32_t>(dst->op_params[3]);
  8784. p.d0 = static_cast<uint32_t>(dst->op_params[4]);
  8785. p.d1 = static_cast<uint32_t>(dst->op_params[5]);
  8786. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8787. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8788. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  8789. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8790. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  8791. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  8792. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8793. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  8794. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  8795. GGML_ASSERT(ne03 == ne2);
  8796. GGML_ASSERT(ne02 == ne12);
  8797. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D, std::move(p), dryrun);
  8798. }
  8799. static void ggml_vk_conv_transpose_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8800. const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8801. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8802. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8803. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8804. GGML_TENSOR_BINARY_OP_LOCALS
  8805. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8806. GGML_ASSERT(nb10 == sizeof(float));
  8807. GGML_ASSERT(nb0 == sizeof(float));
  8808. vk_op_conv_transpose_2d_push_constants p{};
  8809. p.Cout = static_cast<uint32_t>(ne02);
  8810. p.Cin = static_cast<uint32_t>(ne03);
  8811. p.N = static_cast<uint32_t>(ne13);
  8812. p.KW = static_cast<uint32_t>(ne00);
  8813. p.KH = static_cast<uint32_t>(ne01);
  8814. p.W = static_cast<uint32_t>(ne10);
  8815. p.H = static_cast<uint32_t>(ne11);
  8816. p.OW = static_cast<uint32_t>(ne0);
  8817. p.OH = static_cast<uint32_t>(ne1);
  8818. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8819. p.s1 = static_cast<uint32_t>(dst->op_params[0]);
  8820. p.p0 = 0;
  8821. p.p1 = 0;
  8822. p.d0 = 1;
  8823. p.d1 = 1;
  8824. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8825. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8826. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  8827. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8828. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  8829. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  8830. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8831. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  8832. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  8833. GGML_ASSERT(ne02 == ne2);
  8834. GGML_ASSERT(ne03 == ne12);
  8835. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_2D, std::move(p), dryrun);
  8836. }
  8837. 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, bool dryrun = false) {
  8838. vk_op_conv2d_dw_push_constants p{};
  8839. p.ne = ggml_nelements(dst);
  8840. p.channels = dst->ne[2];
  8841. p.batches = dst->ne[3];
  8842. p.dst_w = dst->ne[0];
  8843. p.dst_h = dst->ne[1];
  8844. p.src_w = src1->ne[0];
  8845. p.src_h = src1->ne[1];
  8846. p.knl_w = src0->ne[0];
  8847. p.knl_h = src0->ne[1];
  8848. p.stride_x = dst->op_params[0];
  8849. p.stride_y = dst->op_params[1];
  8850. p.pad_x = dst->op_params[2];
  8851. p.pad_y = dst->op_params[3];
  8852. p.dilation_x = dst->op_params[4];
  8853. p.dilation_y = dst->op_params[5];
  8854. GGML_ASSERT(src0->ne[3] == p.channels);
  8855. GGML_ASSERT(src1->ne[3] == p.batches);
  8856. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p), dryrun);
  8857. }
  8858. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8859. const float * op_params = (const float *)dst->op_params;
  8860. 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 }, dryrun);
  8861. }
  8862. #ifdef GGML_VULKAN_RUN_TESTS
  8863. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  8864. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  8865. return;
  8866. }
  8867. i0 = std::max(i0, 5);
  8868. i1 = std::max(i1, 5);
  8869. i2 = std::max(i2, 0);
  8870. fprintf(stderr, " ");
  8871. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8872. fprintf(stderr, "%7d ", idx1);
  8873. }
  8874. fprintf(stderr, "\n");
  8875. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  8876. fprintf(stderr, "%7d: ", idx0);
  8877. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8878. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  8879. float val;
  8880. if (type == GGML_TYPE_F32) {
  8881. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  8882. } else if (type == GGML_TYPE_F16) {
  8883. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  8884. } else {
  8885. GGML_ABORT("fatal error");
  8886. }
  8887. fprintf(stderr, "% 7.2f ", val);
  8888. } else {
  8889. fprintf(stderr, " ");
  8890. }
  8891. }
  8892. fprintf(stderr, "\n");
  8893. }
  8894. }
  8895. template <typename X_TYPE, typename Y_TYPE>
  8896. 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) {
  8897. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  8898. const size_t x_ne = m * k * batch;
  8899. const size_t y_ne = k * n * batch;
  8900. const size_t d_ne = m * n * batch;
  8901. vk_pipeline p;
  8902. std::string shname;
  8903. if (shader_size == 0) {
  8904. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8905. p = ctx->device->pipeline_matmul_f32->a_s;
  8906. shname = "F32_ALIGNED_S";
  8907. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8908. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  8909. shname = "F32_F16_ALIGNED_S";
  8910. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8911. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  8912. shname = "F16_F32_ALIGNED_S";
  8913. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8914. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  8915. shname = "F16_ALIGNED_S";
  8916. } else {
  8917. GGML_ABORT("fatal error");
  8918. }
  8919. } else if (shader_size == 1) {
  8920. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8921. p = ctx->device->pipeline_matmul_f32->a_m;
  8922. shname = "F32_ALIGNED_M";
  8923. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8924. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  8925. shname = "F32_F16_ALIGNED_M";
  8926. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8927. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  8928. shname = "F16_F32_ALIGNED_M";
  8929. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8930. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  8931. shname = "F16_ALIGNED_M";
  8932. } else {
  8933. GGML_ABORT("fatal error");
  8934. }
  8935. } else if (shader_size == 2) {
  8936. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8937. p = ctx->device->pipeline_matmul_f32->a_l;
  8938. shname = "F32_ALIGNED_L";
  8939. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8940. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  8941. shname = "F32_F16_ALIGNED_L";
  8942. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8943. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  8944. shname = "F16_F32_ALIGNED_L";
  8945. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8946. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  8947. shname = "F16_ALIGNED_L";
  8948. } else {
  8949. GGML_ABORT("fatal error");
  8950. }
  8951. } else {
  8952. GGML_ASSERT(0);
  8953. }
  8954. const size_t kpad = ggml_vk_align_size(k, p->align);
  8955. if (k != kpad) {
  8956. if (shader_size == 0) {
  8957. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8958. p = ctx->device->pipeline_matmul_f32->s;
  8959. shname = "F32_S";
  8960. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8961. p = ctx->device->pipeline_matmul_f32_f16->s;
  8962. shname = "F32_F16_S";
  8963. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8964. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  8965. shname = "F16_F32_S";
  8966. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8967. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  8968. shname = "F16_S";
  8969. }
  8970. } else if (shader_size == 1) {
  8971. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8972. p = ctx->device->pipeline_matmul_f32->m;
  8973. shname = "F32_M";
  8974. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8975. p = ctx->device->pipeline_matmul_f32_f16->m;
  8976. shname = "F32_F16_M";
  8977. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8978. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  8979. shname = "F16_F32_M";
  8980. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8981. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  8982. shname = "F16_M";
  8983. }
  8984. } else if (shader_size == 2) {
  8985. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8986. p = ctx->device->pipeline_matmul_f32->l;
  8987. shname = "F32_L";
  8988. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8989. p = ctx->device->pipeline_matmul_f32_f16->l;
  8990. shname = "F32_F16_L";
  8991. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8992. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  8993. shname = "F16_F32_L";
  8994. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8995. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  8996. shname = "F16_L";
  8997. }
  8998. }
  8999. }
  9000. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9001. if (split_k > 1) {
  9002. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9003. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9004. // Resize buffer
  9005. if (ctx->prealloc_split_k != nullptr) {
  9006. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9007. }
  9008. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9009. }
  9010. }
  9011. if (ctx->device->need_compiles) {
  9012. ggml_vk_load_shaders(ctx->device);
  9013. }
  9014. ggml_pipeline_allocate_descriptor_sets(ctx);
  9015. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9016. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9017. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9018. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  9019. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  9020. float* d = (float *) malloc(sizeof(float) * d_ne);
  9021. for (size_t i = 0; i < x_ne; i++) {
  9022. if (std::is_same<float, X_TYPE>()) {
  9023. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9024. // x[i] = 1.0f;
  9025. // x[i] = i + 1;
  9026. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9027. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9028. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9029. // x[i] = ggml_fp32_to_fp16(1.0f);
  9030. // x[i] = ggml_fp32_to_fp16(i + 1);
  9031. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9032. } else {
  9033. GGML_ABORT("fatal error");
  9034. }
  9035. }
  9036. for (size_t i = 0; i < y_ne; i++) {
  9037. if (std::is_same<float, Y_TYPE>()) {
  9038. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9039. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9040. // y[i] = i + 1;
  9041. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9042. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9043. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9044. // y[i] = ggml_fp32_to_fp16(i + 1);
  9045. } else {
  9046. GGML_ABORT("fatal error");
  9047. }
  9048. }
  9049. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  9050. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  9051. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9052. ggml_vk_ctx_begin(ctx->device, subctx);
  9053. for (size_t i = 0; i < num_it; i++) {
  9054. ggml_vk_matmul(
  9055. 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),
  9056. m, n, k,
  9057. k, k, m, k*m, k*n, m*n,
  9058. split_k, batch, batch, batch, 1, 1, n
  9059. );
  9060. }
  9061. ggml_vk_ctx_end(subctx);
  9062. auto begin = std::chrono::high_resolution_clock::now();
  9063. ggml_vk_submit(subctx, ctx->fence);
  9064. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  9065. ctx->device->device.resetFences({ ctx->fence });
  9066. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9067. auto end = std::chrono::high_resolution_clock::now();
  9068. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9069. // copy dst to host
  9070. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  9071. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  9072. ggml_init_params iparams = {
  9073. /*.mem_size =*/ 1024*1024*1024,
  9074. /*.mem_buffer =*/ NULL,
  9075. /*.no_alloc =*/ true,
  9076. };
  9077. ggml_context * ggml_ctx = ggml_init(iparams);
  9078. ggml_type src0_type;
  9079. ggml_type src1_type;
  9080. if (std::is_same<float, X_TYPE>()) {
  9081. src0_type = GGML_TYPE_F32;
  9082. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9083. src0_type = GGML_TYPE_F16;
  9084. } else {
  9085. GGML_ABORT("fatal error");
  9086. }
  9087. if (std::is_same<float, Y_TYPE>()) {
  9088. src1_type = GGML_TYPE_F32;
  9089. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9090. src1_type = GGML_TYPE_F16;
  9091. } else {
  9092. GGML_ABORT("fatal error");
  9093. }
  9094. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  9095. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  9096. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9097. src0_ggml->data = x;
  9098. src1_ggml->data = y;
  9099. tensor_ggml->data = d_chk;
  9100. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9101. ggml_build_forward_expand(cgraph, tensor_ggml);
  9102. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9103. ggml_free(ggml_ctx);
  9104. double avg_err = 0.0;
  9105. int first_err_n = -1;
  9106. int first_err_m = -1;
  9107. int first_err_b = -1;
  9108. for (size_t i = 0; i < m*n*batch; i++) {
  9109. double err = std::fabs(d[i] - d_chk[i]);
  9110. avg_err += err;
  9111. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9112. first_err_b = i / (m * n);
  9113. first_err_n = (i % (m * n)) / m;
  9114. first_err_m = (i % (m * n)) % m;
  9115. }
  9116. }
  9117. avg_err /= m * n;
  9118. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9119. 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;
  9120. if (avg_err > 0.1 || std::isnan(avg_err)) {
  9121. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9122. std::cerr << "Actual result: " << std::endl << std::endl;
  9123. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9124. std::cerr << "Expected result: " << std::endl << std::endl;
  9125. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9126. if (split_k > 1) {
  9127. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9128. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9129. std::cerr << "d_buf0: " << std::endl << std::endl;
  9130. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9131. std::cerr << "d_buf1: " << std::endl << std::endl;
  9132. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9133. std::cerr << "d_buf2: " << std::endl << std::endl;
  9134. 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);
  9135. std::cerr << "d_buf3: " << std::endl << std::endl;
  9136. 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);
  9137. free(split_k_buf);
  9138. }
  9139. }
  9140. free(d_chk);
  9141. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  9142. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  9143. ggml_vk_destroy_buffer(d_X);
  9144. ggml_vk_destroy_buffer(d_Y);
  9145. ggml_vk_destroy_buffer(d_D);
  9146. free(x);
  9147. free(y);
  9148. free(d);
  9149. }
  9150. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  9151. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  9152. return;
  9153. }
  9154. i0 = std::max(i0, 5);
  9155. i1 = std::max(i1, 5);
  9156. i2 = std::max(i2, 0);
  9157. i3 = std::max(i3, 0);
  9158. fprintf(stderr, " ");
  9159. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9160. fprintf(stderr, "%7d ", idx1);
  9161. }
  9162. fprintf(stderr, "\n");
  9163. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9164. fprintf(stderr, "%7d: ", idx0);
  9165. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9166. 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]) {
  9167. float val;
  9168. if (tensor->type == GGML_TYPE_F32) {
  9169. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  9170. } else if (tensor->type == GGML_TYPE_F16) {
  9171. 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]));
  9172. } else {
  9173. GGML_ABORT("fatal error");
  9174. }
  9175. fprintf(stderr, "% 7.2f ", val);
  9176. } else {
  9177. fprintf(stderr, " ");
  9178. }
  9179. }
  9180. fprintf(stderr, "\n");
  9181. }
  9182. }
  9183. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  9184. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  9185. }
  9186. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  9187. if (quant == GGML_TYPE_F32) {
  9188. memcpy(to, from, sizeof(float) * ne);
  9189. return;
  9190. }
  9191. const auto * tt = ggml_get_type_traits(quant);
  9192. ggml_to_float_t dequant_fn = tt->to_float;
  9193. dequant_fn(from, to, ne);
  9194. }
  9195. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9196. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  9197. const size_t x_sz = sizeof(float) * ne;
  9198. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  9199. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9200. float * x = (float *) malloc(x_sz);
  9201. void * qx = malloc(qx_sz);
  9202. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9203. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9204. float * x_ref = (float *) malloc(x_sz);
  9205. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  9206. for (size_t i = 0; i < ne; i++) {
  9207. x[i] = rand() / (float)RAND_MAX;
  9208. }
  9209. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  9210. ggml_vk_quantize_data(x, qx, ne, quant);
  9211. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  9212. ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9213. if (ctx->device->need_compiles) {
  9214. ggml_vk_load_shaders(ctx->device);
  9215. }
  9216. ggml_pipeline_allocate_descriptor_sets(ctx);
  9217. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9218. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9219. ggml_vk_ctx_begin(ctx->device, subctx);
  9220. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  9221. 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});
  9222. ggml_vk_ctx_end(subctx);
  9223. auto begin = std::chrono::high_resolution_clock::now();
  9224. ggml_vk_submit(subctx, ctx->fence);
  9225. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9226. ctx->device->device.resetFences({ ctx->fence });
  9227. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9228. auto end = std::chrono::high_resolution_clock::now();
  9229. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9230. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  9231. int first_err = -1;
  9232. double avg_err = 0.0;
  9233. for (size_t i = 0; i < ne; i++) {
  9234. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  9235. avg_err += error;
  9236. if (first_err < 0 && error > 0.05) {
  9237. first_err = i;
  9238. }
  9239. }
  9240. avg_err /= ne;
  9241. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  9242. if (avg_err > 0.1) {
  9243. std::cerr << "first_error = " << first_err << std::endl;
  9244. std::cerr << "Actual result: " << std::endl << std::endl;
  9245. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9246. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  9247. }
  9248. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  9249. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9250. std::cerr << x_ref[i] << ", ";
  9251. }
  9252. std::cerr << std::endl;
  9253. }
  9254. ggml_vk_destroy_buffer(x_buf);
  9255. ggml_vk_destroy_buffer(qx_buf);
  9256. free(x);
  9257. free(qx);
  9258. free(x_ref);
  9259. free(x_chk);
  9260. }
  9261. // This does not work without ggml q8_1 quantization support
  9262. //
  9263. // typedef uint16_t ggml_half;
  9264. // typedef uint32_t ggml_half2;
  9265. //
  9266. // #define QK8_1 32
  9267. // typedef struct {
  9268. // union {
  9269. // struct {
  9270. // ggml_half d; // delta
  9271. // ggml_half s; // d * sum(qs[i])
  9272. // } GGML_COMMON_AGGR_S;
  9273. // ggml_half2 ds;
  9274. // } GGML_COMMON_AGGR_U;
  9275. // int8_t qs[QK8_1]; // quants
  9276. // } block_q8_1;
  9277. //
  9278. // static void ggml_vk_test_quantize(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9279. // VK_LOG_DEBUG("ggml_vk_test_quantize(" << ne << ")");
  9280. // GGML_ASSERT(quant == GGML_TYPE_Q8_1);
  9281. //
  9282. // const size_t x_sz = sizeof(float) * ne;
  9283. // const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9284. // float * x = (float *) malloc(x_sz);
  9285. // block_q8_1 * qx = (block_q8_1 *)malloc(qx_sz);
  9286. // block_q8_1 * qx_res = (block_q8_1 *)malloc(qx_sz);
  9287. // vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9288. // vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9289. //
  9290. // for (size_t i = 0; i < ne; i++) {
  9291. // x[i] = rand() / (float)RAND_MAX;
  9292. // }
  9293. //
  9294. // vk_pipeline p = ggml_vk_get_quantize_pipeline(ctx, quant);
  9295. //
  9296. // ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9297. //
  9298. // if (ctx->device->need_compiles) {
  9299. // ggml_vk_load_shaders(ctx->device);
  9300. // }
  9301. //
  9302. // ggml_pipeline_allocate_descriptor_sets(ctx);
  9303. //
  9304. // ggml_vk_buffer_write(x_buf, 0, x, x_sz);
  9305. //
  9306. // vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9307. // ggml_vk_ctx_begin(ctx->device, subctx);
  9308. // ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, x_buf), ggml_vk_subbuffer(ctx, qx_buf), ne);
  9309. // ggml_vk_ctx_end(subctx);
  9310. //
  9311. // auto begin = std::chrono::high_resolution_clock::now();
  9312. //
  9313. // ggml_vk_submit(subctx, ctx->fence);
  9314. // VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_quantize waitForFences");
  9315. // ctx->device->device.resetFences({ ctx->fence });
  9316. // ggml_vk_queue_command_pools_cleanup(ctx->device);
  9317. //
  9318. // auto end = std::chrono::high_resolution_clock::now();
  9319. //
  9320. // double ms_quant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9321. // ggml_vk_buffer_read(qx_buf, 0, qx, qx_sz);
  9322. //
  9323. // ggml_vk_quantize_data(x, qx_res, ne, quant);
  9324. //
  9325. // int first_err = -1;
  9326. //
  9327. // for (size_t i = 0; i < ne / 32; i++) {
  9328. // 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));
  9329. //
  9330. // if (first_err < 0 && error > 0.1) {
  9331. // first_err = i;
  9332. // }
  9333. //
  9334. // 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));
  9335. //
  9336. // if (first_err < 0 && error > 0.1) {
  9337. // first_err = i;
  9338. // }
  9339. //
  9340. // for (size_t j = 0; j < 32; j++) {
  9341. // uint64_t error = std::abs(qx_res[i].qs[j] - qx[i].qs[j]);
  9342. //
  9343. // if (first_err < 0 && error > 1) {
  9344. // first_err = i;
  9345. // }
  9346. // }
  9347. // }
  9348. //
  9349. // std::cerr << "TEST QUANTIZE " << ggml_type_name(quant) << " time=" << ms_quant << "ms " << (first_err == -1 ? "CORRECT" : "INCORRECT") << std::endl;
  9350. //
  9351. // if (first_err != -1) {
  9352. // std::cerr << "first_error = " << first_err << std::endl;
  9353. // std::cerr << "Actual result: " << std::endl << std::endl;
  9354. // 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) << " ";
  9355. // for (size_t j = 0; j < 32; j++) {
  9356. // std::cout << " qs" << j << "=" << (uint32_t)qx[first_err].qs[j] << " ";
  9357. // }
  9358. // std::cerr << std::endl << std::endl << "Expected result: " << std::endl << std::endl;
  9359. // 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) << " ";
  9360. // for (size_t j = 0; j < 32; j++) {
  9361. // std::cout << " qs" << j << "=" << (uint32_t)qx_res[first_err].qs[j] << " ";
  9362. // }
  9363. // std::cerr << std::endl;
  9364. // }
  9365. //
  9366. // ggml_vk_destroy_buffer(x_buf);
  9367. // ggml_vk_destroy_buffer(qx_buf);
  9368. //
  9369. // free(x);
  9370. // free(qx);
  9371. // free(qx_res);
  9372. // }
  9373. 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) {
  9374. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  9375. const size_t x_ne = m * k * batch;
  9376. const size_t y_ne = k * n * batch;
  9377. const size_t d_ne = m * n * batch;
  9378. vk_matmul_pipeline2 * pipelines;
  9379. if (mmq) {
  9380. pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1;
  9381. } else {
  9382. pipelines = ctx->device->pipeline_dequant_mul_mat_mat;
  9383. }
  9384. const bool fp16acc = ctx->device->fp16;
  9385. vk_pipeline p;
  9386. std::string shname;
  9387. if (shader_size == 0) {
  9388. p = fp16acc ? pipelines[quant].f16acc->a_s : pipelines[quant].f32acc->a_s;
  9389. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  9390. } else if (shader_size == 1) {
  9391. p = fp16acc ? pipelines[quant].f16acc->a_m : pipelines[quant].f32acc->a_m;
  9392. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  9393. } else if (shader_size == 2) {
  9394. p = fp16acc ? pipelines[quant].f16acc->a_l : pipelines[quant].f32acc->a_l;
  9395. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  9396. } else {
  9397. GGML_ASSERT(0);
  9398. }
  9399. const size_t kpad = mmq ? 0 : ggml_vk_align_size(k, p->align);
  9400. if (mmq || k != kpad) {
  9401. if (shader_size == 0) {
  9402. p = fp16acc ? pipelines[quant].f16acc->s : pipelines[quant].f32acc->s;
  9403. shname = std::string(ggml_type_name(quant)) + "_S";
  9404. } else if (shader_size == 1) {
  9405. p = fp16acc ? pipelines[quant].f16acc->m : pipelines[quant].f32acc->m;
  9406. shname = std::string(ggml_type_name(quant)) + "_M";
  9407. } else if (shader_size == 2) {
  9408. p = fp16acc ? pipelines[quant].f16acc->l : pipelines[quant].f32acc->l;
  9409. shname = std::string(ggml_type_name(quant)) + "_L";
  9410. } else {
  9411. GGML_ASSERT(0);
  9412. }
  9413. }
  9414. if (p == nullptr) {
  9415. std::cerr << "error: no pipeline for ggml_vk_test_dequant_matmul " << ggml_type_name(quant) << std::endl;
  9416. return;
  9417. }
  9418. const size_t x_sz = sizeof(float) * x_ne;
  9419. const size_t y_sz = sizeof(float) * y_ne;
  9420. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9421. const size_t qy_sz = mmq ? y_ne * ggml_type_size(GGML_TYPE_Q8_1)/ggml_blck_size(GGML_TYPE_Q8_1) : y_sz;
  9422. const size_t d_sz = sizeof(float) * d_ne;
  9423. float * x = (float *) malloc(x_sz);
  9424. float * y = (float *) malloc(y_sz);
  9425. void * qx = malloc(qx_sz);
  9426. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9427. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9428. vk_buffer qy_buf = ggml_vk_create_buffer_check(ctx->device, qy_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9429. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9430. float * d = (float *) malloc(d_sz);
  9431. float * d_chk = (float *) malloc(d_sz);
  9432. for (size_t i = 0; i < x_ne; i++) {
  9433. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9434. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9435. // x[i] = i % k;
  9436. }
  9437. ggml_vk_quantize_data(x, qx, x_ne, quant);
  9438. for (size_t i = 0; i < y_ne; i++) {
  9439. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9440. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9441. // y[i] = i % k;
  9442. }
  9443. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9444. if (split_k > 1) {
  9445. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9446. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9447. // Resize buffer
  9448. if (ctx->prealloc_split_k != nullptr) {
  9449. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9450. }
  9451. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9452. }
  9453. }
  9454. if (mmq) {
  9455. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_quantize_q8_1, num_it);
  9456. }
  9457. if (ctx->device->need_compiles) {
  9458. ggml_vk_load_shaders(ctx->device);
  9459. }
  9460. ggml_pipeline_allocate_descriptor_sets(ctx);
  9461. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9462. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  9463. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9464. ggml_vk_ctx_begin(ctx->device, subctx);
  9465. if (mmq) {
  9466. for (size_t i = 0; i < num_it; i++) {
  9467. ggml_vk_quantize_q8_1(ctx, subctx, { y_buf, 0, y_sz }, { qy_buf, 0, qy_sz }, y_ne);
  9468. ggml_vk_matmul(
  9469. 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 },
  9470. m, n, k,
  9471. k, k, m, k*m, k*n, m*n,
  9472. split_k, batch, batch, batch, 1, 1, n
  9473. );
  9474. }
  9475. } else {
  9476. for (size_t i = 0; i < num_it; i++) {
  9477. ggml_vk_matmul(
  9478. 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 },
  9479. m, n, k,
  9480. k, k, m, k*m, k*n, m*n,
  9481. split_k, batch, batch, batch, 1, 1, n
  9482. );
  9483. }
  9484. }
  9485. ggml_vk_ctx_end(subctx);
  9486. auto begin = std::chrono::high_resolution_clock::now();
  9487. ggml_vk_submit(subctx, ctx->fence);
  9488. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9489. ctx->device->device.resetFences({ ctx->fence });
  9490. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9491. auto end = std::chrono::high_resolution_clock::now();
  9492. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9493. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  9494. ggml_init_params iparams = {
  9495. /*.mem_size =*/ 1024*1024*1024,
  9496. /*.mem_buffer =*/ NULL,
  9497. /*.no_alloc =*/ true,
  9498. };
  9499. ggml_context * ggml_ctx = ggml_init(iparams);
  9500. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  9501. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  9502. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9503. src0_ggml->data = qx;
  9504. src1_ggml->data = y;
  9505. tensor_ggml->data = d_chk;
  9506. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9507. ggml_build_forward_expand(cgraph, tensor_ggml);
  9508. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9509. ggml_free(ggml_ctx);
  9510. double avg_err = 0.0;
  9511. int first_err_n = -1;
  9512. int first_err_m = -1;
  9513. int first_err_b = -1;
  9514. for (size_t i = 0; i < m*n*batch; i++) {
  9515. double err = std::fabs(d[i] - d_chk[i]);
  9516. avg_err += err;
  9517. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9518. first_err_b = i / (m * n);
  9519. first_err_n = (i % (m * n)) / m;
  9520. first_err_m = (i % (m * n)) % m;
  9521. }
  9522. }
  9523. avg_err /= m * n;
  9524. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9525. std::cerr << "TEST dequant matmul " << shname;
  9526. if (mmq) {
  9527. std::cerr << " mmq";
  9528. }
  9529. 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;
  9530. if (avg_err > 0.01 || std::isnan(avg_err)) {
  9531. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9532. std::cerr << "Actual result: " << std::endl << std::endl;
  9533. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9534. std::cerr << std::endl;
  9535. std::cerr << "Expected result: " << std::endl << std::endl;
  9536. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9537. std::cerr << "src0: " << std::endl << std::endl;
  9538. ggml_vk_print_matrix_area(x, GGML_TYPE_F32, k, m, first_err_m, first_err_n, first_err_b);
  9539. std::cerr << std::endl;
  9540. std::cerr << "src1: " << std::endl << std::endl;
  9541. ggml_vk_print_matrix_area(y, GGML_TYPE_F32, k, n, first_err_m, first_err_n, first_err_b);
  9542. if (split_k > 1) {
  9543. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9544. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9545. std::cerr << "d_buf0: " << std::endl << std::endl;
  9546. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9547. std::cerr << "d_buf1: " << std::endl << std::endl;
  9548. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9549. std::cerr << "d_buf2: " << std::endl << std::endl;
  9550. 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);
  9551. std::cerr << "d_buf3: " << std::endl << std::endl;
  9552. 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);
  9553. free(split_k_buf);
  9554. }
  9555. }
  9556. ggml_vk_destroy_buffer(qx_buf);
  9557. ggml_vk_destroy_buffer(y_buf);
  9558. ggml_vk_destroy_buffer(qy_buf);
  9559. ggml_vk_destroy_buffer(d_buf);
  9560. free(x);
  9561. free(qx);
  9562. free(y);
  9563. free(d);
  9564. free(d_chk);
  9565. }
  9566. #endif
  9567. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx) {
  9568. #if defined(GGML_VULKAN_RUN_TESTS)
  9569. const std::vector<size_t> vals {
  9570. 512, 512, 128,
  9571. 128, 512, 512,
  9572. 4096, 512, 4096,
  9573. 11008, 512, 4096,
  9574. 4096, 512, 11008,
  9575. 32000, 512, 4096,
  9576. 8, 8, 8,
  9577. 100, 46, 576,
  9578. 623, 111, 128,
  9579. 100, 46, 558,
  9580. 512, 1, 256,
  9581. 128, 110, 622,
  9582. 511, 511, 127,
  9583. 511, 511, 7,
  9584. 511, 511, 17,
  9585. 49, 49, 128,
  9586. 128, 49, 49,
  9587. 4096, 49, 4096,
  9588. };
  9589. const size_t num_it = 100;
  9590. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9591. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9592. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9593. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true);
  9594. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true);
  9595. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true);
  9596. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0);
  9597. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0);
  9598. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0);
  9599. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true);
  9600. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true);
  9601. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true);
  9602. abort();
  9603. for (size_t i = 0; i < vals.size(); i += 3) {
  9604. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  9605. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  9606. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  9607. std::cerr << '\n';
  9608. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  9609. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  9610. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  9611. std::cerr << '\n';
  9612. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  9613. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  9614. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  9615. std::cerr << '\n' << std::endl;
  9616. if (vals[i + 2] % 32 == 0) {
  9617. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9618. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9619. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9620. std::cerr << '\n';
  9621. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  9622. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  9623. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  9624. std::cerr << '\n';
  9625. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  9626. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  9627. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  9628. std::cerr << '\n' << std::endl;
  9629. }
  9630. if (vals[i + 2] % 256 == 0) {
  9631. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  9632. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  9633. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  9634. std::cerr << '\n';
  9635. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  9636. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  9637. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  9638. std::cerr << '\n';
  9639. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  9640. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  9641. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  9642. std::cerr << '\n' << std::endl;
  9643. }
  9644. }
  9645. GGML_ABORT("fatal error");
  9646. #endif
  9647. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  9648. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  9649. // Resize buffer
  9650. if (ctx->prealloc_x != nullptr) {
  9651. ggml_vk_destroy_buffer(ctx->prealloc_x);
  9652. }
  9653. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  9654. }
  9655. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  9656. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  9657. // Resize buffer
  9658. if (ctx->prealloc_y != nullptr) {
  9659. ggml_vk_destroy_buffer(ctx->prealloc_y);
  9660. }
  9661. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  9662. }
  9663. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  9664. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  9665. // Resize buffer
  9666. if (ctx->prealloc_split_k != nullptr) {
  9667. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9668. }
  9669. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  9670. }
  9671. 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)) {
  9672. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")");
  9673. // Resize buffer
  9674. if (ctx->prealloc_add_rms_partials != nullptr) {
  9675. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  9676. }
  9677. ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials);
  9678. }
  9679. }
  9680. static bool ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_cgraph * cgraph, ggml_tensor* tensor, int tensor_idx, bool use_fence, bool almost_ready);
  9681. // Returns true if node has enqueued work into the queue, false otherwise
  9682. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  9683. 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 dryrun, bool last_node, bool almost_ready, bool submit){
  9684. ggml_tensor * node = cgraph->nodes[node_idx];
  9685. if (ggml_is_empty(node) || !node->buffer) {
  9686. return false;
  9687. }
  9688. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  9689. ctx->semaphore_idx = 0;
  9690. ggml_tensor * src0 = node->src[0];
  9691. ggml_tensor * src1 = node->src[1];
  9692. ggml_tensor * src2 = node->src[2];
  9693. ggml_tensor * src3 = node->src[3];
  9694. switch (node->op) {
  9695. // Return on empty ops to avoid generating a compute_ctx and setting exit_tensor
  9696. case GGML_OP_RESHAPE:
  9697. case GGML_OP_VIEW:
  9698. case GGML_OP_PERMUTE:
  9699. case GGML_OP_TRANSPOSE:
  9700. case GGML_OP_NONE:
  9701. return false;
  9702. case GGML_OP_UNARY:
  9703. switch (ggml_get_unary_op(node)) {
  9704. case GGML_UNARY_OP_EXP:
  9705. case GGML_UNARY_OP_SILU:
  9706. case GGML_UNARY_OP_GELU:
  9707. case GGML_UNARY_OP_GELU_ERF:
  9708. case GGML_UNARY_OP_GELU_QUICK:
  9709. case GGML_UNARY_OP_RELU:
  9710. case GGML_UNARY_OP_TANH:
  9711. case GGML_UNARY_OP_SIGMOID:
  9712. case GGML_UNARY_OP_HARDSIGMOID:
  9713. case GGML_UNARY_OP_HARDSWISH:
  9714. break;
  9715. default:
  9716. return false;
  9717. }
  9718. break;
  9719. case GGML_OP_GLU:
  9720. switch (ggml_get_glu_op(node)) {
  9721. case GGML_GLU_OP_GEGLU:
  9722. case GGML_GLU_OP_REGLU:
  9723. case GGML_GLU_OP_SWIGLU:
  9724. case GGML_GLU_OP_SWIGLU_OAI:
  9725. case GGML_GLU_OP_GEGLU_ERF:
  9726. case GGML_GLU_OP_GEGLU_QUICK:
  9727. break;
  9728. default:
  9729. return false;
  9730. }
  9731. break;
  9732. case GGML_OP_ADD:
  9733. {
  9734. int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops;
  9735. if (next_node_idx < cgraph->n_nodes &&
  9736. cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM &&
  9737. cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] &&
  9738. ggml_nrows(cgraph->nodes[next_node_idx]) == 1 &&
  9739. ctx->device->add_rms_fusion) {
  9740. if (dryrun) {
  9741. ctx->prealloc_size_add_rms_partials += ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]);
  9742. }
  9743. ctx->do_add_rms_partials = true;
  9744. }
  9745. } break;
  9746. case GGML_OP_REPEAT:
  9747. case GGML_OP_REPEAT_BACK:
  9748. case GGML_OP_GET_ROWS:
  9749. case GGML_OP_ADD_ID:
  9750. case GGML_OP_ACC:
  9751. case GGML_OP_SUB:
  9752. case GGML_OP_MUL:
  9753. case GGML_OP_DIV:
  9754. case GGML_OP_CONCAT:
  9755. case GGML_OP_UPSCALE:
  9756. case GGML_OP_SCALE:
  9757. case GGML_OP_SQR:
  9758. case GGML_OP_SQRT:
  9759. case GGML_OP_SIN:
  9760. case GGML_OP_COS:
  9761. case GGML_OP_CLAMP:
  9762. case GGML_OP_PAD:
  9763. case GGML_OP_ROLL:
  9764. case GGML_OP_CPY:
  9765. case GGML_OP_SET_ROWS:
  9766. case GGML_OP_CONT:
  9767. case GGML_OP_DUP:
  9768. case GGML_OP_SILU_BACK:
  9769. case GGML_OP_NORM:
  9770. case GGML_OP_GROUP_NORM:
  9771. case GGML_OP_RMS_NORM:
  9772. case GGML_OP_RMS_NORM_BACK:
  9773. case GGML_OP_L2_NORM:
  9774. case GGML_OP_DIAG_MASK_INF:
  9775. case GGML_OP_SOFT_MAX:
  9776. case GGML_OP_SOFT_MAX_BACK:
  9777. case GGML_OP_ROPE:
  9778. case GGML_OP_ROPE_BACK:
  9779. case GGML_OP_MUL_MAT:
  9780. case GGML_OP_MUL_MAT_ID:
  9781. case GGML_OP_ARGSORT:
  9782. case GGML_OP_SUM:
  9783. case GGML_OP_SUM_ROWS:
  9784. case GGML_OP_MEAN:
  9785. case GGML_OP_ARGMAX:
  9786. case GGML_OP_COUNT_EQUAL:
  9787. case GGML_OP_IM2COL:
  9788. case GGML_OP_IM2COL_3D:
  9789. case GGML_OP_TIMESTEP_EMBEDDING:
  9790. case GGML_OP_CONV_TRANSPOSE_1D:
  9791. case GGML_OP_POOL_2D:
  9792. case GGML_OP_CONV_2D:
  9793. case GGML_OP_CONV_TRANSPOSE_2D:
  9794. case GGML_OP_CONV_2D_DW:
  9795. case GGML_OP_RWKV_WKV6:
  9796. case GGML_OP_RWKV_WKV7:
  9797. case GGML_OP_SSM_SCAN:
  9798. case GGML_OP_SSM_CONV:
  9799. case GGML_OP_LEAKY_RELU:
  9800. case GGML_OP_FLASH_ATTN_EXT:
  9801. case GGML_OP_OPT_STEP_ADAMW:
  9802. case GGML_OP_OPT_STEP_SGD:
  9803. break;
  9804. default:
  9805. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(node->op) << std::endl;
  9806. GGML_ABORT("fatal error");
  9807. }
  9808. vk_context compute_ctx;
  9809. if (!dryrun) {
  9810. if (ctx->compute_ctx.expired()) {
  9811. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9812. ctx->compute_ctx = compute_ctx;
  9813. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  9814. } else {
  9815. compute_ctx = ctx->compute_ctx.lock();
  9816. }
  9817. } else {
  9818. switch (node->op) {
  9819. case GGML_OP_REPEAT:
  9820. case GGML_OP_REPEAT_BACK:
  9821. case GGML_OP_ACC:
  9822. case GGML_OP_GET_ROWS:
  9823. case GGML_OP_ADD:
  9824. case GGML_OP_SUB:
  9825. case GGML_OP_MUL:
  9826. case GGML_OP_DIV:
  9827. case GGML_OP_CONCAT:
  9828. case GGML_OP_UPSCALE:
  9829. case GGML_OP_SCALE:
  9830. case GGML_OP_SQR:
  9831. case GGML_OP_SQRT:
  9832. case GGML_OP_SIN:
  9833. case GGML_OP_COS:
  9834. case GGML_OP_CLAMP:
  9835. case GGML_OP_PAD:
  9836. case GGML_OP_CPY:
  9837. case GGML_OP_SET_ROWS:
  9838. case GGML_OP_CONT:
  9839. case GGML_OP_DUP:
  9840. case GGML_OP_SILU_BACK:
  9841. case GGML_OP_NORM:
  9842. case GGML_OP_GROUP_NORM:
  9843. case GGML_OP_RMS_NORM:
  9844. case GGML_OP_RMS_NORM_BACK:
  9845. case GGML_OP_L2_NORM:
  9846. case GGML_OP_UNARY:
  9847. case GGML_OP_GLU:
  9848. case GGML_OP_DIAG_MASK_INF:
  9849. case GGML_OP_SOFT_MAX:
  9850. case GGML_OP_SOFT_MAX_BACK:
  9851. case GGML_OP_ROPE_BACK:
  9852. case GGML_OP_ARGSORT:
  9853. case GGML_OP_SUM:
  9854. case GGML_OP_SUM_ROWS:
  9855. case GGML_OP_MEAN:
  9856. case GGML_OP_ARGMAX:
  9857. case GGML_OP_COUNT_EQUAL:
  9858. case GGML_OP_IM2COL:
  9859. case GGML_OP_IM2COL_3D:
  9860. case GGML_OP_TIMESTEP_EMBEDDING:
  9861. case GGML_OP_CONV_TRANSPOSE_1D:
  9862. case GGML_OP_POOL_2D:
  9863. case GGML_OP_CONV_2D:
  9864. case GGML_OP_CONV_TRANSPOSE_2D:
  9865. case GGML_OP_CONV_2D_DW:
  9866. case GGML_OP_LEAKY_RELU:
  9867. case GGML_OP_OPT_STEP_SGD:
  9868. {
  9869. // These operations all go through ggml_vk_op_f32, so short-circuit and
  9870. // do the only thing needed for the dryrun.
  9871. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, node, node->op);
  9872. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9873. if (node->op == GGML_OP_RMS_NORM) {
  9874. ctx->do_add_rms_partials = false;
  9875. }
  9876. return false;
  9877. }
  9878. default:
  9879. break;
  9880. }
  9881. }
  9882. if (!dryrun) {
  9883. // This logic detects dependencies between modes in the graph and calls ggml_vk_sync_buffers
  9884. // to synchronize them. This handles most "normal" synchronization when computing the graph, and when
  9885. // there is no auxiliary memory use, it shouldn't be necessary to call ggml_vk_sync_buffers
  9886. // outside of this logic. When a node uses one of the prealloc buffers for something like
  9887. // dequantization or split_k, additional synchronization is needed between those passes.
  9888. bool need_sync = false;
  9889. // Check whether "node" requires synchronization. The node requires synchronization if it
  9890. // overlaps in memory with another unsynchronized node and at least one of them is a write.
  9891. // Destination nodes are checked against both the written/read lists. Source nodes are only
  9892. // checked against the written list. Two nodes overlap in memory if they come from the same
  9893. // buffer and the tensor or view ranges overlap.
  9894. auto const &overlaps_unsynced = [&](const ggml_tensor *node, const std::vector<const ggml_tensor *> &unsynced_nodes) -> bool {
  9895. if (unsynced_nodes.size() == 0) {
  9896. return false;
  9897. }
  9898. auto n_base = vk_tensor_offset(node) + node->view_offs;
  9899. auto n_size = ggml_nbytes(node);
  9900. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context;
  9901. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  9902. for (auto &other : unsynced_nodes) {
  9903. ggml_backend_vk_buffer_context * o_buf_ctx = (ggml_backend_vk_buffer_context *)other->buffer->context;
  9904. vk_buffer o_buf = o_buf_ctx->dev_buffer;
  9905. if (a_buf == o_buf) {
  9906. auto o_base = vk_tensor_offset(other) + other->view_offs;
  9907. auto o_size = ggml_nbytes(other);
  9908. if ((o_base <= n_base && n_base < o_base + o_size) ||
  9909. (n_base <= o_base && o_base < n_base + n_size)) {
  9910. return true;
  9911. }
  9912. }
  9913. }
  9914. return false;
  9915. };
  9916. // For all fused ops, check if the destination node or any of the source
  9917. // nodes require synchronization.
  9918. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) {
  9919. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  9920. // If the node actually writes to memory, then check if it needs to sync
  9921. if (ctx->fused_ops_write_mask & (1 << i)) {
  9922. if (overlaps_unsynced(cur_node, ctx->unsynced_nodes_read) || overlaps_unsynced(cur_node, ctx->unsynced_nodes_written)) {
  9923. need_sync = true;
  9924. break;
  9925. }
  9926. }
  9927. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  9928. if (!cur_node->src[j]) {
  9929. continue;
  9930. }
  9931. if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) {
  9932. need_sync = true;
  9933. break;
  9934. }
  9935. }
  9936. }
  9937. #define ENABLE_SYNC_LOGGING 0
  9938. if (need_sync) {
  9939. #if ENABLE_SYNC_LOGGING
  9940. std::cerr << "sync" << std::endl;
  9941. #endif
  9942. ctx->unsynced_nodes_written.clear();
  9943. ctx->unsynced_nodes_read.clear();
  9944. ggml_vk_sync_buffers(ctx, compute_ctx);
  9945. }
  9946. // Add all fused nodes to the unsynchronized lists.
  9947. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  9948. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  9949. // Multiple outputs could be written, e.g. in topk_moe. Add them all to the list.
  9950. if (ctx->fused_ops_write_mask & (1 << i)) {
  9951. ctx->unsynced_nodes_written.push_back(cur_node);
  9952. }
  9953. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  9954. if (!cur_node->src[j]) {
  9955. continue;
  9956. }
  9957. ctx->unsynced_nodes_read.push_back(cur_node->src[j]);
  9958. }
  9959. }
  9960. }
  9961. #if ENABLE_SYNC_LOGGING
  9962. if (!dryrun) {
  9963. for (int i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  9964. auto *n = cgraph->nodes[node_idx + i];
  9965. std::cerr << node_idx + i << " " << ggml_op_name(n->op) << " " << n->name;
  9966. if (n->op == GGML_OP_GLU) {
  9967. std::cerr << " " << ggml_glu_op_name(ggml_get_glu_op(n)) << " " << (n->src[1] ? "split" : "single") << " ";
  9968. }
  9969. std::cerr << std::endl;
  9970. }
  9971. }
  9972. #endif
  9973. switch (node->op) {
  9974. case GGML_OP_REPEAT:
  9975. ggml_vk_repeat(ctx, compute_ctx, src0, node, dryrun);
  9976. break;
  9977. case GGML_OP_REPEAT_BACK:
  9978. ggml_vk_repeat_back(ctx, compute_ctx, src0, node, dryrun);
  9979. break;
  9980. case GGML_OP_ACC:
  9981. ggml_vk_acc(ctx, compute_ctx, src0, src1, node, dryrun);
  9982. break;
  9983. case GGML_OP_GET_ROWS:
  9984. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node, dryrun);
  9985. break;
  9986. case GGML_OP_ADD:
  9987. if (ctx->num_additional_fused_ops) {
  9988. ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx, dryrun);
  9989. } else {
  9990. ggml_vk_add(ctx, compute_ctx, src0, src1, node, dryrun);
  9991. }
  9992. break;
  9993. case GGML_OP_SUB:
  9994. ggml_vk_sub(ctx, compute_ctx, src0, src1, node, dryrun);
  9995. break;
  9996. case GGML_OP_MUL:
  9997. ggml_vk_mul(ctx, compute_ctx, src0, src1, node, dryrun);
  9998. break;
  9999. case GGML_OP_DIV:
  10000. ggml_vk_div(ctx, compute_ctx, src0, src1, node, dryrun);
  10001. break;
  10002. case GGML_OP_ADD_ID:
  10003. ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  10004. break;
  10005. case GGML_OP_CONCAT:
  10006. ggml_vk_concat(ctx, compute_ctx, src0, src1, node, dryrun);
  10007. break;
  10008. case GGML_OP_UPSCALE:
  10009. ggml_vk_upscale(ctx, compute_ctx, src0, node, dryrun);
  10010. break;
  10011. case GGML_OP_SCALE:
  10012. ggml_vk_scale(ctx, compute_ctx, src0, node, dryrun);
  10013. break;
  10014. case GGML_OP_SQR:
  10015. ggml_vk_sqr(ctx, compute_ctx, src0, node, dryrun);
  10016. break;
  10017. case GGML_OP_SQRT:
  10018. ggml_vk_sqrt(ctx, compute_ctx, src0, node, dryrun);
  10019. break;
  10020. case GGML_OP_SIN:
  10021. ggml_vk_sin(ctx, compute_ctx, src0, node, dryrun);
  10022. break;
  10023. case GGML_OP_COS:
  10024. ggml_vk_cos(ctx, compute_ctx, src0, node, dryrun);
  10025. break;
  10026. case GGML_OP_CLAMP:
  10027. ggml_vk_clamp(ctx, compute_ctx, src0, node, dryrun);
  10028. break;
  10029. case GGML_OP_PAD:
  10030. ggml_vk_pad(ctx, compute_ctx, src0, node, dryrun);
  10031. break;
  10032. case GGML_OP_ROLL:
  10033. ggml_vk_roll(ctx, compute_ctx, src0, node, dryrun);
  10034. break;
  10035. case GGML_OP_CPY:
  10036. case GGML_OP_CONT:
  10037. case GGML_OP_DUP:
  10038. ggml_vk_cpy(ctx, compute_ctx, src0, node, dryrun);
  10039. break;
  10040. case GGML_OP_SET_ROWS:
  10041. ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node, dryrun);
  10042. break;
  10043. case GGML_OP_SILU_BACK:
  10044. ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node, dryrun);
  10045. break;
  10046. case GGML_OP_NORM:
  10047. ggml_vk_norm(ctx, compute_ctx, src0, node, dryrun);
  10048. break;
  10049. case GGML_OP_GROUP_NORM:
  10050. ggml_vk_group_norm(ctx, compute_ctx, src0, node, dryrun);
  10051. break;
  10052. case GGML_OP_RMS_NORM:
  10053. if (ctx->num_additional_fused_ops > 0) {
  10054. // fused rms_norm + mul
  10055. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10056. ggml_tensor *other_src = mul->src[0] == node ? mul->src[1] : mul->src[0];
  10057. ggml_vk_rms_norm(ctx, compute_ctx, src0, other_src, mul, (float *)node->op_params, dryrun);
  10058. } else {
  10059. ggml_vk_rms_norm(ctx, compute_ctx, src0, src0, node, (float *)node->op_params, dryrun);
  10060. }
  10061. break;
  10062. case GGML_OP_RMS_NORM_BACK:
  10063. ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node, dryrun);
  10064. break;
  10065. case GGML_OP_L2_NORM:
  10066. ggml_vk_l2_norm(ctx, compute_ctx, src0, node, dryrun);
  10067. break;
  10068. case GGML_OP_UNARY:
  10069. switch (ggml_get_unary_op(node)) {
  10070. case GGML_UNARY_OP_EXP:
  10071. case GGML_UNARY_OP_SILU:
  10072. case GGML_UNARY_OP_GELU:
  10073. case GGML_UNARY_OP_GELU_ERF:
  10074. case GGML_UNARY_OP_GELU_QUICK:
  10075. case GGML_UNARY_OP_RELU:
  10076. case GGML_UNARY_OP_TANH:
  10077. case GGML_UNARY_OP_SIGMOID:
  10078. case GGML_UNARY_OP_HARDSIGMOID:
  10079. case GGML_UNARY_OP_HARDSWISH:
  10080. ggml_vk_unary(ctx, compute_ctx, src0, node, dryrun);
  10081. break;
  10082. default:
  10083. return false;
  10084. }
  10085. break;
  10086. case GGML_OP_GLU:
  10087. switch (ggml_get_glu_op(node)) {
  10088. case GGML_GLU_OP_GEGLU:
  10089. case GGML_GLU_OP_REGLU:
  10090. case GGML_GLU_OP_SWIGLU:
  10091. case GGML_GLU_OP_SWIGLU_OAI:
  10092. case GGML_GLU_OP_GEGLU_ERF:
  10093. case GGML_GLU_OP_GEGLU_QUICK:
  10094. ggml_vk_glu(ctx, compute_ctx, src0, src1, node, dryrun);
  10095. break;
  10096. default:
  10097. return false;
  10098. }
  10099. break;
  10100. case GGML_OP_DIAG_MASK_INF:
  10101. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node, dryrun);
  10102. break;
  10103. case GGML_OP_SOFT_MAX:
  10104. if (ctx->num_additional_fused_ops) {
  10105. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx, dryrun);
  10106. } else {
  10107. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  10108. }
  10109. break;
  10110. case GGML_OP_SOFT_MAX_BACK:
  10111. ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node, dryrun);
  10112. break;
  10113. case GGML_OP_ROPE:
  10114. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, false, dryrun);
  10115. break;
  10116. case GGML_OP_ROPE_BACK:
  10117. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, true, dryrun);
  10118. break;
  10119. case GGML_OP_ARGSORT:
  10120. if (ctx->num_additional_fused_ops) {
  10121. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx, dryrun);
  10122. } else {
  10123. ggml_vk_argsort(ctx, compute_ctx, src0, node, dryrun);
  10124. }
  10125. break;
  10126. case GGML_OP_SUM:
  10127. ggml_vk_sum(ctx, compute_ctx, src0, node, dryrun);
  10128. break;
  10129. case GGML_OP_SUM_ROWS:
  10130. ggml_vk_sum_rows(ctx, compute_ctx, src0, node, dryrun);
  10131. break;
  10132. case GGML_OP_MEAN:
  10133. ggml_vk_mean(ctx, compute_ctx, src0, node, dryrun);
  10134. break;
  10135. case GGML_OP_ARGMAX:
  10136. ggml_vk_argmax(ctx, compute_ctx, src0, node, dryrun);
  10137. break;
  10138. case GGML_OP_COUNT_EQUAL:
  10139. ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node, dryrun);
  10140. break;
  10141. case GGML_OP_IM2COL:
  10142. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node, dryrun);
  10143. break;
  10144. case GGML_OP_IM2COL_3D:
  10145. ggml_vk_im2col_3d(ctx, compute_ctx, src0, src1, node, dryrun);
  10146. break;
  10147. case GGML_OP_TIMESTEP_EMBEDDING:
  10148. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node, dryrun);
  10149. break;
  10150. case GGML_OP_CONV_TRANSPOSE_1D:
  10151. ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node, dryrun);
  10152. break;
  10153. case GGML_OP_POOL_2D:
  10154. ggml_vk_pool_2d(ctx, compute_ctx, src0, node, dryrun);
  10155. break;
  10156. case GGML_OP_CONV_2D:
  10157. ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node, dryrun);
  10158. break;
  10159. case GGML_OP_CONV_TRANSPOSE_2D:
  10160. ggml_vk_conv_transpose_2d(ctx, compute_ctx, src0, src1, node, dryrun);
  10161. break;
  10162. case GGML_OP_CONV_2D_DW:
  10163. ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node, dryrun);
  10164. break;
  10165. case GGML_OP_LEAKY_RELU:
  10166. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node, dryrun);
  10167. break;
  10168. case GGML_OP_MUL_MAT:
  10169. ggml_vk_mul_mat(ctx, compute_ctx, src0, src1, node, dryrun);
  10170. break;
  10171. case GGML_OP_MUL_MAT_ID:
  10172. ggml_vk_mul_mat_id(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  10173. break;
  10174. case GGML_OP_FLASH_ATTN_EXT:
  10175. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node, dryrun);
  10176. break;
  10177. case GGML_OP_RWKV_WKV6:
  10178. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node, dryrun);
  10179. break;
  10180. case GGML_OP_RWKV_WKV7:
  10181. ggml_vk_rwkv_wkv7(ctx, compute_ctx, node, dryrun);
  10182. break;
  10183. case GGML_OP_SSM_SCAN:
  10184. ggml_vk_ssm_scan(ctx, compute_ctx, node, dryrun);
  10185. break;
  10186. case GGML_OP_SSM_CONV:
  10187. ggml_vk_ssm_conv(ctx, compute_ctx, node, dryrun);
  10188. break;
  10189. case GGML_OP_OPT_STEP_ADAMW:
  10190. ggml_vk_opt_step_adamw(ctx, compute_ctx, node, dryrun);
  10191. break;
  10192. case GGML_OP_OPT_STEP_SGD:
  10193. ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  10194. break;
  10195. default:
  10196. return false;
  10197. }
  10198. if (dryrun) {
  10199. return false;
  10200. }
  10201. ctx->tensor_ctxs[node_idx] = compute_ctx;
  10202. #if defined(GGML_VULKAN_CHECK_RESULTS)
  10203. // Force context reset on each node so that each tensor ends up in its own context
  10204. // and can be run and compared to its CPU equivalent separately
  10205. last_node = true;
  10206. #endif
  10207. if (submit || last_node) {
  10208. ggml_vk_ctx_end(compute_ctx);
  10209. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  10210. if (last_node) {
  10211. compute_ctx->exit_tensor_idx = node_idx_begin;
  10212. }
  10213. else {
  10214. compute_ctx->exit_tensor_idx = -1;
  10215. }
  10216. ctx->compute_ctx.reset();
  10217. bool ok = ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, false, almost_ready);
  10218. if (!ok) {
  10219. if (node->op == GGML_OP_UNARY) {
  10220. 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;
  10221. } else if (node->op == GGML_OP_GLU) {
  10222. 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;
  10223. } else {
  10224. std::cerr << __func__ << ": error: op not supported " << node->name << " (" << ggml_op_name(node->op) << ")" << std::endl;
  10225. }
  10226. }
  10227. }
  10228. return true;
  10229. }
  10230. static bool ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, ggml_tensor * tensor, int tensor_idx, bool use_fence = true, bool almost_ready = false) {
  10231. GGML_UNUSED(cgraph);
  10232. ggml_backend_buffer * buf = nullptr;
  10233. switch (tensor->op) {
  10234. case GGML_OP_ADD:
  10235. case GGML_OP_ACC:
  10236. case GGML_OP_GET_ROWS:
  10237. case GGML_OP_SUB:
  10238. case GGML_OP_MUL:
  10239. case GGML_OP_DIV:
  10240. case GGML_OP_ADD_ID:
  10241. case GGML_OP_CONCAT:
  10242. case GGML_OP_UPSCALE:
  10243. case GGML_OP_SCALE:
  10244. case GGML_OP_SQR:
  10245. case GGML_OP_SQRT:
  10246. case GGML_OP_SIN:
  10247. case GGML_OP_COS:
  10248. case GGML_OP_CLAMP:
  10249. case GGML_OP_PAD:
  10250. case GGML_OP_ROLL:
  10251. case GGML_OP_CPY:
  10252. case GGML_OP_SET_ROWS:
  10253. case GGML_OP_CONT:
  10254. case GGML_OP_DUP:
  10255. case GGML_OP_SILU_BACK:
  10256. case GGML_OP_NORM:
  10257. case GGML_OP_GROUP_NORM:
  10258. case GGML_OP_RMS_NORM:
  10259. case GGML_OP_RMS_NORM_BACK:
  10260. case GGML_OP_L2_NORM:
  10261. case GGML_OP_DIAG_MASK_INF:
  10262. case GGML_OP_SOFT_MAX:
  10263. case GGML_OP_SOFT_MAX_BACK:
  10264. case GGML_OP_ROPE:
  10265. case GGML_OP_ROPE_BACK:
  10266. case GGML_OP_RESHAPE:
  10267. case GGML_OP_VIEW:
  10268. case GGML_OP_PERMUTE:
  10269. case GGML_OP_TRANSPOSE:
  10270. case GGML_OP_NONE:
  10271. case GGML_OP_ARGSORT:
  10272. case GGML_OP_SUM:
  10273. case GGML_OP_SUM_ROWS:
  10274. case GGML_OP_MEAN:
  10275. case GGML_OP_ARGMAX:
  10276. case GGML_OP_COUNT_EQUAL:
  10277. case GGML_OP_IM2COL:
  10278. case GGML_OP_IM2COL_3D:
  10279. case GGML_OP_TIMESTEP_EMBEDDING:
  10280. case GGML_OP_CONV_TRANSPOSE_1D:
  10281. case GGML_OP_POOL_2D:
  10282. case GGML_OP_CONV_2D:
  10283. case GGML_OP_CONV_TRANSPOSE_2D:
  10284. case GGML_OP_CONV_2D_DW:
  10285. case GGML_OP_RWKV_WKV6:
  10286. case GGML_OP_RWKV_WKV7:
  10287. case GGML_OP_SSM_SCAN:
  10288. case GGML_OP_SSM_CONV:
  10289. case GGML_OP_LEAKY_RELU:
  10290. case GGML_OP_REPEAT:
  10291. case GGML_OP_REPEAT_BACK:
  10292. case GGML_OP_OPT_STEP_ADAMW:
  10293. case GGML_OP_OPT_STEP_SGD:
  10294. buf = tensor->buffer;
  10295. break;
  10296. case GGML_OP_UNARY:
  10297. switch (ggml_get_unary_op(tensor)) {
  10298. case GGML_UNARY_OP_EXP:
  10299. case GGML_UNARY_OP_SILU:
  10300. case GGML_UNARY_OP_GELU:
  10301. case GGML_UNARY_OP_GELU_ERF:
  10302. case GGML_UNARY_OP_GELU_QUICK:
  10303. case GGML_UNARY_OP_RELU:
  10304. case GGML_UNARY_OP_TANH:
  10305. case GGML_UNARY_OP_SIGMOID:
  10306. case GGML_UNARY_OP_HARDSIGMOID:
  10307. case GGML_UNARY_OP_HARDSWISH:
  10308. buf = tensor->buffer;
  10309. break;
  10310. default:
  10311. return false;
  10312. }
  10313. break;
  10314. case GGML_OP_GLU:
  10315. switch (ggml_get_glu_op(tensor)) {
  10316. case GGML_GLU_OP_GEGLU:
  10317. case GGML_GLU_OP_REGLU:
  10318. case GGML_GLU_OP_SWIGLU:
  10319. case GGML_GLU_OP_SWIGLU_OAI:
  10320. case GGML_GLU_OP_GEGLU_ERF:
  10321. case GGML_GLU_OP_GEGLU_QUICK:
  10322. buf = tensor->buffer;
  10323. break;
  10324. default:
  10325. return false;
  10326. }
  10327. break;
  10328. case GGML_OP_MUL_MAT:
  10329. case GGML_OP_MUL_MAT_ID:
  10330. case GGML_OP_FLASH_ATTN_EXT:
  10331. buf = tensor->buffer;
  10332. break;
  10333. default:
  10334. return false;
  10335. }
  10336. if (buf == nullptr) {
  10337. return false;
  10338. }
  10339. 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 << ")");
  10340. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  10341. // always wait for the GPU work to be done for the last submit
  10342. if (tensor_idx == subctx->exit_tensor_idx) {
  10343. use_fence = true;
  10344. }
  10345. // Only run if ctx hasn't been submitted yet
  10346. if (!subctx->seqs.empty()) {
  10347. #ifdef GGML_VULKAN_CHECK_RESULTS
  10348. ggml_vk_check_results_0(ctx, cgraph, tensor_idx);
  10349. use_fence = true;
  10350. #endif
  10351. // Do staging buffer copies
  10352. for (auto& cpy : subctx->in_memcpys) {
  10353. memcpy(cpy.dst, cpy.src, cpy.n);
  10354. }
  10355. for (auto& mset : subctx->memsets) {
  10356. memset(mset.dst, mset.val, mset.n);
  10357. }
  10358. if (almost_ready && !ctx->almost_ready_fence_pending && !use_fence) {
  10359. ggml_vk_submit(subctx, ctx->almost_ready_fence);
  10360. ctx->almost_ready_fence_pending = true;
  10361. } else {
  10362. ggml_vk_submit(subctx, use_fence ? ctx->fence : vk::Fence{});
  10363. }
  10364. if (use_fence) {
  10365. ggml_vk_wait_for_fence(ctx);
  10366. }
  10367. #ifdef GGML_VULKAN_CHECK_RESULTS
  10368. ggml_vk_check_results_1(ctx, cgraph, tensor_idx);
  10369. #endif
  10370. }
  10371. if (tensor_idx == subctx->exit_tensor_idx) {
  10372. // Do staging buffer copies
  10373. for (auto& cpy : subctx->out_memcpys) {
  10374. memcpy(cpy.dst, cpy.src, cpy.n);
  10375. }
  10376. subctx->in_memcpys.clear();
  10377. subctx->out_memcpys.clear();
  10378. subctx->memsets.clear();
  10379. }
  10380. return true;
  10381. }
  10382. // Clean up after graph processing is done
  10383. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  10384. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  10385. ctx->prealloc_y_last_pipeline_used = {};
  10386. ctx->unsynced_nodes_written.clear();
  10387. ctx->unsynced_nodes_read.clear();
  10388. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  10389. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  10390. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  10391. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  10392. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  10393. }
  10394. ctx->gc.semaphores.clear();
  10395. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  10396. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  10397. }
  10398. ctx->gc.tl_semaphores.clear();
  10399. ctx->semaphore_idx = 0;
  10400. ctx->event_idx = 0;
  10401. for (auto& event : ctx->gc.events) {
  10402. ctx->device->device.resetEvent(event);
  10403. }
  10404. ctx->tensor_ctxs.clear();
  10405. ctx->gc.contexts.clear();
  10406. ctx->pipeline_descriptor_set_requirements = 0;
  10407. ctx->descriptor_set_idx = 0;
  10408. }
  10409. // Clean up on backend free
  10410. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  10411. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  10412. ggml_vk_graph_cleanup(ctx);
  10413. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10414. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10415. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10416. ctx->prealloc_y_last_pipeline_used = nullptr;
  10417. ctx->prealloc_size_x = 0;
  10418. ctx->prealloc_size_y = 0;
  10419. ctx->prealloc_size_split_k = 0;
  10420. for (auto& event : ctx->gc.events) {
  10421. ctx->device->device.destroyEvent(event);
  10422. }
  10423. ctx->gc.events.clear();
  10424. ctx->device->device.destroyFence(ctx->fence);
  10425. ctx->device->device.destroyFence(ctx->almost_ready_fence);
  10426. for (auto& pool : ctx->descriptor_pools) {
  10427. ctx->device->device.destroyDescriptorPool(pool);
  10428. }
  10429. ctx->descriptor_pools.clear();
  10430. ctx->descriptor_sets.clear();
  10431. ctx->compute_cmd_pool.destroy(ctx->device->device);
  10432. ctx->transfer_cmd_pool.destroy(ctx->device->device);
  10433. }
  10434. static int ggml_vk_get_device_count() {
  10435. ggml_vk_instance_init();
  10436. return vk_instance.device_indices.size();
  10437. }
  10438. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  10439. ggml_vk_instance_init();
  10440. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  10441. vk::PhysicalDeviceProperties props;
  10442. devices[device].getProperties(&props);
  10443. snprintf(description, description_size, "%s", props.deviceName.data());
  10444. }
  10445. // backend interface
  10446. #define UNUSED GGML_UNUSED
  10447. // device backend
  10448. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  10449. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  10450. }
  10451. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10452. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  10453. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10454. ggml_vk_destroy_buffer(ctx->dev_buffer);
  10455. delete ctx;
  10456. }
  10457. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  10458. return vk_ptr_base;
  10459. UNUSED(buffer);
  10460. }
  10461. static enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  10462. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  10463. if (tensor->view_src != nullptr) {
  10464. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  10465. }
  10466. return GGML_STATUS_SUCCESS;
  10467. }
  10468. 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) {
  10469. VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")");
  10470. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10471. vk_buffer buf = buf_ctx->dev_buffer;
  10472. uint32_t val32 = (uint32_t)value * 0x01010101;
  10473. ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size);
  10474. }
  10475. 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) {
  10476. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10477. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10478. vk_buffer buf = buf_ctx->dev_buffer;
  10479. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10480. }
  10481. 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) {
  10482. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10483. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10484. vk_buffer buf = buf_ctx->dev_buffer;
  10485. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10486. }
  10487. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  10488. if (ggml_backend_buffer_is_vk(src->buffer)) {
  10489. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10490. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10491. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10492. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10493. 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));
  10494. return true;
  10495. }
  10496. return false;
  10497. UNUSED(buffer);
  10498. }
  10499. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  10500. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10501. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  10502. }
  10503. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  10504. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  10505. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  10506. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  10507. /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor,
  10508. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  10509. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  10510. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  10511. /* .clear = */ ggml_backend_vk_buffer_clear,
  10512. /* .reset = */ NULL,
  10513. };
  10514. // vk buffer type
  10515. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10516. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  10517. return ctx->name.c_str();
  10518. }
  10519. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10520. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  10521. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10522. vk_buffer dev_buffer = nullptr;
  10523. try {
  10524. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  10525. } catch (const vk::SystemError& e) {
  10526. return nullptr;
  10527. }
  10528. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  10529. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  10530. }
  10531. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10532. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10533. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  10534. }
  10535. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10536. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10537. return ctx->device->suballocation_block_size;
  10538. }
  10539. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  10540. return ggml_nbytes(tensor);
  10541. UNUSED(buft);
  10542. }
  10543. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  10544. ggml_vk_instance_init();
  10545. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  10546. vk_device dev = ggml_vk_get_device(dev_num);
  10547. return &dev->buffer_type;
  10548. }
  10549. // host buffer type
  10550. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10551. return GGML_VK_NAME "_Host";
  10552. UNUSED(buft);
  10553. }
  10554. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  10555. return GGML_VK_NAME "_Host";
  10556. UNUSED(buffer);
  10557. }
  10558. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10559. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  10560. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  10561. }
  10562. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10563. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  10564. size += 32; // Behave like the CPU buffer type
  10565. void * ptr = nullptr;
  10566. try {
  10567. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  10568. } catch (vk::SystemError& e) {
  10569. GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory (%s)\n", e.what());
  10570. // fallback to cpu buffer
  10571. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  10572. }
  10573. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  10574. buffer->buft = buft;
  10575. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  10576. return buffer;
  10577. UNUSED(buft);
  10578. }
  10579. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10580. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  10581. UNUSED(buft);
  10582. }
  10583. static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10584. return vk_instance.devices[0]->suballocation_block_size;
  10585. UNUSED(buft);
  10586. }
  10587. // Should be changed to return device-specific host buffer type
  10588. // but that probably requires changes in llama.cpp
  10589. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  10590. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  10591. /* .iface = */ {
  10592. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  10593. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  10594. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  10595. /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size,
  10596. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  10597. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  10598. },
  10599. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  10600. /* .context = */ nullptr,
  10601. };
  10602. // Make sure device 0 is initialized
  10603. ggml_vk_instance_init();
  10604. ggml_vk_get_device(0);
  10605. return &ggml_backend_vk_buffer_type_host;
  10606. }
  10607. // backend
  10608. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  10609. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10610. return ctx->name.c_str();
  10611. }
  10612. static void ggml_backend_vk_free(ggml_backend_t backend) {
  10613. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10614. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  10615. ggml_vk_cleanup(ctx);
  10616. delete ctx;
  10617. delete backend;
  10618. }
  10619. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  10620. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10621. return &ctx->device->buffer_type;
  10622. }
  10623. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  10624. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  10625. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10626. 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");
  10627. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10628. vk_context transfer_ctx;
  10629. if (ctx->transfer_ctx.expired()) {
  10630. // Initialize new transfer context
  10631. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10632. ctx->transfer_ctx = transfer_ctx;
  10633. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10634. } else {
  10635. transfer_ctx = ctx->transfer_ctx.lock();
  10636. }
  10637. vk_buffer buf = buf_ctx->dev_buffer;
  10638. ggml_vk_buffer_write_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10639. }
  10640. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  10641. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  10642. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10643. 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");
  10644. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10645. vk_context transfer_ctx;
  10646. if (ctx->transfer_ctx.expired()) {
  10647. // Initialize new transfer context
  10648. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10649. ctx->transfer_ctx = transfer_ctx;
  10650. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10651. } else {
  10652. transfer_ctx = ctx->transfer_ctx.lock();
  10653. }
  10654. vk_buffer buf = buf_ctx->dev_buffer;
  10655. ggml_vk_buffer_read_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10656. }
  10657. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  10658. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  10659. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10660. 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)) {
  10661. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10662. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10663. vk_context transfer_ctx;
  10664. if (ctx->transfer_ctx.expired()) {
  10665. // Initialize new transfer context
  10666. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10667. ctx->transfer_ctx = transfer_ctx;
  10668. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10669. } else {
  10670. transfer_ctx = ctx->transfer_ctx.lock();
  10671. }
  10672. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10673. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10674. 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));
  10675. return true;
  10676. }
  10677. return false;
  10678. }
  10679. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  10680. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  10681. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10682. if(ctx->transfer_ctx.expired()) {
  10683. return;
  10684. }
  10685. vk_context transfer_ctx = ctx->transfer_ctx.lock();
  10686. ggml_vk_ctx_end(transfer_ctx);
  10687. for (auto& cpy : transfer_ctx->in_memcpys) {
  10688. memcpy(cpy.dst, cpy.src, cpy.n);
  10689. }
  10690. ggml_vk_submit(transfer_ctx, ctx->fence);
  10691. ggml_vk_wait_for_fence(ctx);
  10692. for (auto& cpy : transfer_ctx->out_memcpys) {
  10693. memcpy(cpy.dst, cpy.src, cpy.n);
  10694. }
  10695. ctx->transfer_ctx.reset();
  10696. }
  10697. static bool ggml_vk_is_empty(ggml_tensor * node) {
  10698. 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;
  10699. }
  10700. static bool ggml_vk_can_fuse(const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list<enum ggml_op> ops) {
  10701. if (!ggml_can_fuse(cgraph, node_idx, ops)) {
  10702. return false;
  10703. }
  10704. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
  10705. // additional constraints specific to this fusion
  10706. const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
  10707. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10708. GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
  10709. GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
  10710. // rms_norm only supports f32
  10711. if (mul->src[0]->type != GGML_TYPE_F32 ||
  10712. mul->src[1]->type != GGML_TYPE_F32 ||
  10713. mul->type != GGML_TYPE_F32) {
  10714. return false;
  10715. }
  10716. // if rms_norm is the B operand, then we don't handle broadcast
  10717. if (rms_norm == mul->src[1] &&
  10718. !ggml_are_same_shape(mul->src[0], rms_norm)) {
  10719. return false;
  10720. }
  10721. // rms_norm shader assumes contiguous rows
  10722. if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
  10723. return false;
  10724. }
  10725. }
  10726. return true;
  10727. }
  10728. static bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10729. int node_idx, topk_moe_mode mode) {
  10730. const ggml_tensor * softmax;
  10731. const ggml_tensor * weights;
  10732. switch (mode) {
  10733. case TOPK_MOE_EARLY_SOFTMAX_NORM:
  10734. softmax = cgraph->nodes[node_idx + 0];
  10735. weights = cgraph->nodes[node_idx + 9];
  10736. break;
  10737. case TOPK_MOE_EARLY_SOFTMAX:
  10738. softmax = cgraph->nodes[node_idx + 0];
  10739. weights = cgraph->nodes[node_idx + 4];
  10740. break;
  10741. case TOPK_MOE_LATE_SOFTMAX:
  10742. softmax = cgraph->nodes[node_idx + 4];
  10743. weights = cgraph->nodes[node_idx + 5];
  10744. break;
  10745. default:
  10746. return false;
  10747. }
  10748. const float * op_params = (const float *)softmax->op_params;
  10749. float scale = op_params[0];
  10750. float max_bias = op_params[1];
  10751. if (!ggml_is_contiguous(softmax->src[0]) || !ggml_is_contiguous(weights)) {
  10752. return false;
  10753. }
  10754. if (scale != 1.0f || max_bias != 0.0f) {
  10755. return false;
  10756. }
  10757. // don't fuse when masks or sinks are present
  10758. if (softmax->src[1] || softmax->src[2]) {
  10759. return false;
  10760. }
  10761. const int n_expert = softmax->ne[0];
  10762. // n_expert must be a power of 2
  10763. if (!is_pow2(n_expert) || n_expert > (1 << (num_topk_moe_pipelines-1))) {
  10764. return false;
  10765. }
  10766. if (!ctx->device->subgroup_arithmetic ||
  10767. !ctx->device->subgroup_shuffle ||
  10768. !ctx->device->subgroup_require_full_support ||
  10769. ctx->device->disable_fusion) {
  10770. return false;
  10771. }
  10772. return true;
  10773. }
  10774. static bool ggml_vk_can_fuse_rope_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10775. int node_idx) {
  10776. GGML_UNUSED(ctx);
  10777. const ggml_tensor *rope = cgraph->nodes[node_idx + 0];
  10778. const ggml_tensor *view = cgraph->nodes[node_idx + 1];
  10779. const ggml_tensor *set_rows = cgraph->nodes[node_idx + 2];
  10780. // ne3 not tested
  10781. if (rope->src[0]->ne[3] != 1) {
  10782. return false;
  10783. }
  10784. if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) {
  10785. return false;
  10786. }
  10787. if (set_rows->src[1]->type != GGML_TYPE_I64) {
  10788. return false;
  10789. }
  10790. // The view should flatten two dims of rope into one dim
  10791. if (!ggml_is_contiguous(view) ||
  10792. view->ne[0] != rope->ne[0] * rope->ne[1]) {
  10793. return false;
  10794. }
  10795. // Only norm/neox shaders have the fusion code
  10796. const int mode = ((const int32_t *) rope->op_params)[2];
  10797. if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX) {
  10798. return false;
  10799. }
  10800. return true;
  10801. }
  10802. static uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) {
  10803. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  10804. if (first_node->op != GGML_OP_ADD) {
  10805. return 0;
  10806. }
  10807. if (!ctx->device->multi_add) {
  10808. return 0;
  10809. }
  10810. int32_t num_adds = 1;
  10811. while (node_idx + num_adds < cgraph->n_nodes &&
  10812. cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD &&
  10813. num_adds < MAX_FUSED_ADDS) {
  10814. num_adds++;
  10815. }
  10816. // The shader currently requires same shapes (but different strides are allowed),
  10817. // everything f32, and no misalignment
  10818. for (int32_t i = 0; i < num_adds; ++i) {
  10819. const ggml_tensor *next_node = cgraph->nodes[node_idx + i];
  10820. if (!ggml_are_same_shape(first_node, next_node->src[0]) ||
  10821. !ggml_are_same_shape(first_node, next_node->src[1]) ||
  10822. next_node->type != GGML_TYPE_F32 ||
  10823. next_node->src[0]->type != GGML_TYPE_F32 ||
  10824. next_node->src[1]->type != GGML_TYPE_F32 ||
  10825. get_misalign_bytes(ctx, next_node) ||
  10826. get_misalign_bytes(ctx, next_node->src[0]) ||
  10827. get_misalign_bytes(ctx, next_node->src[1])) {
  10828. num_adds = i;
  10829. }
  10830. }
  10831. // Verify we can fuse these
  10832. ggml_op adds[MAX_FUSED_ADDS];
  10833. for (int32_t i = 0; i < num_adds; ++i) {
  10834. adds[i] = GGML_OP_ADD;
  10835. }
  10836. // decrease num_adds if they can't all be fused
  10837. while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) {
  10838. num_adds--;
  10839. }
  10840. // a single add is not "fused", so just return zero
  10841. if (num_adds == 1) {
  10842. return 0;
  10843. }
  10844. return num_adds;
  10845. }
  10846. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  10847. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  10848. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10849. if (vk_instance.debug_utils_support) {
  10850. vk::DebugUtilsLabelEXT dul = {};
  10851. dul.pLabelName = "ggml_backend_vk_graph_compute";
  10852. dul.color = std::array<float,4>{1.0f, 1.0f, 1.0f, 1.0f};
  10853. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(ctx->device->compute_queue.queue, reinterpret_cast<VkDebugUtilsLabelEXT*>(&dul));
  10854. }
  10855. ctx->prealloc_size_add_rms_partials = 0;
  10856. ctx->prealloc_size_add_rms_partials_offset = 0;
  10857. ctx->do_add_rms_partials = false;
  10858. uint64_t total_mat_mul_bytes = 0;
  10859. for (int i = 0; i < cgraph->n_nodes; i++) {
  10860. if (!ctx->device->disable_fusion) {
  10861. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  10862. if (num_adds) {
  10863. ctx->num_additional_fused_ops = num_adds - 1;
  10864. } else if (ggml_vk_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  10865. ctx->num_additional_fused_ops = 1;
  10866. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 2 }) &&
  10867. ggml_check_edges(cgraph, i, rope_view_set_rows_edges) &&
  10868. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i)) {
  10869. ctx->num_additional_fused_ops = 2;
  10870. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax_norm, { i + 3, i + 9 }) &&
  10871. ggml_check_edges(cgraph, i, topk_moe_early_softmax_norm_edges) &&
  10872. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX_NORM)) {
  10873. ctx->num_additional_fused_ops = topk_moe_early_softmax_norm.size() - 1;
  10874. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax, { i + 3, i + 4 }) &&
  10875. ggml_check_edges(cgraph, i, topk_moe_early_softmax_edges) &&
  10876. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX)) {
  10877. ctx->num_additional_fused_ops = topk_moe_early_softmax.size() - 1;
  10878. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_late_softmax, { i + 1, i + 5 }) &&
  10879. ggml_check_edges(cgraph, i, topk_moe_late_softmax_edges) &&
  10880. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_LATE_SOFTMAX)) {
  10881. ctx->num_additional_fused_ops = topk_moe_late_softmax.size() - 1;
  10882. }
  10883. }
  10884. ggml_vk_build_graph(ctx, cgraph, i, nullptr, 0, true, false, false, false);
  10885. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  10886. total_mat_mul_bytes += ggml_nbytes(cgraph->nodes[i]->src[0]);
  10887. } else if (cgraph->nodes[i]->op == GGML_OP_CONV_2D || cgraph->nodes[i]->op == GGML_OP_CONV_TRANSPOSE_2D) {
  10888. // Return CRSxNPQxsizeof(*) to account as many bytes as mul_mat has in im2col->mul_mat mode.
  10889. auto CRS_size =
  10890. cgraph->nodes[i]->src[0]->ne[0] * cgraph->nodes[i]->src[0]->ne[1] * cgraph->nodes[i]->src[1]->ne[2];
  10891. auto NPQ_size = cgraph->nodes[i]->ne[0] * cgraph->nodes[i]->ne[1] * cgraph->nodes[i]->ne[3];
  10892. total_mat_mul_bytes += NPQ_size * CRS_size * ggml_type_size(cgraph->nodes[i]->type);
  10893. }
  10894. i += ctx->num_additional_fused_ops;
  10895. ctx->num_additional_fused_ops = 0;
  10896. }
  10897. if (ctx->device->need_compiles) {
  10898. ggml_vk_load_shaders(ctx->device);
  10899. }
  10900. ggml_vk_preallocate_buffers(ctx);
  10901. ggml_pipeline_allocate_descriptor_sets(ctx);
  10902. int last_node = cgraph->n_nodes - 1;
  10903. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  10904. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  10905. last_node -= 1;
  10906. }
  10907. // Reserve tensor context space for all nodes
  10908. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  10909. bool first_node_in_batch = true; // true if next node will be first node in a batch
  10910. int submit_node_idx = 0; // index to first node in a batch
  10911. vk_context compute_ctx;
  10912. if (vk_perf_logger_enabled) {
  10913. // allocate/resize the query pool
  10914. if (ctx->device->num_queries < cgraph->n_nodes + 1) {
  10915. if (ctx->device->query_pool) {
  10916. ctx->device->device.destroyQueryPool(ctx->device->query_pool);
  10917. }
  10918. vk::QueryPoolCreateInfo query_create_info;
  10919. query_create_info.queryType = vk::QueryType::eTimestamp;
  10920. query_create_info.queryCount = cgraph->n_nodes + 100;
  10921. ctx->device->query_pool = ctx->device->device.createQueryPool(query_create_info);
  10922. ctx->device->num_queries = query_create_info.queryCount;
  10923. }
  10924. ctx->device->device.resetQueryPool(ctx->device->query_pool, 0, cgraph->n_nodes+1);
  10925. GGML_ASSERT(ctx->compute_ctx.expired());
  10926. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10927. ctx->compute_ctx = compute_ctx;
  10928. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10929. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, 0);
  10930. }
  10931. ctx->prealloc_y_last_pipeline_used = nullptr;
  10932. ctx->prealloc_y_last_tensor_used = nullptr;
  10933. if (ctx->prealloc_size_add_rms_partials) {
  10934. if (ctx->compute_ctx.expired()) {
  10935. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10936. ctx->compute_ctx = compute_ctx;
  10937. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10938. } else {
  10939. compute_ctx = ctx->compute_ctx.lock();
  10940. }
  10941. // initialize partial sums to zero.
  10942. ggml_vk_buffer_memset_async(compute_ctx, ctx->prealloc_add_rms_partials, 0, 0, ctx->prealloc_size_add_rms_partials);
  10943. ggml_vk_sync_buffers(ctx, compute_ctx);
  10944. }
  10945. // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution.
  10946. // Estimate the amount of matmul work by looking at the weight matrix size, and submit every 100MB
  10947. // (and scaled down based on model size, so smaller models submit earlier).
  10948. // Also submit at least every 100 nodes, in case there are workloads without as much matmul.
  10949. int nodes_per_submit = 100;
  10950. int submitted_nodes = 0;
  10951. int submit_count = 0;
  10952. uint64_t mul_mat_bytes = 0;
  10953. uint64_t mul_mat_bytes_per_submit = std::min(uint64_t(100*1000*1000), total_mat_mul_bytes / 40u);
  10954. for (int i = 0; i < cgraph->n_nodes; i++) {
  10955. if (first_node_in_batch) {
  10956. submit_node_idx = i;
  10957. }
  10958. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  10959. mul_mat_bytes += ggml_nbytes(cgraph->nodes[i]->src[0]);
  10960. }
  10961. if (!ctx->device->disable_fusion) {
  10962. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  10963. if (num_adds) {
  10964. ctx->num_additional_fused_ops = num_adds - 1;
  10965. } else if (ggml_vk_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  10966. ctx->num_additional_fused_ops = 1;
  10967. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 2 }) &&
  10968. ggml_check_edges(cgraph, i, rope_view_set_rows_edges) &&
  10969. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i)) {
  10970. ctx->num_additional_fused_ops = 2;
  10971. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax_norm, { i + 3, i + 9 }) &&
  10972. ggml_check_edges(cgraph, i, topk_moe_early_softmax_norm_edges) &&
  10973. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX_NORM)) {
  10974. ctx->num_additional_fused_ops = topk_moe_early_softmax_norm.size() - 1;
  10975. // view of argsort writes to memory
  10976. ctx->fused_ops_write_mask |= 1 << 3;
  10977. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax, { i + 3, i + 4 }) &&
  10978. ggml_check_edges(cgraph, i, topk_moe_early_softmax_edges) &&
  10979. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX)) {
  10980. ctx->num_additional_fused_ops = topk_moe_early_softmax.size() - 1;
  10981. // view of argsort writes to memory
  10982. ctx->fused_ops_write_mask |= 1 << 3;
  10983. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_late_softmax, { i + 1, i + 5 }) &&
  10984. ggml_check_edges(cgraph, i, topk_moe_late_softmax_edges) &&
  10985. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_LATE_SOFTMAX)) {
  10986. ctx->num_additional_fused_ops = topk_moe_late_softmax.size() - 1;
  10987. // view of argsort writes to memory
  10988. ctx->fused_ops_write_mask |= 1 << 1;
  10989. }
  10990. }
  10991. ctx->fused_ops_write_mask |= 1 << ctx->num_additional_fused_ops;
  10992. // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining)
  10993. bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5;
  10994. bool submit = (submitted_nodes >= nodes_per_submit) ||
  10995. (mul_mat_bytes >= mul_mat_bytes_per_submit) ||
  10996. (i + ctx->num_additional_fused_ops >= last_node) ||
  10997. (almost_ready && !ctx->almost_ready_fence_pending);
  10998. bool enqueued = ggml_vk_build_graph(ctx, cgraph, i, cgraph->nodes[submit_node_idx], submit_node_idx, false, i + ctx->num_additional_fused_ops >= last_node, almost_ready, submit);
  10999. if (vk_perf_logger_enabled) {
  11000. if (ctx->compute_ctx.expired()) {
  11001. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11002. ctx->compute_ctx = compute_ctx;
  11003. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11004. } else {
  11005. compute_ctx = ctx->compute_ctx.lock();
  11006. }
  11007. // If there are fused ops, just write out timestamps for all nodes to keep the accounting simple
  11008. for (int j = 0; j < ctx->num_additional_fused_ops + 1; ++j) {
  11009. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, i+j+1);
  11010. }
  11011. }
  11012. if (enqueued) {
  11013. ++submitted_nodes;
  11014. #ifndef GGML_VULKAN_CHECK_RESULTS
  11015. if (first_node_in_batch) {
  11016. first_node_in_batch = false;
  11017. }
  11018. #endif
  11019. }
  11020. if (submit && enqueued) {
  11021. first_node_in_batch = true;
  11022. submitted_nodes = 0;
  11023. mul_mat_bytes = 0;
  11024. if (submit_count < 3) {
  11025. mul_mat_bytes_per_submit *= 2;
  11026. }
  11027. submit_count++;
  11028. }
  11029. i += ctx->num_additional_fused_ops;
  11030. ctx->num_additional_fused_ops = 0;
  11031. ctx->fused_ops_write_mask = 0;
  11032. }
  11033. if (vk_perf_logger_enabled) {
  11034. // End the command buffer and submit/wait
  11035. GGML_ASSERT(!ctx->compute_ctx.expired());
  11036. compute_ctx = ctx->compute_ctx.lock();
  11037. ggml_vk_ctx_end(compute_ctx);
  11038. ggml_vk_submit(compute_ctx, ctx->device->fence);
  11039. VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences");
  11040. ctx->device->device.resetFences({ ctx->device->fence });
  11041. // Get the results and pass them to the logger
  11042. std::vector<uint64_t> timestamps(cgraph->n_nodes + 1);
  11043. 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");
  11044. for (int i = 0; i < cgraph->n_nodes; i++) {
  11045. if (!ggml_vk_is_empty(cgraph->nodes[i])) {
  11046. ctx->device->perf_logger->log_timing(cgraph->nodes[i], uint64_t((timestamps[i+1] - timestamps[i]) * ctx->device->properties.limits.timestampPeriod));
  11047. }
  11048. }
  11049. ctx->device->perf_logger->print_timings();
  11050. }
  11051. ggml_vk_graph_cleanup(ctx);
  11052. return GGML_STATUS_SUCCESS;
  11053. UNUSED(backend);
  11054. }
  11055. // Sort the graph for improved parallelism.
  11056. static void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph)
  11057. {
  11058. VK_LOG_DEBUG("ggml_vk_graph_optimize(" << graph->n_nodes << " nodes)");
  11059. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11060. if (ctx->device->disable_graph_optimize) {
  11061. return;
  11062. }
  11063. auto const &is_empty = [](ggml_tensor * node) -> bool {
  11064. 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;
  11065. };
  11066. auto const &is_src_of = [](const ggml_tensor *dst, const ggml_tensor *src) -> bool {
  11067. for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) {
  11068. if (dst->src[s] == src) {
  11069. return true;
  11070. }
  11071. }
  11072. // implicit dependency if they view the same tensor
  11073. const ggml_tensor *dst2 = dst->view_src ? dst->view_src : dst;
  11074. const ggml_tensor *src2 = src->view_src ? src->view_src : src;
  11075. if (dst2 == src2) {
  11076. return true;
  11077. }
  11078. return false;
  11079. };
  11080. // This function tries to reorder the graph to allow nodes to run in parallel.
  11081. // This helps with small batches, but for large batches its a slowdown, probably
  11082. // due to cache contention. So only reorder if the majority of nodes have few rows.
  11083. int num_small_nodes = 0;
  11084. int num_counted_nodes = 0;
  11085. for (int i = 0; i < graph->n_nodes; ++i) {
  11086. if (!is_empty(graph->nodes[i]) &&
  11087. graph->nodes[i]->op != GGML_OP_SET_ROWS) {
  11088. if (ggml_nrows(graph->nodes[i]) <= 8) {
  11089. num_small_nodes++;
  11090. }
  11091. num_counted_nodes++;
  11092. }
  11093. }
  11094. if (num_small_nodes < num_counted_nodes / 2) {
  11095. return;
  11096. }
  11097. std::vector<ggml_tensor *> new_order;
  11098. std::vector<bool> used(graph->n_nodes, false);
  11099. int first_unused = 0;
  11100. while (first_unused < graph->n_nodes) {
  11101. std::vector<int> current_set;
  11102. // Check for fusion patterns and avoid reordering them
  11103. auto const &match_pattern = [&](const std::initializer_list<ggml_op> &pattern, int start) -> bool {
  11104. if (start + (int)pattern.size() <= graph->n_nodes) {
  11105. bool is_pattern = true;
  11106. for (size_t j = 0; j < pattern.size(); ++j) {
  11107. if (graph->nodes[start + j]->op != pattern.begin()[j] || used[start + j]) {
  11108. is_pattern = false;
  11109. }
  11110. }
  11111. return is_pattern;
  11112. }
  11113. return false;
  11114. };
  11115. auto const &keep_pattern = [&](const std::initializer_list<ggml_op> &pattern) -> bool {
  11116. if (match_pattern(pattern, first_unused)) {
  11117. for (size_t j = 0; j < pattern.size(); ++j) {
  11118. new_order.push_back(graph->nodes[first_unused + j]);
  11119. used[first_unused + j] = true;
  11120. }
  11121. while (first_unused < graph->n_nodes && used[first_unused]) {
  11122. first_unused++;
  11123. }
  11124. return true;
  11125. }
  11126. return false;
  11127. };
  11128. if (keep_pattern(topk_moe_early_softmax_norm)) {
  11129. continue;
  11130. }
  11131. if (keep_pattern(topk_moe_early_softmax)) {
  11132. continue;
  11133. }
  11134. if (keep_pattern(topk_moe_late_softmax)) {
  11135. continue;
  11136. }
  11137. // First, grab the next unused node.
  11138. current_set.push_back(first_unused);
  11139. // Loop through the next N nodes. Grab any that don't depend on other nodes that
  11140. // haven't already been run. Nodes that have already been run have used[i] set
  11141. // to true. Allow nodes that depend on the previous node if it's a fusion pattern
  11142. // that we support (e.g. RMS_NORM + MUL).
  11143. // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes.
  11144. // The goal is to not interleave real and view nodes in a way that breaks fusion.
  11145. const int NUM_TO_CHECK = 20;
  11146. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11147. if (used[j]) {
  11148. continue;
  11149. }
  11150. if (is_empty(graph->nodes[j])) {
  11151. continue;
  11152. }
  11153. // Don't pull forward nodes from fusion patterns
  11154. if (match_pattern(topk_moe_early_softmax_norm, j) ||
  11155. match_pattern(topk_moe_early_softmax, j) ||
  11156. match_pattern(topk_moe_late_softmax, j)) {
  11157. continue;
  11158. }
  11159. bool ok = true;
  11160. for (int c = first_unused; c < j; ++c) {
  11161. if (!used[c] &&
  11162. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11163. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL)) {
  11164. ok = false;
  11165. break;
  11166. }
  11167. }
  11168. if (ok) {
  11169. current_set.push_back(j);
  11170. // Look for ROPE + VIEW + SET_ROWS and make them consecutive
  11171. if (graph->nodes[j]->op == GGML_OP_ROPE) {
  11172. int view_idx = -1;
  11173. int set_rows_idx = -1;
  11174. for (int k = j+1; k < std::min(j + 10, graph->n_nodes); ++k) {
  11175. if (view_idx == -1 &&
  11176. graph->nodes[k]->op == GGML_OP_VIEW &&
  11177. graph->nodes[k]->src[0] == graph->nodes[j]) {
  11178. view_idx = k;
  11179. continue;
  11180. }
  11181. if (view_idx != -1 &&
  11182. set_rows_idx == -1 &&
  11183. graph->nodes[k]->op == GGML_OP_SET_ROWS &&
  11184. graph->nodes[k]->src[0] == graph->nodes[view_idx]) {
  11185. set_rows_idx = k;
  11186. break;
  11187. }
  11188. }
  11189. if (set_rows_idx != -1) {
  11190. current_set.push_back(view_idx);
  11191. current_set.push_back(set_rows_idx);
  11192. used[view_idx] = true;
  11193. used[set_rows_idx] = true;
  11194. }
  11195. }
  11196. }
  11197. }
  11198. // Second pass grabs view nodes.
  11199. // Skip this if it would break a fusion optimization (don't split up add->rms_norm or add->add).
  11200. if (graph->nodes[current_set.back()]->op != GGML_OP_ADD) {
  11201. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11202. if (used[j]) {
  11203. continue;
  11204. }
  11205. if (!is_empty(graph->nodes[j])) {
  11206. continue;
  11207. }
  11208. bool ok = true;
  11209. for (int c = first_unused; c < j; ++c) {
  11210. bool c_in_current_set = std::find(current_set.begin(), current_set.end(), c) != current_set.end();
  11211. // skip views whose srcs haven't been processed.
  11212. if (!used[c] &&
  11213. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11214. !c_in_current_set) {
  11215. ok = false;
  11216. break;
  11217. }
  11218. }
  11219. if (ok) {
  11220. current_set.push_back(j);
  11221. }
  11222. }
  11223. }
  11224. // Push the current set into new_order
  11225. for (auto c : current_set) {
  11226. new_order.push_back(graph->nodes[c]);
  11227. used[c] = true;
  11228. }
  11229. while (first_unused < graph->n_nodes && used[first_unused]) {
  11230. first_unused++;
  11231. }
  11232. }
  11233. // Replace the graph with the new order.
  11234. for (int i = 0; i < graph->n_nodes; ++i) {
  11235. graph->nodes[i] = new_order[i];
  11236. }
  11237. }
  11238. // TODO: enable async and synchronize
  11239. static ggml_backend_i ggml_backend_vk_interface = {
  11240. /* .get_name = */ ggml_backend_vk_name,
  11241. /* .free = */ ggml_backend_vk_free,
  11242. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  11243. /* .get_tensor_async = */ NULL, // ggml_backend_vk_get_tensor_async,
  11244. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  11245. /* .synchronize = */ NULL, // ggml_backend_vk_synchronize,
  11246. /* .graph_plan_create = */ NULL,
  11247. /* .graph_plan_free = */ NULL,
  11248. /* .graph_plan_update = */ NULL,
  11249. /* .graph_plan_compute = */ NULL,
  11250. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  11251. /* .event_record = */ NULL,
  11252. /* .event_wait = */ NULL,
  11253. /* .graph_optimize = */ ggml_vk_graph_optimize,
  11254. };
  11255. static ggml_guid_t ggml_backend_vk_guid() {
  11256. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  11257. return &guid;
  11258. }
  11259. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  11260. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  11261. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  11262. ggml_vk_init(ctx, dev_num);
  11263. ggml_backend_t vk_backend = new ggml_backend {
  11264. /* .guid = */ ggml_backend_vk_guid(),
  11265. /* .iface = */ ggml_backend_vk_interface,
  11266. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  11267. /* .context = */ ctx,
  11268. };
  11269. return vk_backend;
  11270. }
  11271. bool ggml_backend_is_vk(ggml_backend_t backend) {
  11272. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  11273. }
  11274. int ggml_backend_vk_get_device_count() {
  11275. return ggml_vk_get_device_count();
  11276. }
  11277. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  11278. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11279. int dev_idx = vk_instance.device_indices[device];
  11280. ggml_vk_get_device_description(dev_idx, description, description_size);
  11281. }
  11282. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  11283. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11284. GGML_ASSERT(device < (int) vk_instance.device_supports_membudget.size());
  11285. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  11286. vk::PhysicalDeviceMemoryBudgetPropertiesEXT budgetprops;
  11287. vk::PhysicalDeviceMemoryProperties2 memprops = {};
  11288. bool membudget_supported = vk_instance.device_supports_membudget[device];
  11289. if (membudget_supported) {
  11290. memprops.pNext = &budgetprops;
  11291. }
  11292. vkdev.getMemoryProperties2(&memprops);
  11293. for (uint32_t i = 0; i < memprops.memoryProperties.memoryHeapCount; ++i) {
  11294. const vk::MemoryHeap & heap = memprops.memoryProperties.memoryHeaps[i];
  11295. if (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
  11296. *total = heap.size;
  11297. if (membudget_supported && i < budgetprops.heapUsage.size()) {
  11298. *free = budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
  11299. } else {
  11300. *free = heap.size;
  11301. }
  11302. break;
  11303. }
  11304. }
  11305. }
  11306. static vk::PhysicalDeviceType ggml_backend_vk_get_device_type(int device_idx) {
  11307. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11308. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11309. vk::PhysicalDeviceProperties2 props = {};
  11310. device.getProperties2(&props);
  11311. return props.properties.deviceType;
  11312. }
  11313. static std::string ggml_backend_vk_get_device_pci_id(int device_idx) {
  11314. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11315. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11316. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  11317. bool ext_support = false;
  11318. for (const auto& properties : ext_props) {
  11319. if (strcmp("VK_EXT_pci_bus_info", properties.extensionName) == 0) {
  11320. ext_support = true;
  11321. break;
  11322. }
  11323. }
  11324. if (!ext_support) {
  11325. return "";
  11326. }
  11327. vk::PhysicalDeviceProperties2 props = {};
  11328. vk::PhysicalDevicePCIBusInfoPropertiesEXT pci_bus_info = {};
  11329. props.pNext = &pci_bus_info;
  11330. device.getProperties2(&props);
  11331. const uint32_t pci_domain = pci_bus_info.pciDomain;
  11332. const uint32_t pci_bus = pci_bus_info.pciBus;
  11333. const uint32_t pci_device = pci_bus_info.pciDevice;
  11334. const uint8_t pci_function = (uint8_t) pci_bus_info.pciFunction; // pci function is between 0 and 7, prevent printf overflow warning
  11335. char pci_bus_id[16] = {};
  11336. snprintf(pci_bus_id, sizeof(pci_bus_id), "%04x:%02x:%02x.%x", pci_domain, pci_bus, pci_device, pci_function);
  11337. return std::string(pci_bus_id);
  11338. }
  11339. //////////////////////////
  11340. struct ggml_backend_vk_device_context {
  11341. size_t device;
  11342. std::string name;
  11343. std::string description;
  11344. bool is_integrated_gpu;
  11345. std::string pci_bus_id;
  11346. };
  11347. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  11348. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11349. return ctx->name.c_str();
  11350. }
  11351. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  11352. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11353. return ctx->description.c_str();
  11354. }
  11355. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  11356. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  11357. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  11358. }
  11359. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  11360. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11361. return ggml_backend_vk_buffer_type(ctx->device);
  11362. }
  11363. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  11364. UNUSED(dev);
  11365. return ggml_backend_vk_host_buffer_type();
  11366. }
  11367. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  11368. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11369. return ctx->is_integrated_gpu ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
  11370. }
  11371. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  11372. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11373. props->name = ggml_backend_vk_device_get_name(dev);
  11374. props->description = ggml_backend_vk_device_get_description(dev);
  11375. props->type = ggml_backend_vk_device_get_type(dev);
  11376. props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str();
  11377. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  11378. props->caps = {
  11379. /* .async = */ false,
  11380. /* .host_buffer = */ true,
  11381. /* .buffer_from_host_ptr = */ false,
  11382. /* .events = */ false,
  11383. };
  11384. }
  11385. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  11386. UNUSED(params);
  11387. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11388. return ggml_backend_vk_init(ctx->device);
  11389. }
  11390. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  11391. switch (op->op) {
  11392. case GGML_OP_UNARY:
  11393. switch (ggml_get_unary_op(op)) {
  11394. case GGML_UNARY_OP_EXP:
  11395. case GGML_UNARY_OP_GELU:
  11396. case GGML_UNARY_OP_GELU_ERF:
  11397. case GGML_UNARY_OP_GELU_QUICK:
  11398. case GGML_UNARY_OP_SILU:
  11399. case GGML_UNARY_OP_RELU:
  11400. case GGML_UNARY_OP_TANH:
  11401. case GGML_UNARY_OP_SIGMOID:
  11402. case GGML_UNARY_OP_HARDSIGMOID:
  11403. case GGML_UNARY_OP_HARDSWISH:
  11404. return ggml_is_contiguous(op->src[0]) &&
  11405. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11406. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11407. (op->src[0]->type == op->type);
  11408. default:
  11409. return false;
  11410. }
  11411. case GGML_OP_GLU:
  11412. switch (ggml_get_glu_op(op)) {
  11413. case GGML_GLU_OP_GEGLU:
  11414. case GGML_GLU_OP_REGLU:
  11415. case GGML_GLU_OP_SWIGLU:
  11416. case GGML_GLU_OP_SWIGLU_OAI:
  11417. case GGML_GLU_OP_GEGLU_ERF:
  11418. case GGML_GLU_OP_GEGLU_QUICK:
  11419. return ggml_is_contiguous(op->src[0]) &&
  11420. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11421. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11422. (op->src[0]->type == op->type);
  11423. default:
  11424. return false;
  11425. }
  11426. case GGML_OP_MUL_MAT:
  11427. case GGML_OP_MUL_MAT_ID:
  11428. {
  11429. ggml_type src0_type = op->src[0]->type;
  11430. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11431. const vk_device& device = ggml_vk_get_device(ctx->device);
  11432. if (op->op == GGML_OP_MUL_MAT_ID) {
  11433. if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) {
  11434. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  11435. return false;
  11436. }
  11437. }
  11438. switch (src0_type) {
  11439. case GGML_TYPE_F32:
  11440. case GGML_TYPE_F16:
  11441. case GGML_TYPE_BF16:
  11442. case GGML_TYPE_Q4_0:
  11443. case GGML_TYPE_Q4_1:
  11444. case GGML_TYPE_Q5_0:
  11445. case GGML_TYPE_Q5_1:
  11446. case GGML_TYPE_Q8_0:
  11447. case GGML_TYPE_Q2_K:
  11448. case GGML_TYPE_Q3_K:
  11449. case GGML_TYPE_Q4_K:
  11450. case GGML_TYPE_Q5_K:
  11451. case GGML_TYPE_Q6_K:
  11452. case GGML_TYPE_IQ1_S:
  11453. case GGML_TYPE_IQ1_M:
  11454. case GGML_TYPE_IQ2_XXS:
  11455. case GGML_TYPE_IQ2_XS:
  11456. case GGML_TYPE_IQ2_S:
  11457. case GGML_TYPE_IQ3_XXS:
  11458. case GGML_TYPE_IQ3_S:
  11459. case GGML_TYPE_IQ4_XS:
  11460. case GGML_TYPE_IQ4_NL:
  11461. case GGML_TYPE_MXFP4:
  11462. break;
  11463. default:
  11464. return false;
  11465. }
  11466. struct ggml_tensor * a;
  11467. struct ggml_tensor * b;
  11468. if (op->op == GGML_OP_MUL_MAT) {
  11469. a = op->src[0];
  11470. b = op->src[1];
  11471. } else {
  11472. a = op->src[2];
  11473. b = op->src[1];
  11474. }
  11475. if (a->ne[3] != b->ne[3]) {
  11476. return false;
  11477. }
  11478. 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) ||
  11479. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  11480. return false;
  11481. }
  11482. if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) {
  11483. // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader.
  11484. // So don't support this combination for now.
  11485. return false;
  11486. }
  11487. return true;
  11488. }
  11489. case GGML_OP_FLASH_ATTN_EXT:
  11490. {
  11491. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11492. auto device = ggml_vk_get_device(ctx->device);
  11493. bool coopmat2 = device->coopmat2;
  11494. uint32_t HSK = op->src[1]->ne[0];
  11495. uint32_t HSV = op->src[2]->ne[0];
  11496. if ((HSK % 8) != 0 || (HSV % 8) != 0) {
  11497. return false;
  11498. }
  11499. if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) {
  11500. return false;
  11501. }
  11502. if (op->src[0]->type != GGML_TYPE_F32) {
  11503. return false;
  11504. }
  11505. if (op->type != GGML_TYPE_F32) {
  11506. return false;
  11507. }
  11508. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  11509. return false;
  11510. }
  11511. // It's straightforward to support different K/V dequant, but would
  11512. // significantly increase the number of pipelines
  11513. if (op->src[1]->type != op->src[2]->type) {
  11514. return false;
  11515. }
  11516. switch (op->src[1]->type) {
  11517. case GGML_TYPE_F16:
  11518. case GGML_TYPE_F32:
  11519. case GGML_TYPE_Q4_0:
  11520. case GGML_TYPE_Q8_0:
  11521. // supported in scalar and coopmat2 paths
  11522. break;
  11523. case GGML_TYPE_Q4_1:
  11524. case GGML_TYPE_Q5_0:
  11525. case GGML_TYPE_Q5_1:
  11526. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  11527. //case GGML_TYPE_Q2_K:
  11528. //case GGML_TYPE_Q3_K:
  11529. //case GGML_TYPE_Q4_K:
  11530. //case GGML_TYPE_Q5_K:
  11531. //case GGML_TYPE_Q6_K:
  11532. //case GGML_TYPE_IQ1_S:
  11533. //case GGML_TYPE_IQ1_M:
  11534. //case GGML_TYPE_IQ2_XXS:
  11535. //case GGML_TYPE_IQ2_XS:
  11536. //case GGML_TYPE_IQ2_S:
  11537. //case GGML_TYPE_IQ3_XXS:
  11538. //case GGML_TYPE_IQ3_S:
  11539. //case GGML_TYPE_IQ4_XS:
  11540. case GGML_TYPE_IQ4_NL:
  11541. // currently supported only in coopmat2 path
  11542. if (!coopmat2) {
  11543. return false;
  11544. }
  11545. break;
  11546. default:
  11547. return false;
  11548. }
  11549. if (!coopmat2 && !device->subgroup_shuffle) {
  11550. // scalar FA uses subgroupShuffle
  11551. return false;
  11552. }
  11553. return true;
  11554. }
  11555. case GGML_OP_GET_ROWS:
  11556. {
  11557. switch (op->src[0]->type) {
  11558. case GGML_TYPE_F32:
  11559. case GGML_TYPE_F16:
  11560. case GGML_TYPE_BF16:
  11561. case GGML_TYPE_Q4_0:
  11562. case GGML_TYPE_Q4_1:
  11563. case GGML_TYPE_Q5_0:
  11564. case GGML_TYPE_Q5_1:
  11565. case GGML_TYPE_Q8_0:
  11566. case GGML_TYPE_Q2_K:
  11567. case GGML_TYPE_Q3_K:
  11568. case GGML_TYPE_Q4_K:
  11569. case GGML_TYPE_Q5_K:
  11570. case GGML_TYPE_Q6_K:
  11571. case GGML_TYPE_IQ1_S:
  11572. case GGML_TYPE_IQ1_M:
  11573. case GGML_TYPE_IQ2_XXS:
  11574. case GGML_TYPE_IQ2_XS:
  11575. case GGML_TYPE_IQ2_S:
  11576. case GGML_TYPE_IQ3_XXS:
  11577. case GGML_TYPE_IQ3_S:
  11578. case GGML_TYPE_IQ4_XS:
  11579. case GGML_TYPE_IQ4_NL:
  11580. case GGML_TYPE_MXFP4:
  11581. return true;
  11582. default:
  11583. return false;
  11584. }
  11585. }
  11586. case GGML_OP_SET_ROWS:
  11587. {
  11588. switch (op->type) {
  11589. case GGML_TYPE_F32:
  11590. case GGML_TYPE_F16:
  11591. case GGML_TYPE_BF16:
  11592. case GGML_TYPE_Q4_0:
  11593. case GGML_TYPE_Q4_1:
  11594. case GGML_TYPE_Q5_0:
  11595. case GGML_TYPE_Q5_1:
  11596. case GGML_TYPE_Q8_0:
  11597. case GGML_TYPE_IQ4_NL:
  11598. return true;
  11599. default:
  11600. return false;
  11601. }
  11602. }
  11603. case GGML_OP_CONT:
  11604. case GGML_OP_CPY:
  11605. case GGML_OP_DUP:
  11606. {
  11607. ggml_type src0_type = op->src[0]->type;
  11608. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  11609. if (src0_type == GGML_TYPE_F32) {
  11610. switch (src1_type) {
  11611. case GGML_TYPE_F32:
  11612. case GGML_TYPE_F16:
  11613. case GGML_TYPE_BF16:
  11614. case GGML_TYPE_Q4_0:
  11615. case GGML_TYPE_Q4_1:
  11616. case GGML_TYPE_Q5_0:
  11617. case GGML_TYPE_Q5_1:
  11618. case GGML_TYPE_Q8_0:
  11619. case GGML_TYPE_IQ4_NL:
  11620. return true;
  11621. default:
  11622. break;
  11623. }
  11624. }
  11625. if (src1_type == GGML_TYPE_F32) {
  11626. switch (src0_type) {
  11627. case GGML_TYPE_F16:
  11628. case GGML_TYPE_Q4_0:
  11629. case GGML_TYPE_Q4_1:
  11630. case GGML_TYPE_Q5_0:
  11631. case GGML_TYPE_Q5_1:
  11632. case GGML_TYPE_Q8_0:
  11633. case GGML_TYPE_IQ4_NL:
  11634. return true;
  11635. default:
  11636. break;
  11637. }
  11638. }
  11639. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  11640. return true;
  11641. }
  11642. if (
  11643. (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) ||
  11644. (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32)
  11645. ) {
  11646. return true;
  11647. }
  11648. // We can handle copying from a type to the same type if it's
  11649. // contiguous (memcpy). We use f16 or f32 shaders to do the copy,
  11650. // so the type/block size must be a multiple of 4.
  11651. if (src0_type == src1_type &&
  11652. ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op) &&
  11653. (ggml_type_size(src0_type) % 2) == 0) {
  11654. return true;
  11655. }
  11656. return false;
  11657. }
  11658. case GGML_OP_REPEAT:
  11659. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  11660. case GGML_OP_REPEAT_BACK:
  11661. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32;
  11662. case GGML_OP_ROPE:
  11663. case GGML_OP_ROPE_BACK:
  11664. case GGML_OP_NONE:
  11665. case GGML_OP_RESHAPE:
  11666. case GGML_OP_VIEW:
  11667. case GGML_OP_PERMUTE:
  11668. case GGML_OP_TRANSPOSE:
  11669. case GGML_OP_RMS_NORM:
  11670. return true;
  11671. case GGML_OP_NORM:
  11672. case GGML_OP_GROUP_NORM:
  11673. case GGML_OP_L2_NORM:
  11674. return ggml_is_contiguous(op->src[0]);
  11675. case GGML_OP_ADD:
  11676. case GGML_OP_SUB:
  11677. case GGML_OP_MUL:
  11678. case GGML_OP_DIV:
  11679. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11680. (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
  11681. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  11682. case GGML_OP_ADD_ID:
  11683. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 &&
  11684. op->type == GGML_TYPE_F32;
  11685. case GGML_OP_SILU_BACK:
  11686. case GGML_OP_RMS_NORM_BACK:
  11687. case GGML_OP_SQR:
  11688. case GGML_OP_SQRT:
  11689. case GGML_OP_SIN:
  11690. case GGML_OP_COS:
  11691. case GGML_OP_CLAMP:
  11692. case GGML_OP_LEAKY_RELU:
  11693. case GGML_OP_OPT_STEP_ADAMW:
  11694. case GGML_OP_OPT_STEP_SGD:
  11695. return op->src[0]->type == GGML_TYPE_F32;
  11696. case GGML_OP_ARGSORT:
  11697. return op->ne[0] <= max_argsort_cols;
  11698. case GGML_OP_UPSCALE:
  11699. case GGML_OP_ACC:
  11700. case GGML_OP_CONCAT:
  11701. case GGML_OP_SCALE:
  11702. case GGML_OP_PAD:
  11703. case GGML_OP_ROLL:
  11704. case GGML_OP_DIAG_MASK_INF:
  11705. case GGML_OP_SOFT_MAX:
  11706. case GGML_OP_SOFT_MAX_BACK:
  11707. return true;
  11708. case GGML_OP_SUM:
  11709. case GGML_OP_SUM_ROWS:
  11710. case GGML_OP_MEAN:
  11711. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  11712. case GGML_OP_ARGMAX:
  11713. case GGML_OP_COUNT_EQUAL:
  11714. case GGML_OP_IM2COL:
  11715. case GGML_OP_IM2COL_3D:
  11716. case GGML_OP_TIMESTEP_EMBEDDING:
  11717. case GGML_OP_CONV_2D_DW:
  11718. case GGML_OP_POOL_2D:
  11719. case GGML_OP_RWKV_WKV6:
  11720. case GGML_OP_RWKV_WKV7:
  11721. return true;
  11722. case GGML_OP_SSM_SCAN:
  11723. {
  11724. for (int i = 0; i < 6; i++) {
  11725. if (op->src[i] && ggml_is_quantized(op->src[i]->type)) {
  11726. return false;
  11727. }
  11728. }
  11729. if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) {
  11730. return false;
  11731. }
  11732. if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
  11733. return false;
  11734. }
  11735. const uint32_t d_state = op->src[0]->ne[0];
  11736. const uint32_t head_dim = op->src[0]->ne[1];
  11737. bool is_mamba2 = (op->src[3] && op->src[3]->nb[1] == sizeof(float));
  11738. if (!is_mamba2) {
  11739. return false;
  11740. }
  11741. if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
  11742. return false;
  11743. }
  11744. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11745. const vk_device& device = ggml_vk_get_device(ctx->device);
  11746. const uint32_t SPLIT_H = 16;
  11747. size_t stateC_size = SPLIT_H * d_state * sizeof(float);
  11748. if (stateC_size > device->properties.limits.maxComputeSharedMemorySize) {
  11749. return false;
  11750. }
  11751. return true;
  11752. }
  11753. case GGML_OP_SSM_CONV:
  11754. return true;
  11755. case GGML_OP_CONV_TRANSPOSE_1D:
  11756. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  11757. case GGML_OP_CONV_2D:
  11758. case GGML_OP_CONV_TRANSPOSE_2D:
  11759. {
  11760. // Op is disabled for Apple because it segfaults at pipeline create time on MoltenVK
  11761. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11762. const vk_device& device = ggml_vk_get_device(ctx->device);
  11763. if (op->op == GGML_OP_CONV_TRANSPOSE_2D &&
  11764. device->properties.limits.maxPushConstantsSize < sizeof(vk_op_conv_transpose_2d_push_constants)) {
  11765. return false;
  11766. }
  11767. // Channel-contiguous format is not supported yet.
  11768. return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11769. op->src[1]->type == GGML_TYPE_F32 &&
  11770. op->type == GGML_TYPE_F32 &&
  11771. ggml_is_contiguous(op->src[0]) &&
  11772. ggml_is_contiguous(op->src[1]) &&
  11773. ggml_is_contiguous(op));
  11774. }
  11775. default:
  11776. return false;
  11777. }
  11778. UNUSED(dev);
  11779. }
  11780. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  11781. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  11782. return false;
  11783. }
  11784. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11785. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  11786. return buft_ctx->device->idx == ctx->device;
  11787. }
  11788. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  11789. const int min_batch_size = 32;
  11790. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  11791. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  11792. UNUSED(dev);
  11793. }
  11794. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  11795. /* .get_name = */ ggml_backend_vk_device_get_name,
  11796. /* .get_description = */ ggml_backend_vk_device_get_description,
  11797. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  11798. /* .get_type = */ ggml_backend_vk_device_get_type,
  11799. /* .get_props = */ ggml_backend_vk_device_get_props,
  11800. /* .init_backend = */ ggml_backend_vk_device_init,
  11801. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  11802. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  11803. /* .buffer_from_host_ptr = */ NULL,
  11804. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  11805. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  11806. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  11807. /* .event_new = */ NULL,
  11808. /* .event_free = */ NULL,
  11809. /* .event_synchronize = */ NULL,
  11810. };
  11811. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  11812. UNUSED(reg);
  11813. return GGML_VK_NAME;
  11814. }
  11815. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  11816. UNUSED(reg);
  11817. return ggml_backend_vk_get_device_count();
  11818. }
  11819. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  11820. static std::vector<ggml_backend_dev_t> devices;
  11821. static bool initialized = false;
  11822. {
  11823. static std::mutex mutex;
  11824. std::lock_guard<std::mutex> lock(mutex);
  11825. if (!initialized) {
  11826. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  11827. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  11828. char desc[256];
  11829. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  11830. ctx->device = i;
  11831. ctx->name = GGML_VK_NAME + std::to_string(i);
  11832. ctx->description = desc;
  11833. ctx->is_integrated_gpu = ggml_backend_vk_get_device_type(i) == vk::PhysicalDeviceType::eIntegratedGpu;
  11834. ctx->pci_bus_id = ggml_backend_vk_get_device_pci_id(i);
  11835. devices.push_back(new ggml_backend_device {
  11836. /* .iface = */ ggml_backend_vk_device_i,
  11837. /* .reg = */ reg,
  11838. /* .context = */ ctx,
  11839. });
  11840. }
  11841. initialized = true;
  11842. }
  11843. }
  11844. GGML_ASSERT(device < devices.size());
  11845. return devices[device];
  11846. }
  11847. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  11848. /* .get_name = */ ggml_backend_vk_reg_get_name,
  11849. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  11850. /* .get_device = */ ggml_backend_vk_reg_get_device,
  11851. /* .get_proc_address = */ NULL,
  11852. };
  11853. ggml_backend_reg_t ggml_backend_vk_reg() {
  11854. static ggml_backend_reg reg = {
  11855. /* .api_version = */ GGML_BACKEND_API_VERSION,
  11856. /* .iface = */ ggml_backend_vk_reg_i,
  11857. /* .context = */ nullptr,
  11858. };
  11859. try {
  11860. ggml_vk_instance_init();
  11861. return &reg;
  11862. } catch (const vk::SystemError& e) {
  11863. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what());
  11864. return nullptr;
  11865. } catch (const std::exception &e) {
  11866. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: " << e.what());
  11867. return nullptr;
  11868. } catch (...) {
  11869. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: unknown exception during Vulkan init");
  11870. return nullptr;
  11871. }
  11872. }
  11873. // Extension availability
  11874. static bool ggml_vk_instance_validation_ext_available() {
  11875. #ifdef GGML_VULKAN_VALIDATE
  11876. // Check if validation layer provides the extension
  11877. const std::string layer_name = "VK_LAYER_KHRONOS_validation";
  11878. for (const auto& layer : vk::enumerateInstanceLayerProperties()) {
  11879. if (layer_name == layer.layerName.data()) {
  11880. for (const auto& ext : vk::enumerateInstanceExtensionProperties(layer_name)) {
  11881. if (strcmp("VK_EXT_validation_features", ext.extensionName.data()) == 0) {
  11882. return true;
  11883. }
  11884. }
  11885. }
  11886. }
  11887. std::cerr << "ggml_vulkan: WARNING: Validation layer or layer extension VK_EXT_validation_features not found." << std::endl;
  11888. #endif
  11889. return false;
  11890. }
  11891. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  11892. #ifdef __APPLE__
  11893. // Check for portability enumeration extension for MoltenVK support
  11894. for (const auto& properties : instance_extensions) {
  11895. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  11896. return true;
  11897. }
  11898. }
  11899. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  11900. #endif
  11901. return false;
  11902. UNUSED(instance_extensions);
  11903. }
  11904. // Extension availability
  11905. static bool ggml_vk_instance_debug_utils_ext_available(
  11906. const std::vector<vk::ExtensionProperties> & instance_extensions) {
  11907. // Check for portability enumeration extension for MoltenVK support
  11908. for (const auto & properties : instance_extensions) {
  11909. if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) {
  11910. return true;
  11911. }
  11912. }
  11913. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl;
  11914. return false;
  11915. UNUSED(instance_extensions);
  11916. }
  11917. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev) {
  11918. VkPhysicalDeviceFeatures2 device_features2;
  11919. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  11920. VkPhysicalDeviceVulkan11Features vk11_features;
  11921. vk11_features.pNext = nullptr;
  11922. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  11923. device_features2.pNext = &vk11_features;
  11924. vkGetPhysicalDeviceFeatures2(vkdev, &device_features2);
  11925. return vk11_features.storageBuffer16BitAccess;
  11926. }
  11927. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) {
  11928. switch (props.vendorID) {
  11929. case VK_VENDOR_ID_INTEL:
  11930. // Only allowing Xe2 GPU at the moment since Xe2 GPU can gain significant performance boost,
  11931. // while some older hardware (ex. Arc A770) has performance regressions
  11932. return arch == vk_device_architecture::INTEL_XE2;
  11933. case VK_VENDOR_ID_AMD:
  11934. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  11935. // Workaround for AMD proprietary driver reporting support on all GPUs
  11936. return arch == vk_device_architecture::AMD_RDNA3;
  11937. }
  11938. return true;
  11939. default:
  11940. return true;
  11941. }
  11942. }
  11943. // checks
  11944. #ifdef GGML_VULKAN_CHECK_RESULTS
  11945. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  11946. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  11947. return;
  11948. }
  11949. for (int j = 0; j < level; j++) {
  11950. std::cerr << " ";
  11951. }
  11952. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  11953. done.push_back(tensor);
  11954. for (int i = 0; i < GGML_MAX_SRC; i++) {
  11955. if (tensor->src[i] != nullptr) {
  11956. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  11957. }
  11958. }
  11959. }
  11960. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  11961. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  11962. return;
  11963. }
  11964. i0 = std::max(i0, 5);
  11965. i1 = std::max(i1, 5);
  11966. i2 = std::max(i2, 0);
  11967. i3 = std::max(i3, 0);
  11968. fprintf(stderr, " ");
  11969. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  11970. fprintf(stderr, "%7d ", idx1);
  11971. }
  11972. fprintf(stderr, "\n");
  11973. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  11974. fprintf(stderr, "%7d: ", idx0);
  11975. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  11976. 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]) {
  11977. float val;
  11978. if (tensor->type == GGML_TYPE_F32) {
  11979. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  11980. } else if (tensor->type == GGML_TYPE_F16) {
  11981. 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]));
  11982. } else if (tensor->type == GGML_TYPE_I32) {
  11983. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  11984. } else {
  11985. GGML_ABORT("fatal error");
  11986. }
  11987. fprintf(stderr, "% 7.2f ", val);
  11988. } else {
  11989. fprintf(stderr, " ");
  11990. }
  11991. }
  11992. fprintf(stderr, "\n");
  11993. }
  11994. }
  11995. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  11996. void * tensor_data = tensor->data;
  11997. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  11998. if (is_gpu) {
  11999. const size_t tensor_size = ggml_nbytes(tensor);
  12000. tensor_data = malloc(tensor_size);
  12001. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12002. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  12003. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  12004. }
  12005. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  12006. 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;
  12007. if (tensor->src[0] != nullptr) {
  12008. 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;
  12009. }
  12010. if (tensor->src[1] != nullptr) {
  12011. 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;
  12012. }
  12013. std::cerr << std::endl << "Result:" << std::endl;
  12014. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  12015. std::cerr << std::endl;
  12016. std::vector<const ggml_tensor *> done;
  12017. ggml_vk_print_graph_origin(tensor, done);
  12018. if (is_gpu) {
  12019. free(tensor_data);
  12020. }
  12021. }
  12022. void * comp_result;
  12023. size_t comp_size;
  12024. size_t comp_nb[GGML_MAX_DIMS];
  12025. size_t check_counter = 0;
  12026. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12027. ggml_tensor * tensor = cgraph->nodes[tensor_idx];
  12028. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12029. return;
  12030. }
  12031. bool fused_rms_norm_mul = false;
  12032. int rms_norm_idx = -1;
  12033. if (ctx->num_additional_fused_ops == 1 &&
  12034. tensor->op == GGML_OP_RMS_NORM &&
  12035. cgraph->nodes[tensor_idx + 1]->op == GGML_OP_MUL) {
  12036. fused_rms_norm_mul = true;
  12037. tensor = cgraph->nodes[tensor_idx + 1];
  12038. }
  12039. check_counter++;
  12040. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12041. return;
  12042. }
  12043. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  12044. ggml_tensor * src0 = tensor->src[0];
  12045. ggml_tensor * src1 = tensor->src[1];
  12046. struct ggml_init_params iparams = {
  12047. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  12048. /*.mem_buffer =*/ NULL,
  12049. /*.no_alloc =*/ false,
  12050. };
  12051. struct ggml_context * ggml_ctx = ggml_init(iparams);
  12052. std::array<struct ggml_tensor *, GGML_MAX_SRC> src_clone = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  12053. std::array<size_t, GGML_MAX_SRC> src_size = {};
  12054. std::array<void *, GGML_MAX_SRC> src_buffer = {};
  12055. const char * srci_name[GGML_MAX_SRC] = {"src0", "src1", "src2", "src3", "src4", "src5", "src6", "src7", "src8", "src9"};
  12056. struct ggml_tensor * tensor_clone = nullptr;
  12057. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12058. ggml_tensor * srci = tensor->src[i];
  12059. if (fused_rms_norm_mul) {
  12060. rms_norm_idx = tensor->src[0]->op == GGML_OP_RMS_NORM ? 0 : 1;
  12061. ggml_tensor *rms_norm = tensor->src[rms_norm_idx];
  12062. switch (i) {
  12063. case 0: srci = rms_norm->src[0]; break;
  12064. case 1: srci = tensor->src[1 - rms_norm_idx]; break;
  12065. default: continue;
  12066. }
  12067. }
  12068. if (srci == nullptr) {
  12069. continue;
  12070. }
  12071. ggml_tensor * srci_clone = ggml_dup_tensor(ggml_ctx, srci);
  12072. size_t srci_size = ggml_nbytes(srci);
  12073. src_clone[i] = srci_clone;
  12074. src_size[i] = ggml_nbytes(srci);
  12075. src_buffer[i] = malloc(srci_size);
  12076. srci_clone->data = src_buffer[i];
  12077. if (ggml_backend_buffer_is_host(srci->buffer)) {
  12078. memcpy(srci_clone->data, srci->data, srci_size);
  12079. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12080. } else if (ggml_backend_buffer_is_vk(srci->buffer)) {
  12081. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)srci->buffer->context;
  12082. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12083. uint64_t offset = vk_tensor_offset(srci) + srci->view_offs;
  12084. if (!ggml_is_contiguous(srci) && ggml_vk_dim01_contiguous(srci)) {
  12085. for (int i3 = 0; i3 < srci->ne[3]; i3++) {
  12086. for (int i2 = 0; i2 < srci->ne[2]; i2++) {
  12087. const int idx = i3*srci->ne[2] + i2;
  12088. 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]);
  12089. }
  12090. }
  12091. srci_clone->nb[0] = srci->nb[0];
  12092. srci_clone->nb[1] = srci->nb[1];
  12093. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  12094. srci_clone->nb[i] = srci_clone->nb[i - 1]*srci_clone->ne[i - 1];
  12095. }
  12096. } else {
  12097. if (offset + srci_size >= buffer_gpu->size) {
  12098. srci_size = buffer_gpu->size - offset;
  12099. }
  12100. ggml_vk_buffer_read(buffer_gpu, offset, srci_clone->data, srci_size);
  12101. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12102. }
  12103. } else {
  12104. GGML_ABORT("fatal error");
  12105. }
  12106. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12107. ggml_vk_print_tensor(srci, srci_name[i]);
  12108. }
  12109. }
  12110. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  12111. const float * params = (const float *)tensor->op_params;
  12112. 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]);
  12113. if (src_clone[4]) {
  12114. ggml_flash_attn_ext_add_sinks(tensor_clone, src_clone[4]);
  12115. }
  12116. } else if (tensor->op == GGML_OP_MUL_MAT) {
  12117. tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
  12118. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  12119. tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12120. } else if (tensor->op == GGML_OP_SUB) {
  12121. tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
  12122. } else if (tensor->op == GGML_OP_MUL) {
  12123. if (fused_rms_norm_mul) {
  12124. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->src[rms_norm_idx]->op_params);
  12125. tensor_clone = ggml_mul(ggml_ctx, tensor_clone, src_clone[1 - rms_norm_idx]);
  12126. } else {
  12127. tensor_clone = ggml_mul(ggml_ctx, src_clone[0], src_clone[1]);
  12128. }
  12129. } else if (tensor->op == GGML_OP_DIV) {
  12130. tensor_clone = ggml_div(ggml_ctx, src_clone[0], src_clone[1]);
  12131. } else if (tensor->op == GGML_OP_CONCAT) {
  12132. tensor_clone = ggml_concat(ggml_ctx, src_clone[0], src_clone[1], *(int *)tensor->op_params);
  12133. } else if (tensor->op == GGML_OP_UPSCALE) {
  12134. 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]);
  12135. } else if (tensor->op == GGML_OP_SCALE) {
  12136. const float * params = (const float *)tensor->op_params;
  12137. tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]);
  12138. } else if (tensor->op == GGML_OP_SQR) {
  12139. tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]);
  12140. } else if (tensor->op == GGML_OP_SQRT) {
  12141. tensor_clone = ggml_sqrt(ggml_ctx, src_clone[0]);
  12142. } else if (tensor->op == GGML_OP_SIN) {
  12143. tensor_clone = ggml_sin(ggml_ctx, src_clone[0]);
  12144. } else if (tensor->op == GGML_OP_COS) {
  12145. tensor_clone = ggml_cos(ggml_ctx, src_clone[0]);
  12146. } else if (tensor->op == GGML_OP_CLAMP) {
  12147. const float * params = (const float *)tensor->op_params;
  12148. tensor_clone = ggml_clamp(ggml_ctx, src_clone[0], params[0], params[1]);
  12149. } else if (tensor->op == GGML_OP_PAD) {
  12150. 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],
  12151. tensor->op_params[4], tensor->op_params[5], tensor->op_params[6], tensor->op_params[7]);
  12152. } else if (tensor->op == GGML_OP_REPEAT) {
  12153. tensor_clone = ggml_repeat(ggml_ctx, src_clone[0], tensor);
  12154. } else if (tensor->op == GGML_OP_REPEAT_BACK) {
  12155. tensor_clone = ggml_repeat_back(ggml_ctx, src_clone[0], tensor);
  12156. } else if (tensor->op == GGML_OP_ADD) {
  12157. tensor_clone = ggml_add(ggml_ctx, src_clone[0], src_clone[1]);
  12158. } else if (tensor->op == GGML_OP_ACC) {
  12159. 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]);
  12160. } else if (tensor->op == GGML_OP_NORM) {
  12161. tensor_clone = ggml_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12162. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  12163. const float * float_params = (const float *)tensor->op_params;
  12164. tensor_clone = ggml_group_norm(ggml_ctx, src_clone[0], tensor->op_params[0], float_params[1]);
  12165. } else if (tensor->op == GGML_OP_RMS_NORM) {
  12166. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12167. } else if (tensor->op == GGML_OP_RMS_NORM_BACK) {
  12168. const float eps = ((float *) tensor->op_params)[0];
  12169. tensor_clone = ggml_rms_norm_back(ggml_ctx, src_clone[0], src_clone[1], eps);
  12170. } else if (tensor->op == GGML_OP_SILU_BACK) {
  12171. tensor_clone = ggml_silu_back(ggml_ctx, src_clone[0], src_clone[1]);
  12172. } else if (tensor->op == GGML_OP_L2_NORM) {
  12173. const float eps = ((float *) tensor->op_params)[0];
  12174. tensor_clone = ggml_l2_norm(ggml_ctx, src_clone[0], eps);
  12175. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  12176. if (src1 != nullptr) {
  12177. const float * params = (const float *)tensor->op_params;
  12178. tensor_clone = ggml_soft_max_ext(ggml_ctx, src_clone[0], src_clone[1], params[0], params[1]);
  12179. } else {
  12180. tensor_clone = ggml_soft_max(ggml_ctx, src_clone[0]);
  12181. }
  12182. } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) {
  12183. 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]);
  12184. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  12185. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]);
  12186. } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) {
  12187. const int n_dims = ((int32_t *) tensor->op_params)[1];
  12188. const int mode = ((int32_t *) tensor->op_params)[2];
  12189. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  12190. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  12191. const float freq_base = ((float *) tensor->op_params)[5];
  12192. const float freq_scale = ((float *) tensor->op_params)[6];
  12193. const float ext_factor = ((float *) tensor->op_params)[7];
  12194. const float attn_factor = ((float *) tensor->op_params)[8];
  12195. const float beta_fast = ((float *) tensor->op_params)[9];
  12196. const float beta_slow = ((float *) tensor->op_params)[10];
  12197. if (mode & GGML_ROPE_TYPE_MROPE) {
  12198. int32_t *sections = ((int32_t *) tensor->op_params) + 11;
  12199. if (tensor->op == GGML_OP_ROPE) {
  12200. 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);
  12201. } else {
  12202. 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);
  12203. }
  12204. } else {
  12205. if (tensor->op == GGML_OP_ROPE) {
  12206. 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);
  12207. } else {
  12208. 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);
  12209. }
  12210. }
  12211. } else if (tensor->op == GGML_OP_UNARY) {
  12212. switch (ggml_get_unary_op(tensor)) {
  12213. case GGML_UNARY_OP_EXP:
  12214. tensor_clone = ggml_exp(ggml_ctx, src_clone[0]);
  12215. break;
  12216. case GGML_UNARY_OP_SILU:
  12217. tensor_clone = ggml_silu(ggml_ctx, src_clone[0]);
  12218. break;
  12219. case GGML_UNARY_OP_GELU:
  12220. tensor_clone = ggml_gelu(ggml_ctx, src_clone[0]);
  12221. break;
  12222. case GGML_UNARY_OP_GELU_ERF:
  12223. tensor_clone = ggml_gelu_erf(ggml_ctx, src_clone[0]);
  12224. break;
  12225. case GGML_UNARY_OP_GELU_QUICK:
  12226. tensor_clone = ggml_gelu_quick(ggml_ctx, src_clone[0]);
  12227. break;
  12228. case GGML_UNARY_OP_RELU:
  12229. tensor_clone = ggml_relu(ggml_ctx, src_clone[0]);
  12230. break;
  12231. case GGML_UNARY_OP_TANH:
  12232. tensor_clone = ggml_tanh(ggml_ctx, src_clone[0]);
  12233. break;
  12234. case GGML_UNARY_OP_SIGMOID:
  12235. tensor_clone = ggml_sigmoid(ggml_ctx, src_clone[0]);
  12236. break;
  12237. case GGML_UNARY_OP_HARDSIGMOID:
  12238. tensor_clone = ggml_hardsigmoid(ggml_ctx, src_clone[0]);
  12239. break;
  12240. case GGML_UNARY_OP_HARDSWISH:
  12241. tensor_clone = ggml_hardswish(ggml_ctx, src_clone[0]);
  12242. break;
  12243. default:
  12244. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12245. GGML_ABORT("fatal error");
  12246. }
  12247. } else if (tensor->op == GGML_OP_GLU) {
  12248. if (src_clone[1] == nullptr) {
  12249. tensor_clone = ggml_glu(ggml_ctx, src_clone[0], (ggml_glu_op) tensor->op_params[0], tensor->op_params[1]);
  12250. } else {
  12251. tensor_clone = ggml_glu_split(ggml_ctx, src_clone[0], src_clone[1], (ggml_glu_op) tensor->op_params[0]);
  12252. }
  12253. ggml_set_op_params_i32(tensor_clone, 2, ggml_get_op_params_i32(tensor, 2));
  12254. ggml_set_op_params_i32(tensor_clone, 3, ggml_get_op_params_i32(tensor, 3));
  12255. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  12256. if (src1 == nullptr) {
  12257. tensor_clone = ggml_dup(ggml_ctx, src_clone[0]);
  12258. tensor_clone->type = tensor->type;
  12259. } else {
  12260. tensor_clone = ggml_cpy(ggml_ctx, src_clone[0], src_clone[1]);
  12261. }
  12262. } else if (tensor->op == GGML_OP_CONT) {
  12263. tensor_clone = ggml_cont_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12264. } else if (tensor->op == GGML_OP_RESHAPE) {
  12265. tensor_clone = ggml_reshape_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12266. } else if (tensor->op == GGML_OP_VIEW) {
  12267. 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]);
  12268. } else if (tensor->op == GGML_OP_PERMUTE) {
  12269. int32_t * params = (int32_t *)tensor->op_params;
  12270. tensor_clone = ggml_permute(ggml_ctx, src_clone[0], params[0], params[1], params[2], params[3]);
  12271. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  12272. tensor_clone = ggml_transpose(ggml_ctx, src_clone[0]);
  12273. } else if (tensor->op == GGML_OP_GET_ROWS) {
  12274. tensor_clone = ggml_get_rows(ggml_ctx, src_clone[0], src_clone[1]);
  12275. } else if (tensor->op == GGML_OP_ARGSORT) {
  12276. tensor_clone = ggml_argsort(ggml_ctx, src_clone[0], (ggml_sort_order) *(int *)tensor->op_params);
  12277. } else if (tensor->op == GGML_OP_SUM) {
  12278. tensor_clone = ggml_sum(ggml_ctx, src_clone[0]);
  12279. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  12280. tensor_clone = ggml_sum_rows(ggml_ctx, src_clone[0]);
  12281. } else if (tensor->op == GGML_OP_MEAN) {
  12282. tensor_clone = ggml_mean(ggml_ctx, src_clone[0]);
  12283. } else if (tensor->op == GGML_OP_ARGMAX) {
  12284. tensor_clone = ggml_argmax(ggml_ctx, src_clone[0]);
  12285. } else if (tensor->op == GGML_OP_COUNT_EQUAL) {
  12286. tensor_clone = ggml_count_equal(ggml_ctx, src_clone[0], src_clone[1]);
  12287. } else if (tensor->op == GGML_OP_IM2COL) {
  12288. const int32_t s0 = tensor->op_params[0];
  12289. const int32_t s1 = tensor->op_params[1];
  12290. const int32_t p0 = tensor->op_params[2];
  12291. const int32_t p1 = tensor->op_params[3];
  12292. const int32_t d0 = tensor->op_params[4];
  12293. const int32_t d1 = tensor->op_params[5];
  12294. const bool is_2D = tensor->op_params[6] == 1;
  12295. tensor_clone = ggml_im2col(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  12296. } else if (tensor->op == GGML_OP_IM2COL_3D) {
  12297. const int32_t s0 = tensor->op_params[0];
  12298. const int32_t s1 = tensor->op_params[1];
  12299. const int32_t s2 = tensor->op_params[2];
  12300. const int32_t p0 = tensor->op_params[3];
  12301. const int32_t p1 = tensor->op_params[4];
  12302. const int32_t p2 = tensor->op_params[5];
  12303. const int32_t d0 = tensor->op_params[6];
  12304. const int32_t d1 = tensor->op_params[7];
  12305. const int32_t d2 = tensor->op_params[8];
  12306. const int32_t IC = tensor->op_params[9];
  12307. 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);
  12308. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  12309. const int32_t dim = tensor->op_params[0];
  12310. const int32_t max_period = tensor->op_params[1];
  12311. tensor_clone = ggml_timestep_embedding(ggml_ctx, src_clone[0], dim, max_period);
  12312. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_1D){
  12313. const int32_t s0 = tensor->op_params[0];
  12314. const int32_t p0 = tensor->op_params[1];
  12315. const int32_t d0 = tensor->op_params[2];
  12316. tensor_clone = ggml_conv_transpose_1d(ggml_ctx, src_clone[0], src_clone[1], s0, p0, d0);
  12317. } else if (tensor->op == GGML_OP_POOL_2D) {
  12318. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  12319. const int32_t k0 = tensor->op_params[1];
  12320. const int32_t k1 = tensor->op_params[2];
  12321. const int32_t s0 = tensor->op_params[3];
  12322. const int32_t s1 = tensor->op_params[4];
  12323. const int32_t p0 = tensor->op_params[5];
  12324. const int32_t p1 = tensor->op_params[6];
  12325. tensor_clone = ggml_pool_2d(ggml_ctx, src_clone[0], op, k0, k1, s0, s1, p0, p1);
  12326. } else if (tensor->op == GGML_OP_CONV_2D) {
  12327. const int32_t s0 = tensor->op_params[0];
  12328. const int32_t s1 = tensor->op_params[1];
  12329. const int32_t p0 = tensor->op_params[2];
  12330. const int32_t p1 = tensor->op_params[3];
  12331. const int32_t d0 = tensor->op_params[4];
  12332. const int32_t d1 = tensor->op_params[5];
  12333. tensor_clone = ggml_conv_2d(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  12334. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_2D) {
  12335. const int32_t s = tensor->op_params[0];
  12336. tensor_clone = ggml_conv_transpose_2d_p0(ggml_ctx, src_clone[0], src_clone[1], s);
  12337. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  12338. const float * op_params = (const float *)tensor->op_params;
  12339. tensor_clone = ggml_leaky_relu(ggml_ctx, src_clone[0], op_params[0], false);
  12340. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  12341. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, src_clone[0], src_clone[1],
  12342. src_clone[2], src_clone[3], src_clone[4], src_clone[5]);
  12343. } else if (tensor->op == GGML_OP_RWKV_WKV7) {
  12344. tensor_clone = ggml_rwkv_wkv7(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3],
  12345. src_clone[4], src_clone[5], src_clone[6]);
  12346. } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
  12347. src_clone[0]->flags = src0->flags;
  12348. tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
  12349. src_clone[2], src_clone[3], src_clone[4]);
  12350. } else if (tensor->op == GGML_OP_OPT_STEP_SGD) {
  12351. src_clone[0]->flags = src0->flags;
  12352. tensor_clone = ggml_opt_step_sgd(ggml_ctx, src_clone[0], src_clone[1],
  12353. src_clone[2]);
  12354. } else if (tensor->op == GGML_OP_ADD_ID) {
  12355. tensor_clone = ggml_add_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12356. } else if (tensor->op == GGML_OP_SSM_SCAN) {
  12357. tensor_clone = ggml_ssm_scan(ggml_ctx, src_clone[0], src_clone[1], src_clone[2],
  12358. src_clone[3], src_clone[4], src_clone[5], src_clone[6]);
  12359. } else if (tensor->op == GGML_OP_SSM_CONV) {
  12360. tensor_clone = ggml_ssm_conv(ggml_ctx, src_clone[0], src_clone[1]);
  12361. }
  12362. else {
  12363. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12364. GGML_ABORT("fatal error");
  12365. }
  12366. ggml_cgraph * cgraph_cpu = ggml_new_graph(ggml_ctx);
  12367. ggml_build_forward_expand(cgraph_cpu, tensor_clone);
  12368. ggml_graph_compute_with_ctx(ggml_ctx, cgraph_cpu, 8);
  12369. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12370. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  12371. }
  12372. comp_size = ggml_nbytes(tensor_clone);
  12373. comp_result = malloc(comp_size);
  12374. memcpy(comp_result, tensor_clone->data, comp_size);
  12375. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12376. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12377. if (src_buffer[i] != nullptr) {
  12378. free(src_buffer[i]);
  12379. }
  12380. }
  12381. ggml_free(ggml_ctx);
  12382. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  12383. }
  12384. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12385. ggml_tensor * tensor = cgraph->nodes[tensor_idx];
  12386. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12387. return;
  12388. }
  12389. if (ctx->num_additional_fused_ops == 1 &&
  12390. tensor->op == GGML_OP_RMS_NORM &&
  12391. cgraph->nodes[tensor_idx + 1]->op == GGML_OP_MUL) {
  12392. tensor = cgraph->nodes[tensor_idx + 1];
  12393. }
  12394. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12395. return;
  12396. }
  12397. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  12398. ggml_tensor * src0 = tensor->src[0];
  12399. ggml_tensor * src1 = tensor->src[1];
  12400. ggml_tensor * src2 = tensor->src[2];
  12401. ggml_tensor * src3 = tensor->src[3];
  12402. void * tensor_data = tensor->data;
  12403. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  12404. size_t tensor_size = ggml_nbytes(tensor);
  12405. tensor_data = malloc(tensor_size);
  12406. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12407. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12408. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  12409. if (offset + tensor_size >= buffer_gpu->size) {
  12410. tensor_size = buffer_gpu->size - offset;
  12411. }
  12412. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  12413. }
  12414. float first_error_result = -1.0f;
  12415. float first_error_correct = -1.0f;
  12416. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  12417. double avg_err = 0.0;
  12418. size_t counter = 0;
  12419. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  12420. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  12421. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  12422. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  12423. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  12424. float correct = 0.0f;
  12425. float result = 0.0f;
  12426. if (buffer_size_fit) {
  12427. if (tensor->type == GGML_TYPE_F32) {
  12428. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12429. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12430. } else if (tensor->type == GGML_TYPE_F16) {
  12431. 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]));
  12432. 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]));
  12433. } else if (tensor->type == GGML_TYPE_BF16) {
  12434. 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]));
  12435. 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]));
  12436. } else if (tensor->type == GGML_TYPE_I32) {
  12437. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12438. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12439. } else if (tensor->type == GGML_TYPE_I64) {
  12440. correct = *(int64_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12441. result = *(int64_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12442. } else {
  12443. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  12444. }
  12445. } else {
  12446. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  12447. GGML_ABORT("fatal error");
  12448. }
  12449. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  12450. 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;
  12451. 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;
  12452. if (src0 != nullptr) {
  12453. 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;
  12454. }
  12455. if (src1 != nullptr) {
  12456. 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;
  12457. }
  12458. if (src2 != nullptr) {
  12459. 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;
  12460. }
  12461. if (src3 != nullptr) {
  12462. 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;
  12463. }
  12464. 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;
  12465. std::cerr << std::endl << "Result:" << std::endl;
  12466. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  12467. std::cerr << std::endl << "Correct:" << std::endl;
  12468. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  12469. std::cerr << std::endl;
  12470. std::vector<const ggml_tensor *> done;
  12471. ggml_vk_print_graph_origin(tensor, done);
  12472. GGML_ABORT("fatal error");
  12473. }
  12474. const double denom = std::fabs(correct) > 1.0f ? (std::fabs(correct) > 1e-8 ? std::fabs(correct) : 1e-8) : 1.0f;
  12475. if (first_error[0] == -1 && std::fabs(correct - result) / denom > 0.5) {
  12476. first_error[0] = i0;
  12477. first_error[1] = i1;
  12478. first_error[2] = i2;
  12479. first_error[3] = i3;
  12480. first_error_result = result;
  12481. first_error_correct = correct;
  12482. }
  12483. // Special case, value is infinite, avoid NaN result in avg_err
  12484. // NaN also appears in results, if both are nan error is 0
  12485. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  12486. avg_err += std::fabs(correct - result) / denom;
  12487. }
  12488. counter++;
  12489. }
  12490. }
  12491. }
  12492. }
  12493. avg_err /= counter;
  12494. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12495. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  12496. 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;
  12497. if (src0 != nullptr) {
  12498. 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;
  12499. }
  12500. if (src1 != nullptr) {
  12501. 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;
  12502. }
  12503. if (src2 != nullptr) {
  12504. 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;
  12505. }
  12506. if (src3 != nullptr) {
  12507. 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;
  12508. }
  12509. 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;
  12510. std::cerr << std::endl << "Result:" << std::endl;
  12511. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  12512. std::cerr << std::endl << "Correct:" << std::endl;
  12513. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  12514. std::cerr << std::endl;
  12515. std::vector<const ggml_tensor *> done;
  12516. ggml_vk_print_graph_origin(tensor, done);
  12517. }
  12518. if (avg_err > 0.5 || std::isnan(avg_err)) {
  12519. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  12520. 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;
  12521. if (src0 != nullptr) {
  12522. 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;
  12523. }
  12524. if (src1 != nullptr) {
  12525. 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;
  12526. }
  12527. if (src2 != nullptr) {
  12528. 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;
  12529. }
  12530. if (src3 != nullptr) {
  12531. 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;
  12532. }
  12533. 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;
  12534. std::cerr << std::endl << "Result:" << std::endl;
  12535. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  12536. std::cerr << std::endl << "Correct:" << std::endl;
  12537. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  12538. std::cerr << std::endl;
  12539. std::vector<const ggml_tensor *> done;
  12540. ggml_vk_print_graph_origin(tensor, done);
  12541. GGML_ABORT("fatal error");
  12542. } else {
  12543. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  12544. }
  12545. free(comp_result);
  12546. comp_result = nullptr;
  12547. comp_size = 0;
  12548. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  12549. free(tensor_data);
  12550. }
  12551. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  12552. }
  12553. #endif
  12554. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)