ggml-vulkan.cpp 431 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890
  1. #include "ggml-vulkan.h"
  2. #include <vulkan/vulkan_core.h>
  3. #if defined(GGML_VULKAN_RUN_TESTS) || defined(GGML_VULKAN_PERF) || defined(GGML_VULKAN_CHECK_RESULTS)
  4. #include <chrono>
  5. #include "ggml-cpu.h"
  6. #endif
  7. #include <vulkan/vulkan.hpp>
  8. #include <algorithm>
  9. #include <cmath>
  10. #include <iomanip>
  11. #include <iostream>
  12. #include <tuple>
  13. #include <vector>
  14. #include <sstream>
  15. #include <utility>
  16. #include <memory>
  17. #include <limits>
  18. #include <map>
  19. #include <unordered_map>
  20. #include <memory>
  21. #include <mutex>
  22. #include <future>
  23. #include <thread>
  24. #include "ggml-impl.h"
  25. #include "ggml-backend-impl.h"
  26. #include "ggml-vulkan-shaders.hpp"
  27. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  28. #define VK_VENDOR_ID_AMD 0x1002
  29. #define VK_VENDOR_ID_APPLE 0x106b
  30. #define VK_VENDOR_ID_INTEL 0x8086
  31. #define VK_VENDOR_ID_NVIDIA 0x10de
  32. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 32
  33. #define GGML_VK_MAX_NODES 8192
  34. #define MAX_VK_BUFFERS 256
  35. #define VK_CHECK(err, msg) \
  36. do { \
  37. vk::Result err_ = (err); \
  38. if (err_ != vk::Result::eSuccess) { \
  39. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  40. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  41. exit(1); \
  42. } \
  43. } while (0)
  44. #ifdef GGML_VULKAN_DEBUG
  45. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  46. #else
  47. #define VK_LOG_DEBUG(msg) ((void) 0)
  48. #endif // GGML_VULKAN_DEBUG
  49. struct ggml_backend_vk_context;
  50. struct vk_queue {
  51. uint32_t queue_family_index;
  52. vk::Queue queue;
  53. vk::CommandPool pool;
  54. uint32_t cmd_buffer_idx;
  55. std::vector<vk::CommandBuffer> cmd_buffers;
  56. vk::PipelineStageFlags stage_flags;
  57. bool transfer_only;
  58. };
  59. struct vk_pipeline_struct {
  60. std::string name;
  61. vk::ShaderModule shader_module;
  62. vk::DescriptorSetLayout dsl;
  63. std::vector<vk::DescriptorPool> descriptor_pools;
  64. std::vector<vk::DescriptorSet> descriptor_sets;
  65. uint32_t descriptor_set_idx;
  66. vk::PipelineLayout layout;
  67. vk::Pipeline pipeline;
  68. uint32_t push_constant_size;
  69. uint32_t parameter_count;
  70. std::array<uint32_t, 3> wg_denoms;
  71. uint32_t align;
  72. // set to true to request the pipeline is compiled after the dryrun
  73. bool needed {};
  74. // set to true when the shader has been compiled
  75. bool compiled {};
  76. };
  77. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  78. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  79. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  80. struct vk_matmul_pipeline_struct {
  81. vk_pipeline l, m, s;
  82. vk_pipeline a_l, a_m, a_s;
  83. };
  84. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  85. struct vk_matmul_pipeline2 {
  86. vk_matmul_pipeline2() {
  87. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  88. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  89. }
  90. vk_matmul_pipeline f32acc;
  91. vk_matmul_pipeline f16acc;
  92. };
  93. struct vk_device_struct;
  94. typedef std::shared_ptr<vk_device_struct> vk_device;
  95. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  96. struct vk_buffer_struct;
  97. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  98. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  99. struct ggml_backend_vk_buffer_type_context {
  100. std::string name;
  101. vk_device device;
  102. };
  103. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  104. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  105. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  106. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  107. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  108. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  109. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  110. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  111. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  112. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  113. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  114. /* .is_host = */ NULL,
  115. };
  116. #ifdef GGML_VULKAN_MEMORY_DEBUG
  117. class vk_memory_logger;
  118. #endif
  119. #ifdef GGML_VULKAN_PERF
  120. class vk_perf_logger;
  121. #endif
  122. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  123. static constexpr uint32_t mul_mat_vec_max_cols = 8;
  124. struct vk_device_struct {
  125. std::mutex mutex;
  126. vk::PhysicalDevice physical_device;
  127. vk::PhysicalDeviceProperties properties;
  128. std::string name;
  129. uint64_t max_memory_allocation_size;
  130. bool fp16;
  131. bool pipeline_robustness;
  132. vk::Device device;
  133. uint32_t vendor_id;
  134. vk_queue compute_queue;
  135. vk_queue transfer_queue;
  136. bool single_queue;
  137. uint32_t subgroup_size;
  138. uint32_t shader_core_count;
  139. bool uma;
  140. bool float_controls_rte_fp16;
  141. bool subgroup_size_control;
  142. uint32_t subgroup_min_size;
  143. uint32_t subgroup_max_size;
  144. bool subgroup_require_full_support;
  145. bool coopmat_support;
  146. bool coopmat_acc_f32_support;
  147. bool coopmat_acc_f16_support;
  148. uint32_t coopmat_m;
  149. uint32_t coopmat_n;
  150. uint32_t coopmat_k;
  151. bool coopmat2;
  152. size_t idx;
  153. bool mul_mat_l;
  154. bool mul_mat_m;
  155. bool mul_mat_s;
  156. bool mul_mat_id_l;
  157. bool mul_mat_id_m;
  158. bool mul_mat_id_s;
  159. // set to true to indicate that some shaders need to be compiled after the dryrun
  160. bool need_compiles {};
  161. vk_matmul_pipeline pipeline_matmul_f32 {};
  162. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  163. vk_matmul_pipeline2 pipeline_matmul_f16;
  164. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  165. vk_pipeline pipeline_matmul_split_k_reduce;
  166. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  167. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  168. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  169. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  170. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  171. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  172. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  173. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  174. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  175. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_COUNT];
  176. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32;
  177. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  178. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  179. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  180. vk_pipeline pipeline_acc_f32;
  181. vk_pipeline pipeline_add_f32, pipeline_add_f32_norepeat;
  182. vk_pipeline pipeline_add_f16_f32_f16, pipeline_add_f16_f32_f16_norepeat;
  183. vk_pipeline pipeline_mul_f32, pipeline_mul_f32_norepeat;
  184. vk_pipeline pipeline_div_f32, pipeline_div_f32_norepeat;
  185. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  186. vk_pipeline pipeline_upscale_f32;
  187. vk_pipeline pipeline_scale_f32;
  188. vk_pipeline pipeline_sqr_f32;
  189. vk_pipeline pipeline_sin_f32;
  190. vk_pipeline pipeline_cos_f32;
  191. vk_pipeline pipeline_clamp_f32;
  192. vk_pipeline pipeline_pad_f32;
  193. vk_pipeline pipeline_repeat_f32;
  194. vk_pipeline pipeline_cpy_f32_f32, pipeline_cpy_f32_f16, pipeline_cpy_f16_f16;
  195. vk_pipeline pipeline_contig_cpy_f32_f32, pipeline_contig_cpy_f32_f16, pipeline_contig_cpy_f16_f16;
  196. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  197. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  198. vk_pipeline pipeline_norm_f32;
  199. vk_pipeline pipeline_group_norm_f32;
  200. vk_pipeline pipeline_rms_norm_f32;
  201. vk_pipeline pipeline_gelu_f32;
  202. vk_pipeline pipeline_gelu_quick_f32;
  203. vk_pipeline pipeline_silu_f32;
  204. vk_pipeline pipeline_relu_f32;
  205. vk_pipeline pipeline_leaky_relu_f32;
  206. vk_pipeline pipeline_tanh_f32;
  207. vk_pipeline pipeline_diag_mask_inf_f32;
  208. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  209. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  210. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16;
  211. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16;
  212. vk_pipeline pipeline_argsort_f32;
  213. vk_pipeline pipeline_sum_rows_f32;
  214. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  215. vk_pipeline pipeline_timestep_embedding_f32;
  216. vk_pipeline pipeline_pool2d_f32;
  217. vk_pipeline pipeline_rwkv_wkv6_f32;
  218. // [2][2][2] is for {f16acc,f32acc}x{large,small_rows}x{unaligned, aligned}
  219. vk_pipeline pipeline_flash_attn_f32_f16_D64[GGML_TYPE_COUNT][2][2][2];
  220. vk_pipeline pipeline_flash_attn_f32_f16_D80[GGML_TYPE_COUNT][2][2][2];
  221. vk_pipeline pipeline_flash_attn_f32_f16_D96[GGML_TYPE_COUNT][2][2][2];
  222. vk_pipeline pipeline_flash_attn_f32_f16_D112[GGML_TYPE_COUNT][2][2][2];
  223. vk_pipeline pipeline_flash_attn_f32_f16_D128[GGML_TYPE_COUNT][2][2][2];
  224. vk_pipeline pipeline_flash_attn_f32_f16_D256[GGML_TYPE_COUNT][2][2][2];
  225. std::unordered_map<std::string, vk_pipeline_ref> pipelines;
  226. std::unordered_map<std::string, uint64_t> pipeline_descriptor_set_requirements;
  227. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  228. vk::Fence fence;
  229. vk_buffer sync_staging;
  230. ggml_backend_buffer_type buffer_type;
  231. #ifdef GGML_VULKAN_MEMORY_DEBUG
  232. std::unique_ptr<vk_memory_logger> memory_logger;
  233. #endif
  234. #ifdef GGML_VULKAN_PERF
  235. std::unique_ptr<vk_perf_logger> perf_logger;
  236. #endif
  237. ~vk_device_struct() {
  238. VK_LOG_DEBUG("destroy device " << name);
  239. device.destroyFence(fence);
  240. ggml_vk_destroy_buffer(sync_staging);
  241. device.destroyCommandPool(compute_queue.pool);
  242. if (!single_queue) {
  243. device.destroyCommandPool(transfer_queue.pool);
  244. }
  245. for (auto& pipeline : pipelines) {
  246. if (pipeline.second.expired()) {
  247. continue;
  248. }
  249. vk_pipeline pl = pipeline.second.lock();
  250. ggml_vk_destroy_pipeline(device, pl);
  251. }
  252. pipelines.clear();
  253. device.destroy();
  254. }
  255. };
  256. struct vk_buffer_struct {
  257. vk::Buffer buffer = VK_NULL_HANDLE;
  258. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  259. vk::MemoryPropertyFlags memory_property_flags;
  260. void * ptr;
  261. size_t size = 0;
  262. vk_device device;
  263. ~vk_buffer_struct() {
  264. if (size == 0) {
  265. return;
  266. }
  267. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  268. device->device.freeMemory(device_memory);
  269. device->device.destroyBuffer(buffer);
  270. }
  271. };
  272. struct vk_subbuffer {
  273. vk_buffer buffer;
  274. uint64_t offset;
  275. uint64_t size;
  276. operator vk::DescriptorBufferInfo() const {
  277. return { buffer->buffer, offset, size };
  278. }
  279. };
  280. struct vk_semaphore {
  281. vk::Semaphore s;
  282. uint64_t value;
  283. };
  284. struct vk_submission {
  285. vk::CommandBuffer buffer;
  286. std::vector<vk_semaphore> wait_semaphores;
  287. std::vector<vk_semaphore> signal_semaphores;
  288. };
  289. typedef std::vector<vk_submission> vk_sequence;
  290. struct vk_mat_mat_push_constants {
  291. uint32_t M; uint32_t N; uint32_t K;
  292. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  293. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  294. uint32_t k_split;
  295. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  296. };
  297. struct vk_mat_vec_push_constants {
  298. uint32_t ncols; uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  299. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  300. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  301. };
  302. struct vk_mat_mat_id_push_constants {
  303. uint32_t M; uint32_t N; uint32_t K;
  304. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  305. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  306. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  307. };
  308. struct vk_mat_vec_id_push_constants {
  309. uint32_t ncols; uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  310. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  311. uint32_t nei0; uint32_t ne11;
  312. };
  313. struct vk_flash_attn_push_constants {
  314. uint32_t N;
  315. uint32_t KV;
  316. uint32_t ne1;
  317. uint32_t ne2;
  318. uint32_t ne3;
  319. uint32_t neq2;
  320. uint32_t neq3;
  321. uint32_t nek2;
  322. uint32_t nek3;
  323. uint32_t nev2;
  324. uint32_t nev3;
  325. uint32_t nem1;
  326. uint32_t nb01;
  327. uint32_t nb02;
  328. uint32_t nb03;
  329. uint32_t nb11;
  330. uint32_t nb12;
  331. uint32_t nb13;
  332. uint32_t nb21;
  333. uint32_t nb22;
  334. uint32_t nb23;
  335. uint32_t nb31;
  336. float scale;
  337. float max_bias;
  338. float logit_softcap;
  339. uint32_t mask;
  340. uint32_t n_head_log2;
  341. float m0;
  342. float m1;
  343. };
  344. struct vk_op_push_constants {
  345. uint32_t KX;
  346. uint32_t KY;
  347. float param1;
  348. float param2;
  349. };
  350. struct vk_op_unary_push_constants {
  351. uint32_t ne;
  352. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  353. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  354. uint32_t misalign_offsets;
  355. float param1; float param2;
  356. uint32_t ne0_012mp; uint32_t ne0_012L;
  357. uint32_t ne0_01mp; uint32_t ne0_01L;
  358. uint32_t ne0_0mp; uint32_t ne0_0L;
  359. uint32_t ne1_012mp; uint32_t ne1_012L;
  360. uint32_t ne1_01mp; uint32_t ne1_01L;
  361. uint32_t ne1_0mp; uint32_t ne1_0L;
  362. };
  363. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  364. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  365. // Precompute mp (m' in the paper) and L such that division
  366. // can be computed using a multiply (high 32b of 64b result)
  367. // and a shift:
  368. //
  369. // n/d = (mulhi(n, mp) + n) >> L;
  370. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  371. {
  372. // compute L = ceil(log2(d));
  373. L = 0;
  374. while (L < 32 && (uint32_t{1} << L) < d) {
  375. L++;
  376. }
  377. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  378. }
  379. template <typename T> void init_pushconst_fastdiv(T &p) {
  380. GGML_UNUSED(p);
  381. static_assert(!std::is_const<T>::value, "unexpected type");
  382. }
  383. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  384. // Compute magic values to divide by these six numbers.
  385. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  386. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  387. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  388. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  389. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  390. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  391. }
  392. struct vk_op_binary_push_constants {
  393. uint32_t ne;
  394. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  395. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  396. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  397. uint32_t misalign_offsets;
  398. float param1; float param2; int32_t param3;
  399. };
  400. struct vk_op_diag_mask_push_constants {
  401. uint32_t ncols;
  402. uint32_t rows_per_channel;
  403. int32_t n_past;
  404. };
  405. struct vk_op_rope_push_constants {
  406. uint32_t ncols;
  407. uint32_t n_dims;
  408. float freq_scale;
  409. uint32_t p_delta_rows;
  410. float freq_base;
  411. float ext_factor;
  412. float attn_factor;
  413. float corr_dims[2];
  414. float theta_scale;
  415. uint32_t has_ff;
  416. };
  417. struct vk_op_soft_max_push_constants {
  418. uint32_t KX;
  419. uint32_t KY;
  420. float scale;
  421. float max_bias;
  422. float m0;
  423. float m1;
  424. uint32_t n_head_log2;
  425. uint32_t nrows_x;
  426. };
  427. struct vk_op_argsort_push_constants {
  428. uint32_t ncols;
  429. uint32_t ncols_pad;
  430. int32_t order;
  431. };
  432. struct vk_op_im2col_push_constants {
  433. uint32_t batch_offset; uint32_t offset_delta;
  434. uint32_t IC;
  435. uint32_t IW; uint32_t IH;
  436. uint32_t OW; uint32_t OH;
  437. uint32_t KW; uint32_t KH;
  438. uint32_t pelements;
  439. uint32_t CHW;
  440. int32_t s0; int32_t s1;
  441. int32_t p0; int32_t p1;
  442. int32_t d0; int32_t d1;
  443. };
  444. struct vk_op_timestep_embedding_push_constants {
  445. uint32_t nb1;
  446. uint32_t dim;
  447. uint32_t max_period;
  448. };
  449. struct vk_op_pool2d_push_constants {
  450. uint32_t IW; uint32_t IH;
  451. uint32_t OW; uint32_t OH;
  452. uint32_t OC;
  453. uint32_t pelements;
  454. uint32_t op;
  455. int32_t k0; int32_t k1;
  456. int32_t s0; int32_t s1;
  457. int32_t p0; int32_t p1;
  458. };
  459. struct vk_op_rwkv_wkv6_push_constants {
  460. uint32_t B;
  461. uint32_t T;
  462. uint32_t C;
  463. uint32_t H;
  464. };
  465. // Allow pre-recording command buffers
  466. struct vk_staging_memcpy {
  467. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  468. void * dst;
  469. const void * src;
  470. size_t n;
  471. };
  472. struct vk_op_upscale_push_constants {
  473. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  474. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  475. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  476. float sf0; float sf1; float sf2; float sf3;
  477. };
  478. struct vk_context_struct {
  479. vk_submission * s;
  480. std::vector<vk_sequence> seqs;
  481. int exit_tensor_idx;
  482. std::vector<vk_staging_memcpy> in_memcpys;
  483. std::vector<vk_staging_memcpy> out_memcpys;
  484. vk_queue * q;
  485. };
  486. typedef std::shared_ptr<vk_context_struct> vk_context;
  487. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  488. struct ggml_vk_garbage_collector {
  489. std::vector<vk_semaphore> tl_semaphores;
  490. std::vector<vk_semaphore> semaphores;
  491. std::vector<vk::Event> events;
  492. std::vector<vk_buffer> temp_buffers;
  493. std::vector<vk_context> contexts;
  494. };
  495. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  496. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  497. static std::string format_size(size_t size) {
  498. const size_t kib = 1024;
  499. const size_t mib = kib * 1024;
  500. const size_t gib = mib * 1024;
  501. std::ostringstream oss;
  502. oss << std::fixed << std::setprecision(2);
  503. if (size >= gib) {
  504. oss << static_cast<double>(size) / gib << " GiB";
  505. } else if (size >= mib) {
  506. oss << static_cast<double>(size) / mib << " MiB";
  507. } else if (size >= kib) {
  508. oss << static_cast<double>(size) / kib << " KiB";
  509. } else {
  510. oss << size << " B";
  511. }
  512. return oss.str();
  513. }
  514. static std::mutex log_mutex;
  515. class vk_memory_logger {
  516. public:
  517. vk_memory_logger(): total_device(0), total_host(0) {}
  518. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  519. void log_deallocation(vk_buffer_ref buf_ref);
  520. private:
  521. std::map<vk::Buffer, size_t> allocations; // Track allocations
  522. size_t total_device;
  523. size_t total_host;
  524. };
  525. #else
  526. #define VK_LOG_MEMORY(msg) ((void) 0)
  527. #endif // GGML_VULKAN_MEMORY_DEBUG
  528. #if defined(GGML_VULKAN_PERF)
  529. class vk_perf_logger {
  530. public:
  531. void print_timings() {
  532. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  533. for (const auto& t : timings) {
  534. uint64_t total = 0;
  535. for (const auto& time : t.second) {
  536. total += time;
  537. }
  538. std::cerr << t.first << ": " << t.second.size() << " x " << (total / t.second.size() / 1000.0) << " ms" << std::endl;
  539. }
  540. timings.clear();
  541. }
  542. void log_timing(const ggml_tensor * node, uint64_t time) {
  543. if (node->op == GGML_OP_UNARY) {
  544. timings[ggml_unary_op_name(ggml_get_unary_op(node))].push_back(time);
  545. return;
  546. }
  547. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  548. const uint64_t m = node->src[0]->ne[1];
  549. const uint64_t n = node->src[1]->ne[1];
  550. const uint64_t k = node->src[1]->ne[0];
  551. std::string name = ggml_op_name(node->op);
  552. if (n == 1) {
  553. name += "_VEC m=" + std::to_string(m) + " k=" + std::to_string(k);
  554. } else {
  555. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  556. }
  557. timings[name].push_back(time);
  558. return;
  559. }
  560. timings[ggml_op_name(node->op)].push_back(time);
  561. }
  562. private:
  563. std::map<std::string, std::vector<uint64_t>> timings;
  564. };
  565. #endif // GGML_VULKAN_PERF
  566. struct ggml_backend_vk_context {
  567. std::string name;
  568. vk_device device;
  569. size_t semaphore_idx, event_idx;
  570. ggml_vk_garbage_collector gc;
  571. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k;
  572. vk_buffer prealloc_x, prealloc_y, prealloc_split_k;
  573. vk::Fence fence;
  574. vk_buffer buffer_pool[MAX_VK_BUFFERS];
  575. vk_context_ref compute_ctx;
  576. vk_context_ref transfer_ctx;
  577. std::vector<vk_context_ref> tensor_ctxs;
  578. };
  579. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  580. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  581. if (tensor->view_src) {
  582. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  583. }
  584. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  585. }
  586. struct ggml_backend_vk_buffer_context {
  587. vk_device_ref device;
  588. vk_buffer dev_buffer;
  589. std::string name;
  590. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  591. device(device),
  592. dev_buffer(dev_buffer),
  593. name(name) {
  594. }
  595. ~ggml_backend_vk_buffer_context() {
  596. ggml_vk_destroy_buffer(dev_buffer);
  597. }
  598. };
  599. #ifdef GGML_VULKAN_MEMORY_DEBUG
  600. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  601. std::lock_guard<std::mutex> guard(log_mutex);
  602. vk_buffer buf = buf_ref.lock();
  603. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  604. const std::string type = device ? "device" : "host";
  605. allocations[buf->buffer] = size;
  606. total_device += device ? size : 0;
  607. total_host += device ? 0 : size;
  608. 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));
  609. }
  610. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  611. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  612. return;
  613. }
  614. std::lock_guard<std::mutex> guard(log_mutex);
  615. vk_buffer buf = buf_ref.lock();
  616. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  617. std::string type = device ? "device" : "host";
  618. auto it = allocations.find(buf->buffer);
  619. total_device -= device ? it->second : 0;
  620. total_host -= device ? 0 : it->second;
  621. if (it != allocations.end()) {
  622. 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));
  623. allocations.erase(it);
  624. } else {
  625. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  626. }
  627. }
  628. #endif // GGML_VULKAN_MEMORY_DEBUG
  629. struct vk_instance_t {
  630. vk::Instance instance;
  631. std::vector<size_t> device_indices;
  632. vk_device devices[GGML_VK_MAX_DEVICES];
  633. };
  634. static bool vk_instance_initialized = false;
  635. static vk_instance_t vk_instance;
  636. #ifdef GGML_VULKAN_CHECK_RESULTS
  637. static size_t vk_skip_checks;
  638. static size_t vk_output_tensor;
  639. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  640. static void ggml_vk_check_results_0(ggml_tensor * tensor);
  641. static void ggml_vk_check_results_1(ggml_tensor * tensor);
  642. #endif
  643. 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);
  644. static void ggml_backend_vk_free(ggml_backend_t backend);
  645. // variables to track number of compiles in progress
  646. static uint32_t compile_count = 0;
  647. static std::mutex compile_count_mutex;
  648. static std::condition_variable compile_count_cond;
  649. 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,
  650. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  651. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  652. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  653. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  654. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  655. GGML_ASSERT(parameter_count > 0);
  656. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  657. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  658. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  659. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  660. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  661. for (uint32_t i = 0; i < parameter_count; i++) {
  662. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  663. dsl_binding_flags.push_back({});
  664. }
  665. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  666. vk::PushConstantRange pcr(
  667. vk::ShaderStageFlagBits::eCompute,
  668. 0,
  669. pipeline->push_constant_size
  670. );
  671. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  672. {},
  673. dsl_binding);
  674. descriptor_set_layout_create_info.setPNext(&dslbfci);
  675. pipeline->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  676. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, pipeline->parameter_count * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  677. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  678. pipeline->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  679. pipeline->descriptor_set_idx = 0;
  680. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), pipeline->dsl, pcr);
  681. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  682. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  683. for (size_t i = 0; i < specialization_constants.size(); i++) {
  684. specialization_entries[i].constantID = i;
  685. specialization_entries[i].offset = i * sizeof(uint32_t);
  686. specialization_entries[i].size = sizeof(uint32_t);
  687. }
  688. vk::SpecializationInfo specialization_info(
  689. specialization_entries.size(),
  690. specialization_entries.data(),
  691. specialization_constants.size() * sizeof(uint32_t),
  692. specialization_constants.data()
  693. );
  694. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  695. if (device->subgroup_require_full_support && require_full_subgroups) {
  696. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  697. }
  698. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  699. pipeline_shader_stage_create_flags,
  700. vk::ShaderStageFlagBits::eCompute,
  701. pipeline->shader_module,
  702. entrypoint.c_str(),
  703. &specialization_info);
  704. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  705. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  706. if (device->subgroup_size_control && required_subgroup_size > 0) {
  707. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  708. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  709. }
  710. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  711. vk::PipelineCreateFlags{},
  712. pipeline_shader_create_info,
  713. pipeline->layout);
  714. vk::PipelineRobustnessCreateInfoEXT rci;
  715. if (device->pipeline_robustness && disable_robustness) {
  716. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  717. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  718. compute_pipeline_create_info.setPNext(&rci);
  719. }
  720. try {
  721. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  722. } catch (const vk::SystemError& e) {
  723. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  724. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  725. throw e;
  726. }
  727. pipeline->compiled = true;
  728. {
  729. std::lock_guard<std::mutex> guard(device->mutex);
  730. device->pipelines.insert({ pipeline->name, pipeline });
  731. }
  732. {
  733. std::lock_guard<std::mutex> guard(compile_count_mutex);
  734. assert(compile_count > 0);
  735. compile_count--;
  736. }
  737. compile_count_cond.notify_all();
  738. }
  739. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  740. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  741. for (auto& pool : pipeline->descriptor_pools) {
  742. device.destroyDescriptorPool(pool);
  743. }
  744. pipeline->descriptor_pools.clear();
  745. pipeline->descriptor_sets.clear();
  746. pipeline->descriptor_set_idx = 0;
  747. device.destroyDescriptorSetLayout(pipeline->dsl);
  748. device.destroyPipelineLayout(pipeline->layout);
  749. device.destroyShaderModule(pipeline->shader_module);
  750. device.destroyPipeline(pipeline->pipeline);
  751. }
  752. static void ggml_pipeline_request_descriptor_sets(vk_device& device, vk_pipeline& pipeline, uint32_t n) {
  753. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  754. device->pipeline_descriptor_set_requirements[pipeline->name] += n;
  755. if (!pipeline->compiled) {
  756. pipeline->needed = true;
  757. device->need_compiles = true;
  758. }
  759. }
  760. static void ggml_pipeline_allocate_descriptor_sets(vk_device& device) {
  761. std::lock_guard<std::mutex> guard(device->mutex);
  762. for (auto& pair : device->pipeline_descriptor_set_requirements) {
  763. vk_pipeline pipeline = device->pipelines.at(pair.first).lock();
  764. const uint64_t n = pair.second;
  765. VK_LOG_DEBUG("ggml_pipeline_allocate_descriptor_sets(" << pipeline->name << ", " << n << ")");
  766. if (pipeline->descriptor_sets.size() >= pipeline->descriptor_set_idx + n) {
  767. // Enough descriptors are available
  768. continue;
  769. }
  770. uint32_t to_alloc = pipeline->descriptor_set_idx + n - pipeline->descriptor_sets.size();
  771. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - pipeline->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  772. uint32_t pool_idx = pipeline->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  773. while (to_alloc > 0) {
  774. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  775. to_alloc -= alloc_count;
  776. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  777. if (pool_idx >= pipeline->descriptor_pools.size()) {
  778. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, pipeline->parameter_count * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  779. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  780. pipeline->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  781. }
  782. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  783. for (uint32_t i = 0; i < alloc_count; i++) {
  784. layouts[i] = pipeline->dsl;
  785. }
  786. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(pipeline->descriptor_pools[pool_idx], alloc_count, layouts.data());
  787. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  788. pipeline->descriptor_sets.insert(pipeline->descriptor_sets.end(), sets.begin(), sets.end());
  789. pool_idx++;
  790. }
  791. }
  792. }
  793. static void ggml_pipeline_cleanup(vk_pipeline& pipeline) {
  794. VK_LOG_DEBUG("ggml_pipeline_cleanup(" << pipeline->name << ")");
  795. pipeline->descriptor_set_idx = 0;
  796. }
  797. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_queue& q) {
  798. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  799. std::lock_guard<std::mutex> guard(device->mutex);
  800. if (q.cmd_buffers.size() > q.cmd_buffer_idx) {
  801. // Reuse command buffer
  802. return q.cmd_buffers[q.cmd_buffer_idx++];
  803. }
  804. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  805. q.pool,
  806. vk::CommandBufferLevel::ePrimary,
  807. 1);
  808. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  809. auto buf = cmd_buffers.front();
  810. q.cmd_buffers.push_back(buf);
  811. q.cmd_buffer_idx++;
  812. return buf;
  813. }
  814. static vk_submission ggml_vk_create_submission(vk_device& device, vk_queue& q, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  815. VK_LOG_DEBUG("ggml_vk_create_submission()");
  816. vk_submission s;
  817. s.buffer = ggml_vk_create_cmd_buffer(device, q);
  818. s.wait_semaphores = std::move(wait_semaphores);
  819. s.signal_semaphores = std::move(signal_semaphores);
  820. return s;
  821. }
  822. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  823. if (ctx->seqs.empty()) {
  824. if (fence) {
  825. ctx->q->queue.submit({}, fence);
  826. }
  827. return;
  828. }
  829. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  830. std::vector<std::vector<uint64_t>> tl_wait_vals;
  831. std::vector<std::vector<uint64_t>> tl_signal_vals;
  832. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  833. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  834. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  835. std::vector<vk::SubmitInfo> submit_infos;
  836. int idx = -1;
  837. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  838. size_t reserve = 0;
  839. for (const auto& sequence : ctx->seqs) {
  840. reserve += sequence.size();
  841. }
  842. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  843. tl_wait_semaphores.reserve(reserve);
  844. tl_wait_vals.reserve(reserve);
  845. tl_signal_semaphores.reserve(reserve);
  846. tl_signal_vals.reserve(reserve);
  847. tl_submit_infos.reserve(reserve);
  848. submit_infos.reserve(reserve);
  849. stage_flags.reserve(reserve);
  850. for (const auto& sequence : ctx->seqs) {
  851. for (const auto& submission : sequence) {
  852. stage_flags.push_back({});
  853. idx++;
  854. tl_wait_vals.push_back({});
  855. tl_wait_semaphores.push_back({});
  856. tl_signal_vals.push_back({});
  857. tl_signal_semaphores.push_back({});
  858. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  859. stage_flags[idx].push_back(ctx->q->stage_flags);
  860. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  861. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  862. }
  863. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  864. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  865. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  866. }
  867. tl_submit_infos.push_back({
  868. (uint32_t) submission.wait_semaphores.size(),
  869. tl_wait_vals[idx].data(),
  870. (uint32_t) submission.signal_semaphores.size(),
  871. tl_signal_vals[idx].data(),
  872. });
  873. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  874. tl_submit_infos[idx].pNext = nullptr;
  875. vk::SubmitInfo si{
  876. (uint32_t) submission.wait_semaphores.size(),
  877. tl_wait_semaphores[idx].data(),
  878. stage_flags[idx].data(),
  879. 1,
  880. &submission.buffer,
  881. (uint32_t) submission.signal_semaphores.size(),
  882. tl_signal_semaphores[idx].data(),
  883. };
  884. si.setPNext(&tl_submit_infos[idx]);
  885. submit_infos.push_back(si);
  886. }
  887. }
  888. ctx->q->queue.submit(submit_infos, fence);
  889. ctx->seqs.clear();
  890. }
  891. 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) {
  892. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  893. const uint32_t qfsize = queue_family_props.size();
  894. // Try with avoid preferences first
  895. for (uint32_t i = 0; i < qfsize; i++) {
  896. 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)) {
  897. return i;
  898. }
  899. }
  900. // Fall back to only required
  901. for (size_t i = 0; i < qfsize; i++) {
  902. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  903. return i;
  904. }
  905. }
  906. // Fall back to reusing compute queue
  907. for (size_t i = 0; i < qfsize; i++) {
  908. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  909. return i;
  910. }
  911. }
  912. // Fall back to ignoring min_num_queries
  913. for (size_t i = 0; i < qfsize; i++) {
  914. if (queue_family_props[i].queueFlags & required) {
  915. return i;
  916. }
  917. }
  918. // 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.
  919. // 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.
  920. if (compute_index >= 0) {
  921. return compute_index;
  922. }
  923. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  924. for(auto &q_family : queue_family_props) {
  925. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  926. }
  927. abort();
  928. }
  929. 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) {
  930. VK_LOG_DEBUG("ggml_vk_create_queue()");
  931. std::lock_guard<std::mutex> guard(device->mutex);
  932. q.queue_family_index = queue_family_index;
  933. q.transfer_only = transfer_only;
  934. vk::CommandPoolCreateInfo command_pool_create_info_compute(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), queue_family_index);
  935. q.pool = device->device.createCommandPool(command_pool_create_info_compute);
  936. q.cmd_buffer_idx = 0;
  937. q.queue = device->device.getQueue(queue_family_index, queue_index);
  938. q.stage_flags = stage_flags;
  939. }
  940. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_queue& q) {
  941. vk_context result = std::make_shared<vk_context_struct>();
  942. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  943. ctx->gc.contexts.emplace_back(result);
  944. result->q = &q;
  945. return result;
  946. }
  947. static vk_context ggml_vk_create_temporary_context(vk_queue& q) {
  948. vk_context result = std::make_shared<vk_context_struct>();
  949. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  950. result->q = &q;
  951. return result;
  952. }
  953. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  954. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  955. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  956. vk::SemaphoreCreateInfo ci{};
  957. ci.setPNext(&tci);
  958. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  959. ctx->gc.semaphores.push_back({ semaphore, 0 });
  960. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  961. }
  962. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  963. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  964. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  965. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  966. vk::SemaphoreCreateInfo ci{};
  967. ci.setPNext(&tci);
  968. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  969. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  970. }
  971. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  972. }
  973. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  974. if (ctx->event_idx >= ctx->gc.events.size()) {
  975. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  976. }
  977. return ctx->gc.events[ctx->event_idx++];
  978. }
  979. static void ggml_vk_queue_cleanup(vk_device& device, vk_queue& q) {
  980. VK_LOG_DEBUG("ggml_vk_queue_cleanup()");
  981. std::lock_guard<std::mutex> guard(device->mutex);
  982. // Requires command buffers to be done
  983. device->device.resetCommandPool(q.pool);
  984. q.cmd_buffer_idx = 0;
  985. }
  986. static uint32_t find_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  987. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  988. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  989. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  990. (flags & memory_type.propertyFlags) == flags &&
  991. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  992. return static_cast<int32_t>(i);
  993. }
  994. }
  995. return UINT32_MAX;
  996. }
  997. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, vk::MemoryPropertyFlags req_flags, vk::MemoryPropertyFlags fallback_flags = vk::MemoryPropertyFlags(0)) {
  998. VK_LOG_DEBUG("ggml_vk_create_buffer(" << device->name << ", " << size << ", " << to_string(req_flags) << ", " << to_string(fallback_flags) << ")");
  999. if (size > device->max_memory_allocation_size) {
  1000. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device memory allocation limit");
  1001. }
  1002. std::lock_guard<std::mutex> guard(device->mutex);
  1003. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  1004. if (size == 0) {
  1005. buf->size = 0;
  1006. return buf;
  1007. }
  1008. vk::BufferCreateInfo buffer_create_info{
  1009. vk::BufferCreateFlags(),
  1010. size,
  1011. vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst,
  1012. vk::SharingMode::eExclusive,
  1013. 0,
  1014. nullptr,
  1015. };
  1016. buf->buffer = device->device.createBuffer(buffer_create_info);
  1017. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  1018. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  1019. uint32_t memory_type_index = UINT32_MAX;
  1020. memory_type_index = find_properties(&mem_props, &mem_req, req_flags);
  1021. buf->memory_property_flags = req_flags;
  1022. if (memory_type_index == UINT32_MAX && fallback_flags) {
  1023. memory_type_index = find_properties(&mem_props, &mem_req, fallback_flags);
  1024. buf->memory_property_flags = fallback_flags;
  1025. }
  1026. if (memory_type_index == UINT32_MAX) {
  1027. device->device.destroyBuffer(buf->buffer);
  1028. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  1029. }
  1030. try {
  1031. buf->device_memory = device->device.allocateMemory({ mem_req.size, memory_type_index });
  1032. } catch (const vk::SystemError& e) {
  1033. if (buf->memory_property_flags != fallback_flags) {
  1034. // Try again with fallback flags
  1035. memory_type_index = find_properties(&mem_props, &mem_req, fallback_flags);
  1036. buf->memory_property_flags = fallback_flags;
  1037. try {
  1038. buf->device_memory = device->device.allocateMemory({ mem_req.size, memory_type_index });
  1039. }
  1040. catch (const vk::SystemError& e) {
  1041. device->device.destroyBuffer(buf->buffer);
  1042. throw e;
  1043. }
  1044. } else {
  1045. // Out of Host/Device memory, clean up buffer
  1046. device->device.destroyBuffer(buf->buffer);
  1047. throw e;
  1048. }
  1049. }
  1050. buf->ptr = nullptr;
  1051. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1052. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  1053. }
  1054. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  1055. buf->device = device;
  1056. buf->size = size;
  1057. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1058. device->memory_logger->log_allocation(buf, size);
  1059. #endif
  1060. return buf;
  1061. }
  1062. 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)) {
  1063. try {
  1064. return ggml_vk_create_buffer(device, size, req_flags, fallback_flags);
  1065. } catch (const vk::SystemError& e) {
  1066. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  1067. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1068. throw e;
  1069. }
  1070. }
  1071. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  1072. vk_buffer buf;
  1073. try {
  1074. if (device->uma) {
  1075. // Fall back to host memory type
  1076. buf = ggml_vk_create_buffer(device, size, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  1077. } else {
  1078. // use rebar if available, otherwise fallback to device only visible memory
  1079. buf = ggml_vk_create_buffer(device, size, vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, vk::MemoryPropertyFlagBits::eDeviceLocal);
  1080. }
  1081. } catch (const vk::SystemError& e) {
  1082. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  1083. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1084. throw e;
  1085. }
  1086. return buf;
  1087. }
  1088. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  1089. if (buf == nullptr) {
  1090. return;
  1091. }
  1092. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1093. if (buf->device != nullptr) {
  1094. buf->device->memory_logger->log_deallocation(buf);
  1095. }
  1096. #endif
  1097. buf.reset();
  1098. }
  1099. static vk_subbuffer ggml_vk_subbuffer(vk_buffer& buf) {
  1100. return { buf, 0, VK_WHOLE_SIZE };
  1101. }
  1102. static void ggml_vk_sync_buffers(vk_context& ctx) {
  1103. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  1104. const bool transfer_queue = ctx->q->transfer_only;
  1105. ctx->s->buffer.pipelineBarrier(
  1106. ctx->q->stage_flags,
  1107. ctx->q->stage_flags,
  1108. {},
  1109. { {
  1110. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  1111. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  1112. } },
  1113. {},
  1114. {}
  1115. );
  1116. }
  1117. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  1118. VK_LOG_DEBUG("ggml_vk_wait_events()");
  1119. if (events.empty()) {
  1120. return;
  1121. }
  1122. ctx->s->buffer.waitEvents(
  1123. events,
  1124. ctx->q->stage_flags,
  1125. ctx->q->stage_flags,
  1126. {},
  1127. {},
  1128. {}
  1129. );
  1130. }
  1131. // number of rows/cols for flash attention shader
  1132. static constexpr uint32_t flash_attention_num_small_rows = 32;
  1133. static std::array<uint32_t, 2> fa_rows_cols(uint32_t D, uint32_t clamp, ggml_type type, bool small_rows) {
  1134. GGML_UNUSED(clamp);
  1135. // small rows, large cols
  1136. if (small_rows) {
  1137. return {flash_attention_num_small_rows, 128};
  1138. }
  1139. // small cols to reduce register count
  1140. if (ggml_is_quantized(type) || D == 256) {
  1141. return {64, 32};
  1142. }
  1143. return {64, 64};
  1144. };
  1145. static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector<uint32_t>& warptile, bool mul_mat_id) {
  1146. // Needs to be kept up to date on shader changes
  1147. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  1148. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  1149. const uint32_t warps = warptile[0] / warptile[10];
  1150. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  1151. const uint32_t mmid_row_ids = mul_mat_id ? 3072 * sizeof(uint32_t) : 0;
  1152. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  1153. return (load_bufs + mmid_row_ids + coopmat_stage) <= device->properties.limits.maxComputeSharedMemorySize;
  1154. }
  1155. static void ggml_vk_load_shaders(vk_device& device) {
  1156. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  1157. // some shaders have a minimum subgroup size
  1158. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  1159. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  1160. // mulmat
  1161. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  1162. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  1163. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  1164. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid;
  1165. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  1166. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  1167. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  1168. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  1169. uint32_t l_align, m_align, s_align;
  1170. if (device->coopmat2) {
  1171. // spec constants and tile sizes for non-quant matmul/matmul_id
  1172. l_warptile = { 256, 128, 256, 64 };
  1173. m_warptile = { 256, 128, 128, 64 };
  1174. s_warptile = { 128, 64, 64, 64 };
  1175. l_wg_denoms = {128, 256, 1 };
  1176. m_wg_denoms = {128, 128, 1 };
  1177. s_wg_denoms = { 64, 64, 1 };
  1178. // spec constants and tile sizes for quant matmul (non-Qi_K)
  1179. l_warptile_mmq = { 256, 128, 256, 64 };
  1180. m_warptile_mmq = { 256, 128, 128, 64 };
  1181. s_warptile_mmq = { 256, 128, 128, 64 };
  1182. l_mmq_wg_denoms = { 128, 256, 1 };
  1183. m_mmq_wg_denoms = { 128, 128, 1 };
  1184. s_mmq_wg_denoms = { 128, 128, 1 };
  1185. // spec constants and tile sizes for quant matmul (Qi_K)
  1186. l_warptile_mmq_k = { 256, 128, 512, 16 };
  1187. m_warptile_mmq_k = { 256, 128, 256, 16 };
  1188. s_warptile_mmq_k = { 256, 32, 128, 64 };
  1189. l_mmq_wg_denoms_k = { 128, 512, 1 };
  1190. m_mmq_wg_denoms_k = { 128, 256, 1 };
  1191. s_mmq_wg_denoms_k = { 32, 128, 1 };
  1192. // spec constants and tile sizes for quant matmul_id
  1193. l_warptile_mmqid = { 256, 128, 128, 16 };
  1194. m_warptile_mmqid = { 256, 128, 64, 16 };
  1195. s_warptile_mmqid = { 256, 64, 64, 16 };
  1196. l_mmqid_wg_denoms = { 128, 128, 1 };
  1197. m_mmqid_wg_denoms = { 128, 64, 1 };
  1198. s_mmqid_wg_denoms = { 64, 64, 1 };
  1199. l_align = 128;
  1200. m_align = 64;
  1201. s_align = 32;
  1202. } else {
  1203. // Matrix cores require different warp group sizes
  1204. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  1205. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  1206. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  1207. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  1208. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  1209. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  1210. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  1211. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  1212. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  1213. l_warptile = { 128, 128, 128, 16, device->subgroup_size * 2, 64, 2, tm_l, tn_l, tk_l, device->subgroup_size };
  1214. m_warptile = { 128, 64, 64, 16, device->subgroup_size, 32, 2, tm_m, tn_m, tk_m, device->subgroup_size };
  1215. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, device->subgroup_size };
  1216. l_warptile_mmq = { 128, 128, 128, 32, device->subgroup_size * 2, 64, 2, tm_l, tn_l, tk_l, device->subgroup_size };
  1217. m_warptile_mmq = { 128, 64, 64, 32, device->subgroup_size, 32, 2, tm_m, tn_m, tk_m, device->subgroup_size };
  1218. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, device->subgroup_size };
  1219. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  1220. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  1221. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  1222. l_align = 128;
  1223. m_align = 64;
  1224. s_align = 32;
  1225. // Fallback to smaller sizes if there's not enough shared memory. Given the current shaders
  1226. // and tile sizes, this should handle 16KB, 32KB, and 48KB+.
  1227. // This logic doesn't explicitly account for the 12KB row_ids in the mul_mat_mat_id shaders.
  1228. // But the numbers happen to work out for 32KB shared memory size that when using the medium
  1229. // size there's enough room for everything, and we assert for this.
  1230. uint32_t shmem_needed = (l_warptile[1] + l_warptile[2]) * (l_warptile[3] + 1) * sizeof(float);
  1231. if (shmem_needed > device->properties.limits.maxComputeSharedMemorySize) {
  1232. l_warptile = m_warptile;
  1233. l_wg_denoms = m_wg_denoms;
  1234. shmem_needed = (l_warptile[1] + l_warptile[2]) * (l_warptile[3] + 1) * sizeof(float);
  1235. GGML_ASSERT(shmem_needed <= device->properties.limits.maxComputeSharedMemorySize);
  1236. }
  1237. if (device->properties.limits.maxComputeSharedMemorySize >= 32768) {
  1238. // assert mul_mat_mat_id shaders will fit.
  1239. GGML_ASSERT(shmem_needed + 3072*4 <= device->properties.limits.maxComputeSharedMemorySize);
  1240. }
  1241. shmem_needed = (l_warptile_mmq[1] + l_warptile_mmq[2]) * (l_warptile_mmq[3] + 1) * sizeof(float);
  1242. if (shmem_needed > device->properties.limits.maxComputeSharedMemorySize) {
  1243. if (device->properties.limits.maxComputeSharedMemorySize == 32768) {
  1244. l_warptile_mmq = m_warptile_mmq;
  1245. l_mmq_wg_denoms = m_mmq_wg_denoms;
  1246. } else {
  1247. l_warptile_mmq = s_warptile_mmq;
  1248. l_mmq_wg_denoms = s_mmq_wg_denoms;
  1249. }
  1250. shmem_needed = (l_warptile_mmq[1] + l_warptile_mmq[2]) * (l_warptile_mmq[3] + 1) * sizeof(float);
  1251. GGML_ASSERT(shmem_needed <= device->properties.limits.maxComputeSharedMemorySize);
  1252. }
  1253. if (device->properties.limits.maxComputeSharedMemorySize >= 32768) {
  1254. // assert mul_mat_mat_id shaders will fit.
  1255. GGML_ASSERT(shmem_needed + 3072*4 <= device->properties.limits.maxComputeSharedMemorySize);
  1256. }
  1257. // Disable medium and large matrix multiplication if not enough shared memory is available
  1258. // Check mmq warptiles as the largest configuration
  1259. // Throw an error if not enough for any matrix multiplication is available
  1260. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false)) {
  1261. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  1262. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  1263. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false)) {
  1264. device->mul_mat_m = false;
  1265. device->mul_mat_l = false;
  1266. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false)) {
  1267. device->mul_mat_l = false;
  1268. }
  1269. // Disable mul_mat_id if not enough shared memory is available
  1270. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, true)) {
  1271. device->mul_mat_id_s = false;
  1272. device->mul_mat_id_m = false;
  1273. device->mul_mat_id_l = false;
  1274. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, true)) {
  1275. device->mul_mat_id_m = false;
  1276. device->mul_mat_id_l = false;
  1277. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, true)) {
  1278. device->mul_mat_id_l = false;
  1279. }
  1280. }
  1281. if (!device->pipeline_matmul_f32) {
  1282. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  1283. }
  1284. if (!device->pipeline_matmul_f32_f16) {
  1285. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  1286. }
  1287. if (!device->pipeline_matmul_id_f32) {
  1288. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  1289. }
  1290. std::vector<std::future<void>> compiles;
  1291. auto const &ggml_vk_create_pipeline = [&](vk_device& device, vk_pipeline& pipeline, const std::string &name, size_t spv_size, const void* spv_data, const std::string &entrypoint,
  1292. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  1293. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  1294. if (!pipeline) {
  1295. pipeline = std::make_shared<vk_pipeline_struct>();
  1296. pipeline->name = name;
  1297. pipeline->parameter_count = parameter_count;
  1298. pipeline->push_constant_size = push_constant_size;
  1299. pipeline->wg_denoms = wg_denoms;
  1300. pipeline->align = align;
  1301. }
  1302. if (!pipeline->needed || pipeline->compiled) {
  1303. return;
  1304. }
  1305. {
  1306. // wait until fewer than N compiles are in progress
  1307. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  1308. std::unique_lock<std::mutex> guard(compile_count_mutex);
  1309. while (compile_count >= N) {
  1310. compile_count_cond.wait(guard);
  1311. }
  1312. compile_count++;
  1313. }
  1314. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  1315. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  1316. };
  1317. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  1318. if (device->coopmat2) {
  1319. auto const &fa_wg_denoms = [&](uint32_t D, uint32_t clamp, ggml_type type, bool small_rows) -> std::array<uint32_t, 3> {
  1320. return {fa_rows_cols(D, clamp, type, small_rows)[0], 1, 1};
  1321. };
  1322. auto const &fa_spec_constants = [&](uint32_t D, uint32_t clamp, ggml_type type, bool small_rows) -> std::vector<uint32_t> {
  1323. // For large number of rows, 128 invocations seems to work best.
  1324. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  1325. // can't use 256 for D==80.
  1326. uint32_t wg_size = (small_rows && (D % 32) == 0) ? 256 : 128;
  1327. auto rows_cols = fa_rows_cols(D, clamp, type, small_rows);
  1328. return {wg_size, rows_cols[0], rows_cols[1], (D), clamp};
  1329. };
  1330. #define CREATE_FA2(TYPE, NAMELC, D) \
  1331. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][0][0], "flash_attn_f32_f16_D" #D "_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,false), fa_spec_constants(D,1,TYPE,false), 1); \
  1332. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][0][1], "flash_attn_f32_f16_D" #D "_aligned_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,false), fa_spec_constants(D,0,TYPE,false), fa_rows_cols(D,0,TYPE,false)[1]); \
  1333. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][0][0], "flash_attn_f32_f16_D" #D "_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,false), fa_spec_constants(D,1,TYPE,false), 1); \
  1334. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][0][1], "flash_attn_f32_f16_D" #D "_aligned_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,false), fa_spec_constants(D,0,TYPE,false), fa_rows_cols(D,0,TYPE,false)[1]); \
  1335. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][1][0], "flash_attn_f32_f16_D" #D "_f16acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,true), fa_spec_constants(D,1,TYPE,true), 1); \
  1336. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][0][1][1], "flash_attn_f32_f16_D" #D "_aligned_f16acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_len, flash_attn_f32_f16_ ## NAMELC ## _f16acc_cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,true), fa_spec_constants(D,0,TYPE,true), fa_rows_cols(D,0,TYPE,true)[1]); \
  1337. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][1][0], "flash_attn_f32_f16_D" #D "_f32acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,1,TYPE,true), fa_spec_constants(D,1,TYPE,true), 1); \
  1338. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16_D ## D[TYPE][1][1][1], "flash_attn_f32_f16_D" #D "_aligned_f32acc_smallrows" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _cm2_len, flash_attn_f32_f16_ ## NAMELC ## _cm2_data, "main", 5, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(D,0,TYPE,true), fa_spec_constants(D,0,TYPE,true), fa_rows_cols(D,0,TYPE,true)[1]); \
  1339. #define CREATE_FA(TYPE, NAMELC) \
  1340. CREATE_FA2(TYPE, NAMELC, 64) \
  1341. CREATE_FA2(TYPE, NAMELC, 80) \
  1342. CREATE_FA2(TYPE, NAMELC, 96) \
  1343. CREATE_FA2(TYPE, NAMELC, 112) \
  1344. CREATE_FA2(TYPE, NAMELC, 128) \
  1345. CREATE_FA2(TYPE, NAMELC, 256)
  1346. CREATE_FA(GGML_TYPE_F16, f16)
  1347. CREATE_FA(GGML_TYPE_Q4_0, q4_0)
  1348. CREATE_FA(GGML_TYPE_Q4_1, q4_1)
  1349. CREATE_FA(GGML_TYPE_Q5_0, q5_0)
  1350. CREATE_FA(GGML_TYPE_Q5_1, q5_1)
  1351. CREATE_FA(GGML_TYPE_Q8_0, q8_0)
  1352. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  1353. //CREATE_FA(GGML_TYPE_Q2_K, q2_k)
  1354. //CREATE_FA(GGML_TYPE_Q3_K, q3_k)
  1355. //CREATE_FA(GGML_TYPE_Q4_K, q4_k)
  1356. //CREATE_FA(GGML_TYPE_Q5_K, q5_k)
  1357. //CREATE_FA(GGML_TYPE_Q6_K, q6_k)
  1358. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl)
  1359. #undef CREATE_FA
  1360. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1361. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1362. 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); \
  1363. 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); \
  1364. 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); \
  1365. 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); \
  1366. 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); \
  1367. 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); \
  1368. // Create 2 variants, {f16,f32} accumulator
  1369. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1370. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1371. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1372. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  1373. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_0].f16acc, matmul_q4_0_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1374. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_1].f16acc, matmul_q4_1_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1375. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_0].f16acc, matmul_q5_0_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1376. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_1].f16acc, matmul_q5_1_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1377. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q8_0].f16acc, matmul_q8_0_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1378. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q2_K].f16acc, matmul_q2_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1379. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q3_K].f16acc, matmul_q3_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1380. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_K].f16acc, matmul_q4_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1381. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_K].f16acc, matmul_q5_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1382. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q6_K].f16acc, matmul_q6_k_f16, _f16acc, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  1383. CREATE_MM(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ4_NL].f16acc, matmul_iq4_nl_f16, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  1384. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  1385. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f16acc, matmul_id_q4_0_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1386. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f16acc, matmul_id_q4_1_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1387. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f16acc, matmul_id_q5_0_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1388. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f16acc, matmul_id_q5_1_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1389. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f16acc, matmul_id_q8_0_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1390. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f16acc, matmul_id_q2_k_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1391. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f16acc, matmul_id_q3_k_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1392. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f16acc, matmul_id_q4_k_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1393. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f16acc, matmul_id_q5_k_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1394. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f16acc, matmul_id_q6_k_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1395. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f16acc, matmul_id_iq4_nl_f16, , mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  1396. #undef CREATE_MM
  1397. #undef CREATE_MM2
  1398. } else
  1399. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  1400. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  1401. if (device->coopmat_support) {
  1402. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1403. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1404. if (device->mul_mat ## ID ## _l) \
  1405. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _coopmat_len, NAMELC ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, true); \
  1406. if (device->mul_mat ## ID ## _m) \
  1407. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _coopmat_len, NAMELC ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, true); \
  1408. if (device->mul_mat ## ID ## _s) \
  1409. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _coopmat_len, NAMELC ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, true); \
  1410. if (device->mul_mat ## ID ## _l) \
  1411. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _coopmat_len, NAMELC ## _aligned ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, true); \
  1412. if (device->mul_mat ## ID ## _m) \
  1413. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _coopmat_len, NAMELC ## _aligned ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, true); \
  1414. if (device->mul_mat ## ID ## _s) \
  1415. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _coopmat_len, NAMELC ## _aligned ## F16ACC ## _coopmat_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, true); \
  1416. // Create 2 variants, {f16,f32} accumulator
  1417. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1418. if (device->coopmat_acc_f16_support) { \
  1419. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1420. } \
  1421. if (device->coopmat_acc_f32_support) { \
  1422. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1423. } \
  1424. CREATE_MM(pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1425. CREATE_MM(pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1426. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1427. CREATE_MM2(pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1428. if (device->coopmat_acc_f16_support) {
  1429. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f16acc, matmul_q4_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1430. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f16acc, matmul_q4_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1431. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f16acc, matmul_q5_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1432. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f16acc, matmul_q5_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1433. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f16acc, matmul_q8_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1434. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f16acc, matmul_q2_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1435. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f16acc, matmul_q3_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1436. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f16acc, matmul_q4_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1437. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f16acc, matmul_q5_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1438. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f16acc, matmul_q6_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1439. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f16acc, matmul_iq4_nl_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1440. } else {
  1441. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f16acc, matmul_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1442. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f16acc, matmul_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1443. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f16acc, matmul_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1444. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f16acc, matmul_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1445. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f16acc, matmul_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1446. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f16acc, matmul_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1447. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f16acc, matmul_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1448. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f16acc, matmul_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1449. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f16acc, matmul_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1450. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f16acc, matmul_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1451. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f16acc, matmul_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1452. }
  1453. // If there's not enough shared memory for row_ids and the result tile, don't create these pipelines.
  1454. if (device->mul_mat_id_s || device->mul_mat_id_m || device->mul_mat_id_l) {
  1455. CREATE_MM(pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1456. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1457. CREATE_MM2(pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1458. if (device->coopmat_acc_f16_support) {
  1459. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f16acc, matmul_id_q4_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1460. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f16acc, matmul_id_q4_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1461. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f16acc, matmul_id_q5_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1462. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f16acc, matmul_id_q5_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1463. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f16acc, matmul_id_q8_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1464. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f16acc, matmul_id_q2_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1465. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f16acc, matmul_id_q3_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1466. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f16acc, matmul_id_q4_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1467. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f16acc, matmul_id_q5_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1468. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f16acc, matmul_id_q6_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1469. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f16acc, matmul_id_iq4_nl_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1470. } else {
  1471. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f16acc, matmul_id_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1472. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f16acc, matmul_id_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1473. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f16acc, matmul_id_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1474. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f16acc, matmul_id_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1475. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f16acc, matmul_id_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1476. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f16acc, matmul_id_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1477. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f16acc, matmul_id_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1478. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f16acc, matmul_id_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1479. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f16acc, matmul_id_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1480. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f16acc, matmul_id_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1481. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f16acc, matmul_id_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1482. }
  1483. }
  1484. #undef CREATE_MM2
  1485. #undef CREATE_MM
  1486. } else
  1487. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  1488. if (device->fp16) {
  1489. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1490. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1491. if (device->mul_mat ## ID ## _l) \
  1492. 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); \
  1493. if (device->mul_mat ## ID ## _m) \
  1494. 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); \
  1495. if (device->mul_mat ## ID ## _s) \
  1496. 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); \
  1497. if (device->mul_mat ## ID ## _l) \
  1498. 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); \
  1499. if (device->mul_mat ## ID ## _m) \
  1500. 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); \
  1501. if (device->mul_mat ## ID ## _s) \
  1502. 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); \
  1503. // Create 2 variants, {f16,f32} accumulator
  1504. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1505. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1506. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1507. CREATE_MM(pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1508. CREATE_MM(pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1509. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1510. CREATE_MM2(pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1511. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f16acc, matmul_q4_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1512. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f16acc, matmul_q4_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1513. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f16acc, matmul_q5_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1514. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f16acc, matmul_q5_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1515. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f16acc, matmul_q8_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1516. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f16acc, matmul_q2_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1517. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f16acc, matmul_q3_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1518. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f16acc, matmul_q4_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1519. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f16acc, matmul_q5_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1520. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f16acc, matmul_q6_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1521. CREATE_MM(pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f16acc, matmul_iq4_nl_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  1522. // If there's not enough shared memory for row_ids and the result tile, don't create these pipelines.
  1523. if (device->mul_mat_id_s || device->mul_mat_id_m || device->mul_mat_id_l) {
  1524. CREATE_MM(pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1525. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1526. CREATE_MM2(pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1527. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f16acc, matmul_id_q4_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1528. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f16acc, matmul_id_q4_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1529. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f16acc, matmul_id_q5_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1530. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f16acc, matmul_id_q5_1_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1531. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f16acc, matmul_id_q8_0_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1532. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f16acc, matmul_id_q2_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1533. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f16acc, matmul_id_q3_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1534. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f16acc, matmul_id_q4_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1535. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f16acc, matmul_id_q5_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1536. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f16acc, matmul_id_q6_k_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1537. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f16acc, matmul_id_iq4_nl_f32, _f16acc, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1538. }
  1539. #undef CREATE_MM2
  1540. #undef CREATE_MM
  1541. } else {
  1542. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1543. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  1544. if (device->mul_mat ## ID ## _l) \
  1545. 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); \
  1546. if (device->mul_mat ## ID ## _m) \
  1547. 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); \
  1548. if (device->mul_mat ## ID ## _s) \
  1549. 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); \
  1550. if (device->mul_mat ## ID ## _l) \
  1551. 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); \
  1552. if (device->mul_mat ## ID ## _m) \
  1553. 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); \
  1554. if (device->mul_mat ## ID ## _s) \
  1555. 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); \
  1556. CREATE_MM(pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1557. CREATE_MM(pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1558. CREATE_MM(pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1559. CREATE_MM(pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  1560. CREATE_MM(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, );
  1561. CREATE_MM(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, );
  1562. CREATE_MM(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, );
  1563. CREATE_MM(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, );
  1564. CREATE_MM(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, );
  1565. CREATE_MM(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, );
  1566. CREATE_MM(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, );
  1567. CREATE_MM(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, );
  1568. CREATE_MM(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, );
  1569. CREATE_MM(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, );
  1570. CREATE_MM(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, );
  1571. // If there's not enough shared memory for row_ids and the result tile, don't create these pipelines.
  1572. if (device->mul_mat_id_s || device->mul_mat_id_m || device->mul_mat_id_l) {
  1573. CREATE_MM(pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1574. CREATE_MM(pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1575. CREATE_MM(pipeline_matmul_id_f16_f32.f32acc, matmul_id_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  1576. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1577. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1578. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1579. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1580. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1581. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1582. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1583. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1584. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1585. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1586. CREATE_MM(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  1587. }
  1588. #undef CREATE_MM
  1589. }
  1590. // mul mat vec
  1591. // the number of rows computed per shader depends on GPU model and quant
  1592. uint32_t rm_stdq = 1;
  1593. uint32_t rm_kq = 2;
  1594. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  1595. if (device->subgroup_min_size == 64 && device->subgroup_max_size == 64) { // GCN
  1596. rm_stdq = 2;
  1597. rm_kq = 4;
  1598. }
  1599. } else if (device->vendor_id == VK_VENDOR_ID_INTEL)
  1600. rm_stdq = 2;
  1601. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  1602. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f32_f32_"+std::to_string(i+1), mul_mat_vec_f32_f32_f32_len, mul_mat_vec_f32_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2, i+1}, 1);
  1603. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f32_f32_"+std::to_string(i+1), mul_mat_vec_f16_f32_f32_len, mul_mat_vec_f16_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2, i+1}, 1);
  1604. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f32_f32_"+std::to_string(i+1), mul_mat_vec_q4_0_f32_f32_len, mul_mat_vec_q4_0_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1605. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f32_f32_"+std::to_string(i+1), mul_mat_vec_q4_1_f32_f32_len, mul_mat_vec_q4_1_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1606. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f32_f32_"+std::to_string(i+1), mul_mat_vec_q5_0_f32_f32_len, mul_mat_vec_q5_0_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1607. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f32_f32_"+std::to_string(i+1), mul_mat_vec_q5_1_f32_f32_len, mul_mat_vec_q5_1_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1608. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f32_f32_"+std::to_string(i+1), mul_mat_vec_q8_0_f32_f32_len, mul_mat_vec_q8_0_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {device->subgroup_size, 1*rm_stdq, i+1}, 1, true);
  1609. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f32_f32_"+std::to_string(i+1), mul_mat_vec_q2_k_f32_f32_len, mul_mat_vec_q2_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1610. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f32_f32_"+std::to_string(i+1), mul_mat_vec_q3_k_f32_f32_len, mul_mat_vec_q3_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1611. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f32_f32_"+std::to_string(i+1), mul_mat_vec_q4_k_f32_f32_len, mul_mat_vec_q4_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1612. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f32_f32_"+std::to_string(i+1), mul_mat_vec_q5_k_f32_f32_len, mul_mat_vec_q5_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1613. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f32_f32_"+std::to_string(i+1), mul_mat_vec_q6_k_f32_f32_len, mul_mat_vec_q6_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1614. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f32_f32_"+std::to_string(i+1), mul_mat_vec_iq4_nl_f32_f32_len, mul_mat_vec_iq4_nl_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {subgroup_size_16, 2*rm_stdq, i+1}, 1, true);
  1615. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f16_f32_"+std::to_string(i+1), mul_mat_vec_f32_f16_f32_len, mul_mat_vec_f32_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2, i+1}, 1);
  1616. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f16_f32_"+std::to_string(i+1), mul_mat_vec_f16_f16_f32_len, mul_mat_vec_f16_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2, i+1}, 1);
  1617. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f16_f32_"+std::to_string(i+1), mul_mat_vec_q4_0_f16_f32_len, mul_mat_vec_q4_0_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1618. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f16_f32_"+std::to_string(i+1), mul_mat_vec_q4_1_f16_f32_len, mul_mat_vec_q4_1_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1619. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f16_f32_"+std::to_string(i+1), mul_mat_vec_q5_0_f16_f32_len, mul_mat_vec_q5_0_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1620. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f16_f32_"+std::to_string(i+1), mul_mat_vec_q5_1_f16_f32_len, mul_mat_vec_q5_1_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  1621. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f16_f32_"+std::to_string(i+1), mul_mat_vec_q8_0_f16_f32_len, mul_mat_vec_q8_0_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {device->subgroup_size, 1*rm_stdq, i+1}, 1, true);
  1622. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f16_f32_"+std::to_string(i+1), mul_mat_vec_q2_k_f16_f32_len, mul_mat_vec_q2_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1623. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f16_f32_"+std::to_string(i+1), mul_mat_vec_q3_k_f16_f32_len, mul_mat_vec_q3_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1624. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f16_f32_"+std::to_string(i+1), mul_mat_vec_q4_k_f16_f32_len, mul_mat_vec_q4_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1625. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f16_f32_"+std::to_string(i+1), mul_mat_vec_q5_k_f16_f32_len, mul_mat_vec_q5_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1626. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f16_f32_"+std::to_string(i+1), mul_mat_vec_q6_k_f16_f32_len, mul_mat_vec_q6_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  1627. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f16_f32_"+std::to_string(i+1), mul_mat_vec_iq4_nl_f16_f32_len, mul_mat_vec_iq4_nl_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {subgroup_size_16, 2*rm_stdq, i+1}, 1, true);
  1628. }
  1629. 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);
  1630. 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);
  1631. 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);
  1632. 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);
  1633. 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);
  1634. 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);
  1635. 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);
  1636. 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);
  1637. 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);
  1638. 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);
  1639. 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);
  1640. 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);
  1641. 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), {2*rm_stdq, 1, 1}, {subgroup_size_16, 2*rm_stdq}, 1, true);
  1642. // dequant shaders
  1643. 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);
  1644. 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);
  1645. 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);
  1646. 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);
  1647. 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);
  1648. 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);
  1649. 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);
  1650. 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);
  1651. 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);
  1652. 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);
  1653. 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);
  1654. 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);
  1655. // get_rows
  1656. 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);
  1657. 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);
  1658. 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);
  1659. 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);
  1660. 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);
  1661. 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);
  1662. 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);
  1663. 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);
  1664. 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);
  1665. 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);
  1666. 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);
  1667. 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);
  1668. 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);
  1669. 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);
  1670. 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);
  1671. 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);
  1672. 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);
  1673. ggml_vk_create_pipeline(device, device->pipeline_mul_mat_vec_p021_f16_f32, "mul_mat_vec_p021_f16_f32", mul_mat_vec_p021_f16_f32_len, mul_mat_vec_p021_f16_f32_data, "main", 3, 6 * sizeof(uint32_t), {1, 1, 1}, {}, 1);
  1674. 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, 7 * sizeof(uint32_t), {1, 1, 1}, {}, 1);
  1675. 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);
  1676. 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);
  1677. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_f32, "rms_norm_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  1678. 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);
  1679. 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);
  1680. 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);
  1681. 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);
  1682. 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);
  1683. 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);
  1684. 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), {(uint32_t)ggml_blck_size(GGML_TYPE_Q4_0), 1, 1}, {}, 1);
  1685. 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), {(uint32_t)ggml_blck_size(GGML_TYPE_Q4_1), 1, 1}, {}, 1);
  1686. 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), {(uint32_t)ggml_blck_size(GGML_TYPE_Q5_0), 1, 1}, {}, 1);
  1687. 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), {(uint32_t)ggml_blck_size(GGML_TYPE_Q5_1), 1, 1}, {}, 1);
  1688. 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), {(uint32_t)ggml_blck_size(GGML_TYPE_Q8_0), 1, 1}, {}, 1);
  1689. 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), {(uint32_t)ggml_blck_size(GGML_TYPE_IQ4_NL), 1, 1}, {}, 1);
  1690. 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);
  1691. 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);
  1692. 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);
  1693. 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);
  1694. 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);
  1695. 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);
  1696. ggml_vk_create_pipeline(device, device->pipeline_add_f32, "add_f32", add_f32_len, add_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1697. ggml_vk_create_pipeline(device, device->pipeline_add_f32_norepeat, "add_f32_norepeat", add_f32_len, add_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1698. ggml_vk_create_pipeline(device, device->pipeline_add_f16_f32_f16, "add_f16_f32_f16", add_f16_f32_f16_len, add_f16_f32_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1699. ggml_vk_create_pipeline(device, device->pipeline_add_f16_f32_f16_norepeat, "add_f16_f32_f16_norepeat", add_f16_f32_f16_len, add_f16_f32_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1700. 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);
  1701. ggml_vk_create_pipeline(device, device->pipeline_mul_f32, "mul_f32", mul_f32_len, mul_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1702. ggml_vk_create_pipeline(device, device->pipeline_mul_f32_norepeat, "mul_f32_norepeat", mul_f32_len, mul_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1703. ggml_vk_create_pipeline(device, device->pipeline_div_f32, "div_f32", div_f32_len, div_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {0}, 1);
  1704. ggml_vk_create_pipeline(device, device->pipeline_div_f32_norepeat, "div_f32_norepeat", div_f32_len, div_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {1}, 1);
  1705. 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);
  1706. 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);
  1707. 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);
  1708. ggml_vk_create_pipeline(device, device->pipeline_upscale_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {}, 1);
  1709. 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);
  1710. 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);
  1711. 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);
  1712. 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);
  1713. 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);
  1714. ggml_vk_create_pipeline(device, device->pipeline_pad_f32, "pad_f32", pad_f32_len, pad_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  1715. 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);
  1716. ggml_vk_create_pipeline(device, device->pipeline_gelu_f32, "gelu_f32", gelu_f32_len, gelu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1717. ggml_vk_create_pipeline(device, device->pipeline_gelu_quick_f32, "gelu_quick_f32", gelu_quick_f32_len, gelu_quick_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1718. ggml_vk_create_pipeline(device, device->pipeline_silu_f32, "silu_f32", silu_f32_len, silu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1719. ggml_vk_create_pipeline(device, device->pipeline_relu_f32, "relu_f32", relu_f32_len, relu_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1720. 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);
  1721. ggml_vk_create_pipeline(device, device->pipeline_tanh_f32, "tanh_f32", tanh_f32_len, tanh_f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  1722. 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);
  1723. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32, "soft_max_f32", soft_max_f32_len, soft_max_f32_data, "main", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  1724. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_wg512, "soft_max_f32_wg512", soft_max_f32_len, soft_max_f32_data, "main", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  1725. 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", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  1726. 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", 3, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  1727. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32, "rope_norm_f32", rope_norm_f32_len, rope_norm_f32_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1728. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32, "rope_neox_f32", rope_neox_f32_len, rope_neox_f32_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1729. if (device->float_controls_rte_fp16) {
  1730. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f16, "rope_norm_f16", rope_norm_f16_rte_len, rope_norm_f16_rte_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1731. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_rte_len, rope_neox_f16_rte_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1732. } else {
  1733. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f16, "rope_norm_f16", rope_norm_f16_len, rope_norm_f16_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1734. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_len, rope_neox_f16_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  1735. }
  1736. ggml_vk_create_pipeline(device, device->pipeline_argsort_f32, "argsort_f32", argsort_f32_len, argsort_f32_data, "main", 2, sizeof(vk_op_argsort_push_constants), {1024, 1, 1}, {}, 1);
  1737. 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_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  1738. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32, "im2col_f32", im2col_f32_len, im2col_f32_data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true);
  1739. if (device->float_controls_rte_fp16) {
  1740. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16_rte_len, im2col_f32_f16_rte_data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true);
  1741. } else {
  1742. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16_len, im2col_f32_f16_data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true);
  1743. }
  1744. 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);
  1745. 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);
  1746. 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);
  1747. for (auto &c : compiles) {
  1748. c.wait();
  1749. }
  1750. device->need_compiles = false;
  1751. }
  1752. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props);
  1753. static vk_device ggml_vk_get_device(size_t idx) {
  1754. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  1755. if (vk_instance.devices[idx] == nullptr) {
  1756. VK_LOG_DEBUG("Initializing new vk_device");
  1757. vk_device device = std::make_shared<vk_device_struct>();
  1758. vk_instance.devices[idx] = device;
  1759. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1760. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  1761. #endif
  1762. #ifdef GGML_VULKAN_PERF
  1763. device->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  1764. #endif
  1765. size_t dev_num = vk_instance.device_indices[idx];
  1766. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  1767. if (dev_num >= physical_devices.size()) {
  1768. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  1769. throw std::runtime_error("Device not found");
  1770. }
  1771. device->physical_device = physical_devices[dev_num];
  1772. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  1773. bool fp16_storage = false;
  1774. bool fp16_compute = false;
  1775. bool maintenance4_support = false;
  1776. bool sm_builtins = false;
  1777. bool amd_shader_core_properties2 = false;
  1778. bool pipeline_robustness = false;
  1779. bool coopmat2_support = false;
  1780. device->coopmat_support = false;
  1781. // Check if maintenance4 is supported
  1782. for (const auto& properties : ext_props) {
  1783. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  1784. maintenance4_support = true;
  1785. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  1786. fp16_storage = true;
  1787. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  1788. fp16_compute = true;
  1789. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  1790. sm_builtins = true;
  1791. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  1792. amd_shader_core_properties2 = true;
  1793. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  1794. pipeline_robustness = true;
  1795. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  1796. device->subgroup_size_control = true;
  1797. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  1798. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  1799. device->coopmat_support = true;
  1800. device->coopmat_m = 0;
  1801. device->coopmat_n = 0;
  1802. device->coopmat_k = 0;
  1803. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  1804. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  1805. coopmat2_support = true;
  1806. }
  1807. }
  1808. vk::PhysicalDeviceProperties2 props2;
  1809. vk::PhysicalDeviceMaintenance3Properties props3;
  1810. vk::PhysicalDeviceMaintenance4Properties props4;
  1811. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  1812. vk::PhysicalDeviceDriverProperties driver_props;
  1813. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  1814. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  1815. vk::PhysicalDeviceVulkan12Properties vk12_props;
  1816. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  1817. props2.pNext = &props3;
  1818. props3.pNext = &subgroup_props;
  1819. subgroup_props.pNext = &driver_props;
  1820. driver_props.pNext = &vk12_props;
  1821. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  1822. if (maintenance4_support) {
  1823. last_struct->pNext = (VkBaseOutStructure *)&props4;
  1824. last_struct = (VkBaseOutStructure *)&props4;
  1825. }
  1826. if (sm_builtins) {
  1827. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  1828. last_struct = (VkBaseOutStructure *)&sm_props;
  1829. }
  1830. if (amd_shader_core_properties2) {
  1831. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  1832. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  1833. }
  1834. if (device->subgroup_size_control) {
  1835. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  1836. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  1837. }
  1838. #if defined(VK_NV_cooperative_matrix2)
  1839. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  1840. if (coopmat2_support) {
  1841. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  1842. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  1843. }
  1844. #endif
  1845. device->physical_device.getProperties2(&props2);
  1846. device->properties = props2.properties;
  1847. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  1848. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  1849. device->max_memory_allocation_size = std::stoul(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  1850. } else if (maintenance4_support) {
  1851. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  1852. } else {
  1853. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  1854. }
  1855. device->vendor_id = device->properties.vendorID;
  1856. device->subgroup_size = subgroup_props.subgroupSize;
  1857. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  1858. if (sm_builtins) {
  1859. device->shader_core_count = sm_props.shaderSMCount;
  1860. } else if (amd_shader_core_properties2) {
  1861. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  1862. } else {
  1863. device->shader_core_count = 0;
  1864. }
  1865. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  1866. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  1867. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  1868. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props)) {
  1869. device->coopmat_support = false;
  1870. }
  1871. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  1872. // Try to find a non-graphics compute queue and transfer-focused queues
  1873. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  1874. 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);
  1875. const float priorities[] = { 1.0f, 1.0f };
  1876. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  1877. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  1878. if (compute_queue_family_index != transfer_queue_family_index) {
  1879. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  1880. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  1881. } else if(!device->single_queue) {
  1882. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  1883. } else {
  1884. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  1885. }
  1886. vk::DeviceCreateInfo device_create_info;
  1887. std::vector<const char *> device_extensions;
  1888. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  1889. VkPhysicalDeviceFeatures2 device_features2;
  1890. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  1891. device_features2.pNext = nullptr;
  1892. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  1893. VkPhysicalDeviceVulkan11Features vk11_features;
  1894. vk11_features.pNext = nullptr;
  1895. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  1896. device_features2.pNext = &vk11_features;
  1897. VkPhysicalDeviceVulkan12Features vk12_features;
  1898. vk12_features.pNext = nullptr;
  1899. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  1900. vk11_features.pNext = &vk12_features;
  1901. last_struct = (VkBaseOutStructure *)&vk12_features;
  1902. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  1903. pl_robustness_features.pNext = nullptr;
  1904. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  1905. pl_robustness_features.pipelineRobustness = VK_FALSE;
  1906. if (pipeline_robustness) {
  1907. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  1908. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  1909. device_extensions.push_back("VK_EXT_pipeline_robustness");
  1910. }
  1911. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  1912. subgroup_size_control_features.pNext = nullptr;
  1913. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  1914. subgroup_size_control_features.computeFullSubgroups = false;
  1915. subgroup_size_control_features.subgroupSizeControl = false;
  1916. if (device->subgroup_size_control) {
  1917. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  1918. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  1919. }
  1920. #if defined(VK_KHR_cooperative_matrix)
  1921. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  1922. coopmat_features.pNext = nullptr;
  1923. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  1924. coopmat_features.cooperativeMatrix = VK_FALSE;
  1925. if (device->coopmat_support) {
  1926. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  1927. last_struct = (VkBaseOutStructure *)&coopmat_features;
  1928. }
  1929. #endif
  1930. #if defined(VK_NV_cooperative_matrix2)
  1931. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  1932. coopmat2_features.pNext = nullptr;
  1933. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  1934. if (coopmat2_support) {
  1935. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  1936. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  1937. device_extensions.push_back("VK_NV_cooperative_matrix2");
  1938. }
  1939. #endif
  1940. VkPhysicalDeviceMaintenance4Features maint4_features {};
  1941. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  1942. if (maintenance4_support) {
  1943. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  1944. last_struct = (VkBaseOutStructure *)&maint4_features;
  1945. device_extensions.push_back("VK_KHR_maintenance4");
  1946. }
  1947. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  1948. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  1949. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  1950. if (device->subgroup_size_control) {
  1951. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  1952. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  1953. device_extensions.push_back("VK_EXT_subgroup_size_control");
  1954. }
  1955. device->subgroup_size_control = device->subgroup_size_control &&
  1956. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  1957. subgroup_size_control_features.subgroupSizeControl;
  1958. if (device->subgroup_size_control) {
  1959. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  1960. }
  1961. #if defined(VK_KHR_cooperative_matrix)
  1962. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  1963. #endif
  1964. if (coopmat2_support) {
  1965. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  1966. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  1967. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  1968. coopmat2_features.cooperativeMatrixReductions &&
  1969. coopmat2_features.cooperativeMatrixConversions &&
  1970. coopmat2_features.cooperativeMatrixPerElementOperations &&
  1971. coopmat2_features.cooperativeMatrixTensorAddressing &&
  1972. coopmat2_features.cooperativeMatrixBlockLoads &&
  1973. vk12_features.bufferDeviceAddress) {
  1974. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  1975. uint32_t count = 0;
  1976. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  1977. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  1978. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  1979. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  1980. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  1981. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  1982. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  1983. flexible_dimensions.resize(count, empty_prop);
  1984. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  1985. bool found_fp16_128 = false,
  1986. found_fp16_256 = false,
  1987. found_fp32_128 = false,
  1988. found_fp32_256 = false;
  1989. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  1990. // with 32x16x16 and 256 with 32x32x16.
  1991. for (auto &prop : flexible_dimensions) {
  1992. if (prop.saturatingAccumulation == VK_FALSE &&
  1993. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  1994. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  1995. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  1996. if (prop.workgroupInvocations == 128 &&
  1997. prop.MGranularity <= 32 &&
  1998. prop.NGranularity <= 16 &&
  1999. prop.KGranularity <= 16) {
  2000. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  2001. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  2002. found_fp16_128 = true;
  2003. }
  2004. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  2005. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  2006. found_fp32_128 = true;
  2007. }
  2008. }
  2009. if (prop.workgroupInvocations == 256 &&
  2010. prop.MGranularity <= 32 &&
  2011. prop.NGranularity <= 32 &&
  2012. prop.KGranularity <= 16) {
  2013. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  2014. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  2015. found_fp16_256 = true;
  2016. }
  2017. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  2018. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  2019. found_fp32_256 = true;
  2020. }
  2021. }
  2022. }
  2023. }
  2024. if (found_fp16_128 && found_fp16_256 &&
  2025. found_fp32_128 && found_fp32_256 &&
  2026. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  2027. device->coopmat2 = true;
  2028. }
  2029. }
  2030. #endif
  2031. }
  2032. if (!vk11_features.storageBuffer16BitAccess) {
  2033. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  2034. throw std::runtime_error("Unsupported device");
  2035. }
  2036. device_extensions.push_back("VK_KHR_16bit_storage");
  2037. #ifdef GGML_VULKAN_VALIDATE
  2038. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  2039. #endif
  2040. if (device->fp16) {
  2041. device_extensions.push_back("VK_KHR_shader_float16_int8");
  2042. }
  2043. #if defined(VK_KHR_cooperative_matrix)
  2044. if (device->coopmat_support) {
  2045. // Query supported shapes
  2046. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  2047. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  2048. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  2049. uint32_t cm_props_num;
  2050. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  2051. cm_props.resize(cm_props_num);
  2052. for (auto& prop : cm_props) {
  2053. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  2054. }
  2055. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  2056. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  2057. for (auto& prop : cm_props) {
  2058. 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));
  2059. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  2060. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  2061. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  2062. ) {
  2063. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  2064. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  2065. // coopmat sizes not set yet
  2066. if (device->coopmat_m == 0) {
  2067. device->coopmat_acc_f32_support = true;
  2068. device->coopmat_m = prop.MSize;
  2069. device->coopmat_n = prop.NSize;
  2070. device->coopmat_k = prop.KSize;
  2071. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  2072. // Only enable if shape is identical
  2073. device->coopmat_acc_f32_support = true;
  2074. }
  2075. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  2076. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  2077. // coopmat sizes not set yet
  2078. if (device->coopmat_m == 0) {
  2079. device->coopmat_acc_f16_support = true;
  2080. device->coopmat_m = prop.MSize;
  2081. device->coopmat_n = prop.NSize;
  2082. device->coopmat_k = prop.KSize;
  2083. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  2084. // Only enable if shape is identical
  2085. device->coopmat_acc_f16_support = true;
  2086. }
  2087. }
  2088. }
  2089. }
  2090. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  2091. // No suitable matmul mode found
  2092. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  2093. device->coopmat_support = false;
  2094. }
  2095. }
  2096. if (device->coopmat_support) {
  2097. device_extensions.push_back("VK_KHR_cooperative_matrix");
  2098. }
  2099. #endif
  2100. device->name = GGML_VK_NAME + std::to_string(idx);
  2101. device_create_info = {
  2102. vk::DeviceCreateFlags(),
  2103. device_queue_create_infos,
  2104. {},
  2105. device_extensions
  2106. };
  2107. device_create_info.setPNext(&device_features2);
  2108. device->device = device->physical_device.createDevice(device_create_info);
  2109. // Queues
  2110. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  2111. // Shaders
  2112. // Disable matmul tile sizes early if performance low or not supported
  2113. switch (device->vendor_id) {
  2114. #ifndef GGML_VULKAN_RUN_TESTS
  2115. case VK_VENDOR_ID_AMD:
  2116. case VK_VENDOR_ID_INTEL:
  2117. device->mul_mat_l = false;
  2118. device->mul_mat_m = true;
  2119. device->mul_mat_s = true;
  2120. device->mul_mat_id_l = false;
  2121. device->mul_mat_id_m = true;
  2122. device->mul_mat_id_s = true;
  2123. break;
  2124. case VK_VENDOR_ID_APPLE:
  2125. device->mul_mat_l = false;
  2126. device->mul_mat_m = true;
  2127. device->mul_mat_s = false;
  2128. device->mul_mat_id_l = false;
  2129. device->mul_mat_id_m = true;
  2130. device->mul_mat_id_s = false;
  2131. break;
  2132. #endif
  2133. default:
  2134. device->mul_mat_l = true;
  2135. device->mul_mat_m = true;
  2136. device->mul_mat_s = true;
  2137. device->mul_mat_id_l = true;
  2138. device->mul_mat_id_m = true;
  2139. device->mul_mat_id_s = true;
  2140. break;
  2141. }
  2142. ggml_vk_load_shaders(device);
  2143. if (!device->single_queue) {
  2144. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  2145. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  2146. } else {
  2147. // TODO: Use pointer or reference to avoid copy
  2148. device->transfer_queue = device->compute_queue;
  2149. }
  2150. device->buffer_type = {
  2151. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  2152. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  2153. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  2154. };
  2155. device->fence = device->device.createFence({});
  2156. device->idx = idx;
  2157. return device;
  2158. }
  2159. return vk_instance.devices[idx];
  2160. }
  2161. static void ggml_vk_print_gpu_info(size_t idx) {
  2162. GGML_ASSERT(idx < vk_instance.device_indices.size());
  2163. size_t dev_num = vk_instance.device_indices[idx];
  2164. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  2165. GGML_ASSERT(vk_instance_initialized);
  2166. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  2167. if (dev_num >= devices.size()) {
  2168. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  2169. throw std::runtime_error("Device not found");
  2170. }
  2171. vk::PhysicalDevice physical_device = devices[dev_num];
  2172. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  2173. vk::PhysicalDeviceProperties2 props2;
  2174. vk::PhysicalDeviceMaintenance3Properties props3;
  2175. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  2176. vk::PhysicalDeviceDriverProperties driver_props;
  2177. props2.pNext = &props3;
  2178. props3.pNext = &subgroup_props;
  2179. subgroup_props.pNext = &driver_props;
  2180. physical_device.getProperties2(&props2);
  2181. const size_t subgroup_size = subgroup_props.subgroupSize;
  2182. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  2183. bool fp16_storage = false;
  2184. bool fp16_compute = false;
  2185. bool coopmat_support = false;
  2186. bool coopmat2_support = false;
  2187. for (auto properties : ext_props) {
  2188. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  2189. fp16_storage = true;
  2190. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  2191. fp16_compute = true;
  2192. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2193. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  2194. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  2195. coopmat_support = true;
  2196. #endif
  2197. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2198. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  2199. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  2200. coopmat2_support = true;
  2201. #endif
  2202. }
  2203. }
  2204. if (!ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props)) {
  2205. coopmat_support = false;
  2206. }
  2207. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  2208. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  2209. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  2210. vk::PhysicalDeviceFeatures device_features = physical_device.getFeatures();
  2211. VkPhysicalDeviceFeatures2 device_features2;
  2212. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  2213. device_features2.pNext = nullptr;
  2214. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  2215. VkPhysicalDeviceVulkan11Features vk11_features;
  2216. vk11_features.pNext = nullptr;
  2217. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  2218. device_features2.pNext = &vk11_features;
  2219. VkPhysicalDeviceVulkan12Features vk12_features;
  2220. vk12_features.pNext = nullptr;
  2221. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  2222. vk11_features.pNext = &vk12_features;
  2223. // Pointer to the last chain element
  2224. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_features;
  2225. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2226. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  2227. coopmat_features.pNext = nullptr;
  2228. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  2229. coopmat_features.cooperativeMatrix = VK_FALSE;
  2230. if (coopmat_support) {
  2231. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  2232. last_struct = (VkBaseOutStructure *)&coopmat_features;
  2233. }
  2234. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  2235. fp16 = fp16 && vk12_features.shaderFloat16;
  2236. coopmat_support = coopmat_support && coopmat_features.cooperativeMatrix;
  2237. #endif
  2238. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  2239. std::string device_name = props2.properties.deviceName.data();
  2240. GGML_LOG_DEBUG("ggml_vulkan: %zu = %s (%s) | uma: %d | fp16: %d | warp size: %zu | matrix cores: %s\n",
  2241. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, subgroup_size, matrix_cores.c_str());
  2242. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  2243. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  2244. }
  2245. }
  2246. static bool ggml_vk_instance_validation_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  2247. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  2248. void ggml_vk_instance_init() {
  2249. if (vk_instance_initialized) {
  2250. return;
  2251. }
  2252. VK_LOG_DEBUG("ggml_vk_instance_init()");
  2253. vk_instance_initialized = true;
  2254. uint32_t api_version = vk::enumerateInstanceVersion();
  2255. if (api_version < VK_API_VERSION_1_2) {
  2256. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  2257. GGML_ABORT("fatal error");
  2258. }
  2259. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  2260. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  2261. const bool validation_ext = ggml_vk_instance_validation_ext_available(instance_extensions);
  2262. #ifdef __APPLE__
  2263. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  2264. #endif
  2265. std::vector<const char*> layers;
  2266. if (validation_ext) {
  2267. layers.push_back("VK_LAYER_KHRONOS_validation");
  2268. }
  2269. std::vector<const char*> extensions;
  2270. if (validation_ext) {
  2271. extensions.push_back("VK_EXT_validation_features");
  2272. }
  2273. #ifdef __APPLE__
  2274. if (portability_enumeration_ext) {
  2275. extensions.push_back("VK_KHR_portability_enumeration");
  2276. }
  2277. #endif
  2278. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions);
  2279. #ifdef __APPLE__
  2280. if (portability_enumeration_ext) {
  2281. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  2282. }
  2283. #endif
  2284. std::vector<vk::ValidationFeatureEnableEXT> features_enable;
  2285. vk::ValidationFeaturesEXT validation_features;
  2286. if (validation_ext) {
  2287. features_enable = { vk::ValidationFeatureEnableEXT::eBestPractices };
  2288. validation_features = {
  2289. features_enable,
  2290. {},
  2291. };
  2292. validation_features.setPNext(nullptr);
  2293. instance_create_info.setPNext(&validation_features);
  2294. GGML_LOG_DEBUG("ggml_vulkan: Validation layers enabled\n");
  2295. }
  2296. vk_instance.instance = vk::createInstance(instance_create_info);
  2297. size_t num_available_devices = vk_instance.instance.enumeratePhysicalDevices().size();
  2298. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  2299. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  2300. if (devices_env != nullptr) {
  2301. std::string devices(devices_env);
  2302. std::replace(devices.begin(), devices.end(), ',', ' ');
  2303. std::stringstream ss(devices);
  2304. size_t tmp;
  2305. while (ss >> tmp) {
  2306. if(tmp >= num_available_devices) {
  2307. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  2308. throw std::runtime_error("Invalid Vulkan device index");
  2309. }
  2310. vk_instance.device_indices.push_back(tmp);
  2311. }
  2312. } else {
  2313. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  2314. // Make sure at least one device exists
  2315. if (devices.empty()) {
  2316. std::cerr << "ggml_vulkan: Error: No devices found." << std::endl;
  2317. GGML_ABORT("fatal error");
  2318. }
  2319. // Default to using all dedicated GPUs
  2320. for (size_t i = 0; i < devices.size(); i++) {
  2321. vk::PhysicalDeviceProperties2 new_props;
  2322. vk::PhysicalDeviceDriverProperties new_driver;
  2323. vk::PhysicalDeviceIDProperties new_id;
  2324. new_props.pNext = &new_driver;
  2325. new_driver.pNext = &new_id;
  2326. devices[i].getProperties2(&new_props);
  2327. if (new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) {
  2328. // Check if there are two physical devices corresponding to the same GPU
  2329. auto old_device = std::find_if(
  2330. vk_instance.device_indices.begin(),
  2331. vk_instance.device_indices.end(),
  2332. [&devices, &new_id](const size_t k){
  2333. vk::PhysicalDeviceProperties2 old_props;
  2334. vk::PhysicalDeviceIDProperties old_id;
  2335. old_props.pNext = &old_id;
  2336. devices[k].getProperties2(&old_props);
  2337. return std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  2338. }
  2339. );
  2340. if (old_device == vk_instance.device_indices.end()) {
  2341. vk_instance.device_indices.push_back(i);
  2342. } else {
  2343. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  2344. // This can cause error when splitting layers aross the devices, need to keep only 1
  2345. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  2346. vk::PhysicalDeviceProperties2 old_props;
  2347. vk::PhysicalDeviceDriverProperties old_driver;
  2348. old_props.pNext = &old_driver;
  2349. devices[*old_device].getProperties2(&old_props);
  2350. std::map<vk::DriverId, int> driver_priorities {};
  2351. int old_priority = std::numeric_limits<int>::max();
  2352. int new_priority = std::numeric_limits<int>::max();
  2353. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  2354. // Smaller number -> higher priority
  2355. switch (old_props.properties.vendorID) {
  2356. case VK_VENDOR_ID_AMD:
  2357. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  2358. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  2359. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  2360. break;
  2361. case VK_VENDOR_ID_INTEL:
  2362. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  2363. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  2364. break;
  2365. case VK_VENDOR_ID_NVIDIA:
  2366. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  2367. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  2368. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  2369. #endif
  2370. break;
  2371. }
  2372. if (driver_priorities.count(old_driver.driverID)) {
  2373. old_priority = driver_priorities[old_driver.driverID];
  2374. }
  2375. if (driver_priorities.count(new_driver.driverID)) {
  2376. new_priority = driver_priorities[new_driver.driverID];
  2377. }
  2378. if (new_priority < old_priority) {
  2379. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  2380. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  2381. vk_instance.device_indices.push_back(i);
  2382. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  2383. }
  2384. else {
  2385. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  2386. }
  2387. }
  2388. }
  2389. }
  2390. // If no dedicated GPUs found, fall back to GPU 0
  2391. if (vk_instance.device_indices.empty()) {
  2392. vk_instance.device_indices.push_back(0);
  2393. }
  2394. }
  2395. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  2396. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  2397. ggml_vk_print_gpu_info(i);
  2398. }
  2399. }
  2400. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  2401. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  2402. ggml_vk_instance_init();
  2403. GGML_ASSERT(idx < vk_instance.device_indices.size());
  2404. ctx->name = GGML_VK_NAME + std::to_string(idx);
  2405. ctx->device = ggml_vk_get_device(idx);
  2406. ctx->semaphore_idx = 0;
  2407. ctx->event_idx = 0;
  2408. ctx->prealloc_size_x = 0;
  2409. ctx->prealloc_size_y = 0;
  2410. ctx->prealloc_size_split_k = 0;
  2411. ctx->fence = ctx->device->device.createFence({});
  2412. #ifdef GGML_VULKAN_CHECK_RESULTS
  2413. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  2414. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  2415. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  2416. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  2417. #endif
  2418. }
  2419. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  2420. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  2421. switch (type) {
  2422. case GGML_TYPE_F32:
  2423. case GGML_TYPE_Q4_0:
  2424. case GGML_TYPE_Q4_1:
  2425. case GGML_TYPE_Q5_0:
  2426. case GGML_TYPE_Q5_1:
  2427. case GGML_TYPE_Q8_0:
  2428. case GGML_TYPE_Q2_K:
  2429. case GGML_TYPE_Q3_K:
  2430. case GGML_TYPE_Q4_K:
  2431. case GGML_TYPE_Q5_K:
  2432. case GGML_TYPE_Q6_K:
  2433. case GGML_TYPE_IQ4_NL:
  2434. break;
  2435. default:
  2436. return nullptr;
  2437. }
  2438. return ctx->device->pipeline_dequant[type];
  2439. }
  2440. 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) {
  2441. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  2442. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  2443. return ctx->device->pipeline_matmul_f32;
  2444. }
  2445. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  2446. return ctx->device->pipeline_matmul_f32_f16;
  2447. }
  2448. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  2449. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2450. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  2451. }
  2452. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2453. return ctx->device->pipeline_matmul_f16.f16acc;
  2454. }
  2455. } else {
  2456. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2457. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  2458. }
  2459. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2460. return ctx->device->pipeline_matmul_f16.f32acc;
  2461. }
  2462. }
  2463. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  2464. return nullptr;
  2465. }
  2466. switch (src0_type) {
  2467. case GGML_TYPE_Q4_0:
  2468. case GGML_TYPE_Q4_1:
  2469. case GGML_TYPE_Q5_0:
  2470. case GGML_TYPE_Q5_1:
  2471. case GGML_TYPE_Q8_0:
  2472. case GGML_TYPE_Q2_K:
  2473. case GGML_TYPE_Q3_K:
  2474. case GGML_TYPE_Q4_K:
  2475. case GGML_TYPE_Q5_K:
  2476. case GGML_TYPE_Q6_K:
  2477. case GGML_TYPE_IQ4_NL:
  2478. break;
  2479. default:
  2480. return nullptr;
  2481. }
  2482. if (ctx->device->coopmat2) {
  2483. assert(src1_type == GGML_TYPE_F16);
  2484. return ctx->device->pipeline_dequant_mul_mat_mat_f16[src0_type].f16acc;
  2485. }
  2486. return ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f32acc;
  2487. }
  2488. 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) {
  2489. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  2490. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16);
  2491. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  2492. switch (a_type) {
  2493. case GGML_TYPE_F32:
  2494. case GGML_TYPE_F16:
  2495. case GGML_TYPE_Q4_0:
  2496. case GGML_TYPE_Q4_1:
  2497. case GGML_TYPE_Q5_0:
  2498. case GGML_TYPE_Q5_1:
  2499. case GGML_TYPE_Q8_0:
  2500. case GGML_TYPE_Q2_K:
  2501. case GGML_TYPE_Q3_K:
  2502. case GGML_TYPE_Q4_K:
  2503. case GGML_TYPE_Q5_K:
  2504. case GGML_TYPE_Q6_K:
  2505. case GGML_TYPE_IQ4_NL:
  2506. break;
  2507. default:
  2508. return nullptr;
  2509. }
  2510. return b_type == GGML_TYPE_F32 ? ctx->device->pipeline_dequant_mul_mat_vec_f32_f32[a_type][num_cols-1] : ctx->device->pipeline_dequant_mul_mat_vec_f16_f32[a_type][num_cols-1];
  2511. }
  2512. 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) {
  2513. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  2514. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  2515. return ctx->device->pipeline_matmul_id_f32;
  2516. }
  2517. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  2518. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2519. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  2520. }
  2521. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2522. return ctx->device->pipeline_matmul_id_f16.f16acc;
  2523. }
  2524. } else {
  2525. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  2526. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  2527. }
  2528. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  2529. return ctx->device->pipeline_matmul_id_f16.f32acc;
  2530. }
  2531. }
  2532. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  2533. switch (src0_type) {
  2534. case GGML_TYPE_Q4_0:
  2535. case GGML_TYPE_Q4_1:
  2536. case GGML_TYPE_Q5_0:
  2537. case GGML_TYPE_Q5_1:
  2538. case GGML_TYPE_Q8_0:
  2539. case GGML_TYPE_Q2_K:
  2540. case GGML_TYPE_Q3_K:
  2541. case GGML_TYPE_Q4_K:
  2542. case GGML_TYPE_Q5_K:
  2543. case GGML_TYPE_Q6_K:
  2544. case GGML_TYPE_IQ4_NL:
  2545. break;
  2546. default:
  2547. return nullptr;
  2548. }
  2549. return ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f32acc;
  2550. }
  2551. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type) {
  2552. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  2553. GGML_ASSERT(b_type == GGML_TYPE_F32);
  2554. switch (a_type) {
  2555. case GGML_TYPE_F32:
  2556. case GGML_TYPE_F16:
  2557. case GGML_TYPE_Q4_0:
  2558. case GGML_TYPE_Q4_1:
  2559. case GGML_TYPE_Q5_0:
  2560. case GGML_TYPE_Q5_1:
  2561. case GGML_TYPE_Q8_0:
  2562. case GGML_TYPE_Q2_K:
  2563. case GGML_TYPE_Q3_K:
  2564. case GGML_TYPE_Q4_K:
  2565. case GGML_TYPE_Q5_K:
  2566. case GGML_TYPE_Q6_K:
  2567. case GGML_TYPE_IQ4_NL:
  2568. break;
  2569. default:
  2570. return nullptr;
  2571. }
  2572. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[a_type];
  2573. }
  2574. static vk_buffer ggml_vk_pool_malloc(ggml_backend_vk_context * ctx, size_t size) {
  2575. VK_LOG_DEBUG("ggml_vk_pool_malloc(" << size << ")");
  2576. VK_LOG_MEMORY("ggml_vk_pool_malloc");
  2577. int best_i = -1;
  2578. size_t best_size = std::numeric_limits<size_t>::max(); //smallest unused buffer that fits our needs
  2579. int worst_i = -1;
  2580. size_t worst_size = 0; //largest unused buffer seen so far
  2581. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  2582. vk_buffer &b = ctx->buffer_pool[i];
  2583. if (b != nullptr && b->size >= size && b->size < best_size) {
  2584. best_i = i;
  2585. best_size = b->size;
  2586. }
  2587. if (b != nullptr && b->size > worst_size) {
  2588. worst_i = i;
  2589. worst_size = b->size;
  2590. }
  2591. }
  2592. if(best_i != -1) {
  2593. //found the smallest buffer that fits our needs
  2594. vk_buffer b = ctx->buffer_pool[best_i];
  2595. ctx->buffer_pool[best_i].reset();
  2596. return b;
  2597. }
  2598. if(worst_i != -1) {
  2599. //no buffer that fits our needs, resize largest one to save memory
  2600. vk_buffer& b = ctx->buffer_pool[worst_i];
  2601. ggml_vk_destroy_buffer(b);
  2602. }
  2603. return ggml_vk_create_buffer_device(ctx->device, size);
  2604. }
  2605. static void ggml_vk_pool_free(ggml_backend_vk_context * ctx, vk_buffer& buffer) {
  2606. VK_LOG_DEBUG("ggml_vk_pool_free(" << buffer->size << ")");
  2607. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  2608. vk_buffer& b = ctx->buffer_pool[i];
  2609. if (b == nullptr) {
  2610. b = buffer;
  2611. return;
  2612. }
  2613. }
  2614. std::cerr << "ggml_vulkan: WARNING: vk buffer pool full, increase MAX_VK_BUFFERS" << std::endl;
  2615. ggml_vk_destroy_buffer(buffer);
  2616. }
  2617. // Returns an available temporary buffer that may only be used temporarily, it will be reused
  2618. static vk_buffer ggml_vk_create_buffer_temp(ggml_backend_vk_context * ctx, size_t size) {
  2619. // Try to find existing temp buffer with enough capacity
  2620. for (auto& buffer : ctx->gc.temp_buffers) {
  2621. if (buffer->size >= size) {
  2622. return buffer;
  2623. }
  2624. }
  2625. VK_LOG_MEMORY("ggml_vk_create_buffer_temp(" << size << ")");
  2626. // Otherwise create new buffer
  2627. vk_buffer buf = ggml_vk_pool_malloc(ctx, size);
  2628. ctx->gc.temp_buffers.push_back(buf);
  2629. return buf;
  2630. }
  2631. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  2632. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  2633. vk_buffer buf = ggml_vk_create_buffer(device, size,
  2634. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  2635. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  2636. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  2637. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  2638. size/1024.0/1024.0);
  2639. device->device.freeMemory(buf->device_memory);
  2640. device->device.destroyBuffer(buf->buffer);
  2641. return nullptr;
  2642. }
  2643. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  2644. return buf->ptr;
  2645. }
  2646. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  2647. if (ptr == nullptr) {
  2648. return;
  2649. }
  2650. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  2651. vk_buffer buf;
  2652. size_t index;
  2653. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  2654. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  2655. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  2656. if (ptr >= addr && ptr < endr) {
  2657. buf = std::get<2>(device->pinned_memory[i]);
  2658. index = i;
  2659. break;
  2660. }
  2661. }
  2662. if (buf == nullptr) {
  2663. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  2664. return;
  2665. }
  2666. ggml_vk_destroy_buffer(buf);
  2667. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  2668. }
  2669. static void ggml_vk_host_get(vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  2670. buf = nullptr;
  2671. buf_offset = 0;
  2672. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  2673. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  2674. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  2675. if (ptr >= addr && ptr < endr) {
  2676. buf = std::get<2>(device->pinned_memory[i]);
  2677. buf_offset = ((const uint8_t *)ptr) - addr;
  2678. break;
  2679. }
  2680. }
  2681. }
  2682. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_queue& q, bool one_time = true) {
  2683. vk_submission s;
  2684. s.buffer = ggml_vk_create_cmd_buffer(device, q);
  2685. if (one_time) {
  2686. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  2687. } else {
  2688. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  2689. }
  2690. return s;
  2691. }
  2692. 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, size_t push_constant_size, const void* push_constants, std::array<uint32_t, 3> elements) {
  2693. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  2694. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  2695. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  2696. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  2697. for (auto& buffer : descriptor_buffer_infos) {
  2698. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  2699. }
  2700. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  2701. GGML_ASSERT(pipeline->descriptor_set_idx < pipeline->descriptor_sets.size());
  2702. GGML_ASSERT(descriptor_buffer_infos.size() == pipeline->parameter_count);
  2703. vk::DescriptorSet& descriptor_set = pipeline->descriptor_sets[pipeline->descriptor_set_idx++];
  2704. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  2705. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  2706. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size, push_constants);
  2707. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  2708. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  2709. pipeline->layout,
  2710. 0,
  2711. { descriptor_set },
  2712. {});
  2713. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  2714. }
  2715. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  2716. s.buffer.end();
  2717. s.wait_semaphores = std::move(wait_semaphores);
  2718. s.signal_semaphores = std::move(signal_semaphores);
  2719. }
  2720. static void ggml_vk_ctx_end(vk_context& ctx) {
  2721. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  2722. if (ctx->s == nullptr) {
  2723. return;
  2724. }
  2725. ctx->s->buffer.end();
  2726. ctx->s = nullptr;
  2727. }
  2728. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  2729. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  2730. if (subctx->s != nullptr) {
  2731. ggml_vk_ctx_end(subctx);
  2732. }
  2733. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->q) });
  2734. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  2735. }
  2736. static size_t ggml_vk_align_size(size_t width, size_t align) {
  2737. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  2738. return CEIL_DIV(width, align) * align;
  2739. }
  2740. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  2741. if (memcpys == nullptr) {
  2742. memcpy(dst, src, size);
  2743. } else {
  2744. memcpys->emplace_back(dst, src, size);
  2745. }
  2746. }
  2747. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  2748. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  2749. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  2750. ggml_vk_destroy_buffer(device->sync_staging);
  2751. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  2752. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  2753. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  2754. }
  2755. }
  2756. 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) {
  2757. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  2758. GGML_ASSERT(!ggml_is_contiguous(tensor));
  2759. // Buffer is already mapped
  2760. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2761. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  2762. GGML_ABORT("fatal error");
  2763. }
  2764. // Check if src is pinned memory
  2765. vk_buffer buf = nullptr;
  2766. size_t buf_offset = 0;
  2767. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  2768. const uint64_t ne0 = tensor->ne[0];
  2769. const uint64_t ne1 = tensor->ne[1];
  2770. const uint64_t ne2 = tensor->ne[2];
  2771. const uint64_t ne3 = tensor->ne[3];
  2772. const uint64_t nb0 = tensor->nb[0];
  2773. const uint64_t nb1 = tensor->nb[1];
  2774. const uint64_t nb2 = tensor->nb[2];
  2775. const uint64_t nb3 = tensor->nb[3];
  2776. const ggml_type type = tensor->type;
  2777. const uint64_t ts = ggml_type_size(type);
  2778. const uint64_t bs = ggml_blck_size(type);
  2779. const uint64_t dstnb0 = ts;
  2780. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  2781. const uint64_t dstnb2 = dstnb1*ne1;
  2782. const uint64_t dstnb3 = dstnb2*ne2;
  2783. const uint64_t ne = ggml_nelements(tensor);
  2784. if (buf != nullptr) {
  2785. // Memory is pinned, use as staging buffer
  2786. std::vector<vk::BufferCopy> slices;
  2787. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  2788. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  2789. // Find longest contiguous slice
  2790. if (ne1*nb1 == dstnb2) {
  2791. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  2792. } else {
  2793. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  2794. if (ne0*nb0/bs == dstnb1) {
  2795. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  2796. } else {
  2797. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  2798. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  2799. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  2800. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  2801. }
  2802. }
  2803. }
  2804. }
  2805. }
  2806. }
  2807. ggml_vk_sync_buffers(subctx);
  2808. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  2809. return;
  2810. }
  2811. if (!sync_staging) {
  2812. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  2813. }
  2814. // Staging buffer required
  2815. vk_buffer& staging = ctx->device->sync_staging;
  2816. const uint64_t copy_size = ts*ne/bs;
  2817. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  2818. VkBufferCopy buf_copy{ 0, offset, copy_size };
  2819. ggml_vk_sync_buffers(subctx);
  2820. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  2821. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  2822. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  2823. // Find longest contiguous slice
  2824. if (ne1*nb1 == dstnb2) {
  2825. 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);
  2826. } else {
  2827. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  2828. if (ne0*nb0/bs == dstnb1) {
  2829. 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);
  2830. } else {
  2831. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  2832. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  2833. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  2834. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  2835. }
  2836. }
  2837. }
  2838. }
  2839. }
  2840. }
  2841. }
  2842. 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) {
  2843. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  2844. // Buffer is already mapped
  2845. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2846. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  2847. GGML_ABORT("fatal error");
  2848. }
  2849. // Check if src is pinned memory
  2850. vk_buffer buf = nullptr;
  2851. size_t buf_offset = 0;
  2852. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  2853. if (buf != nullptr) {
  2854. // Memory is pinned, use as staging buffer
  2855. std::vector<vk::BufferCopy> slices(1);
  2856. if (width == spitch) {
  2857. // Only do single write if stride is equal
  2858. slices[0].srcOffset = buf_offset;
  2859. slices[0].dstOffset = offset;
  2860. slices[0].size = width * height;
  2861. } else {
  2862. slices.resize(height);
  2863. for (size_t i = 0; i < height; i++) {
  2864. slices[i].srcOffset = buf_offset + i * spitch;
  2865. slices[i].dstOffset = offset + i * width;
  2866. slices[i].size = width;
  2867. }
  2868. }
  2869. ggml_vk_sync_buffers(subctx);
  2870. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  2871. return;
  2872. }
  2873. VK_LOG_DEBUG("STAGING");
  2874. if (!sync_staging) {
  2875. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  2876. }
  2877. // Staging buffer required
  2878. const size_t copy_size = width*height;
  2879. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  2880. vk_buffer& staging_buffer = dst->device->sync_staging;
  2881. VkBufferCopy buf_copy = {
  2882. 0,
  2883. offset,
  2884. copy_size};
  2885. ggml_vk_sync_buffers(subctx);
  2886. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  2887. if (width == spitch) {
  2888. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  2889. } else {
  2890. for (size_t i = 0; i < height; i++) {
  2891. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  2892. }
  2893. }
  2894. }
  2895. 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) {
  2896. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  2897. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  2898. }
  2899. 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) {
  2900. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  2901. // Buffer is already mapped
  2902. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  2903. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  2904. for (size_t i = 0; i < height; i++) {
  2905. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  2906. }
  2907. } else {
  2908. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue);
  2909. ggml_vk_ctx_begin(dst->device, subctx);
  2910. ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  2911. ggml_vk_ctx_end(subctx);
  2912. for (auto& cpy : subctx->in_memcpys) {
  2913. memcpy(cpy.dst, cpy.src, cpy.n);
  2914. }
  2915. ggml_vk_submit(subctx, dst->device->fence);
  2916. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  2917. dst->device->device.resetFences({ dst->device->fence });
  2918. }
  2919. }
  2920. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  2921. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  2922. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  2923. }
  2924. 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) {
  2925. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  2926. GGML_ASSERT(width > 0);
  2927. GGML_ASSERT(height > 0);
  2928. GGML_ASSERT(src != nullptr);
  2929. // TODO: staging_offset is not used
  2930. // Check if dst is pinned memory
  2931. vk_buffer buf = nullptr;
  2932. size_t buf_offset = 0;
  2933. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  2934. std::vector<vk::BufferCopy> slices(1);
  2935. if (width == spitch && width == dpitch) {
  2936. // Only do single write if stride is equal
  2937. slices[0].srcOffset = offset;
  2938. slices[0].dstOffset = buf_offset;
  2939. slices[0].size = width * height;
  2940. } else {
  2941. slices.resize(height);
  2942. for (size_t i = 0; i < height; i++) {
  2943. slices[i].srcOffset = offset + i * spitch;
  2944. slices[i].dstOffset = buf_offset + i * dpitch;
  2945. slices[i].size = width;
  2946. }
  2947. }
  2948. if (buf != nullptr) {
  2949. // Memory is pinned, use as staging buffer
  2950. ggml_vk_sync_buffers(subctx);
  2951. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  2952. return;
  2953. }
  2954. VK_LOG_DEBUG("STAGING");
  2955. if (!sync_staging) {
  2956. GGML_ABORT("Asynchronous read from non-pinned memory not supported");
  2957. }
  2958. // Fall back to staging buffer
  2959. const size_t copy_size = dpitch * height;
  2960. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  2961. vk_buffer& staging_buffer = src->device->sync_staging;
  2962. ggml_vk_sync_buffers(subctx);
  2963. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  2964. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  2965. }
  2966. 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) {
  2967. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  2968. }
  2969. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  2970. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  2971. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  2972. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  2973. // the HW device to host copy path.
  2974. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  2975. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  2976. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  2977. } else {
  2978. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue);
  2979. ggml_vk_ctx_begin(src->device, subctx);
  2980. ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  2981. ggml_vk_ctx_end(subctx);
  2982. ggml_vk_submit(subctx, src->device->fence);
  2983. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  2984. src->device->device.resetFences({ src->device->fence });
  2985. for (auto& cpy : subctx->out_memcpys) {
  2986. memcpy(cpy.dst, cpy.src, cpy.n);
  2987. }
  2988. }
  2989. }
  2990. 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) {
  2991. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  2992. // Make sure both buffers are on same device
  2993. GGML_ASSERT(src->device == dst->device);
  2994. VkBufferCopy bc{ src_offset, dst_offset, size };
  2995. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  2996. }
  2997. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  2998. if (src->device == dst->device) {
  2999. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  3000. // Copy within the device
  3001. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue);
  3002. ggml_vk_ctx_begin(src->device, subctx);
  3003. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  3004. ggml_vk_ctx_end(subctx);
  3005. ggml_vk_submit(subctx, src->device->fence);
  3006. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  3007. src->device->device.resetFences({ src->device->fence });
  3008. } else {
  3009. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  3010. // Copy device to device
  3011. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  3012. ggml_vk_ensure_sync_staging_buffer(dst->device, size);
  3013. // Copy to src staging buffer
  3014. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  3015. // memcpy to dst staging buffer
  3016. memcpy(dst->device->sync_staging->ptr, src->device->sync_staging->ptr, size);
  3017. // Copy to dst buffer
  3018. ggml_vk_buffer_copy(dst, dst_offset, dst->device->sync_staging, 0, size);
  3019. }
  3020. }
  3021. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  3022. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  3023. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue);
  3024. ggml_vk_ctx_begin(dst->device, subctx);
  3025. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  3026. ggml_vk_ctx_end(subctx);
  3027. ggml_vk_submit(subctx, dst->device->fence);
  3028. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  3029. dst->device->device.resetFences({ dst->device->fence });
  3030. }
  3031. static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, int m, int n, int k, const vk_pipeline& pipeline) {
  3032. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ")");
  3033. uint32_t split_k = 1;
  3034. if (ctx->device->shader_core_count != 0 && m >= (int)pipeline->wg_denoms[0] && n >= (int)pipeline->wg_denoms[1]) {
  3035. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  3036. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  3037. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  3038. if (k >= 2048 && m_tiles * n_tiles < ctx->device->shader_core_count / 2) {
  3039. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  3040. // Clamp to 2 or 4
  3041. split_k = std::min(split_k, 4u);
  3042. if (split_k == 3) {
  3043. split_k = 2;
  3044. }
  3045. }
  3046. }
  3047. return split_k;
  3048. }
  3049. static vk_pipeline ggml_vk_guess_matmul_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, bool aligned) {
  3050. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ")");
  3051. if (ctx->device->coopmat2) {
  3052. if ((ctx->device->mul_mat_l && (m % mmp->l->wg_denoms[0]) == 0 && (n % mmp->l->wg_denoms[1]) == 0) || (!ctx->device->mul_mat_m && !ctx->device->mul_mat_s)) {
  3053. return aligned ? mmp->a_l : mmp->l;
  3054. }
  3055. if ((ctx->device->mul_mat_m && (m % mmp->m->wg_denoms[0]) == 0 && (n % mmp->m->wg_denoms[1]) == 0) || !ctx->device->mul_mat_s) {
  3056. return aligned ? mmp->a_m : mmp->m;
  3057. }
  3058. return aligned ? mmp->a_s : mmp->s;
  3059. }
  3060. if ((ctx->device->mul_mat_s && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_m && !ctx->device->mul_mat_l)) {
  3061. return aligned ? mmp->a_s : mmp->s;
  3062. }
  3063. if ((ctx->device->mul_mat_m && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l) {
  3064. return aligned ? mmp->a_m : mmp->m;
  3065. }
  3066. return aligned ? mmp->a_l : mmp->l;
  3067. }
  3068. static uint32_t ggml_vk_guess_matmul_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n) {
  3069. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ")");
  3070. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true)->align;
  3071. }
  3072. static void ggml_vk_matmul(
  3073. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  3074. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  3075. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  3076. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  3077. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3) {
  3078. 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 << ")");
  3079. ggml_vk_sync_buffers(subctx);
  3080. if (split_k == 1) {
  3081. 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 };
  3082. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, sizeof(vk_mat_mat_push_constants), &pc, { m, n, batch });
  3083. return;
  3084. }
  3085. GGML_ASSERT(batch_stride_d == m * n);
  3086. 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, CEIL_DIV(k, split_k), ne02, ne12, broadcast2, broadcast3 };
  3087. // Make sure enough workgroups get assigned for split k to work
  3088. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, split_k_buffer }, sizeof(vk_mat_mat_push_constants), &pc1, { (CEIL_DIV(m, pipeline->wg_denoms[0]) * pipeline->wg_denoms[0]) * split_k, n, batch });
  3089. ggml_vk_sync_buffers(subctx);
  3090. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  3091. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2.size() * sizeof(uint32_t), pc2.data(), { m * n * batch, 1, 1 });
  3092. }
  3093. static vk_pipeline ggml_vk_guess_matmul_id_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, bool aligned) {
  3094. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ")");
  3095. if (ctx->device->coopmat2) {
  3096. if ((ctx->device->mul_mat_id_l && (m % mmp->l->wg_denoms[0]) == 0 && (n % mmp->l->wg_denoms[1]) == 0) || (!ctx->device->mul_mat_id_m && !ctx->device->mul_mat_id_s)) {
  3097. return aligned ? mmp->a_l : mmp->l;
  3098. }
  3099. if ((ctx->device->mul_mat_id_m && (m % mmp->m->wg_denoms[0]) == 0 && (n % mmp->m->wg_denoms[1]) == 0) || !ctx->device->mul_mat_id_s) {
  3100. return aligned ? mmp->a_m : mmp->m;
  3101. }
  3102. return aligned ? mmp->a_s : mmp->s;
  3103. }
  3104. if ((ctx->device->mul_mat_id_s && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_id_m && !ctx->device->mul_mat_id_l)) {
  3105. return aligned ? mmp->a_s : mmp->s;
  3106. }
  3107. if ((ctx->device->mul_mat_id_m && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l) {
  3108. return aligned ? mmp->a_m : mmp->m;
  3109. }
  3110. return aligned ? mmp->a_l : mmp->l;
  3111. }
  3112. static uint32_t ggml_vk_guess_matmul_id_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n) {
  3113. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ")");
  3114. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true)->align;
  3115. }
  3116. static void ggml_vk_matmul_id(
  3117. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  3118. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  3119. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  3120. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  3121. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11) {
  3122. 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 << "), " <<
  3123. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  3124. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  3125. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  3126. ggml_vk_sync_buffers(subctx);
  3127. 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,
  3128. nei0, nei1, nbi1, ne11 };
  3129. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, sizeof(vk_mat_mat_id_push_constants), &pc, { m, nei1, n_as });
  3130. }
  3131. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  3132. return
  3133. tensor->nb[0] == ggml_type_size(tensor->type) &&
  3134. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  3135. tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
  3136. }
  3137. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  3138. // Choose "contiguous copy" shader if src/dst are contiguous
  3139. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  3140. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  3141. if (contig) {
  3142. return ctx->device->pipeline_contig_cpy_f32_f32;
  3143. } else {
  3144. return ctx->device->pipeline_cpy_f32_f32;
  3145. }
  3146. }
  3147. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  3148. if (contig) {
  3149. return ctx->device->pipeline_contig_cpy_f32_f16;
  3150. } else {
  3151. return ctx->device->pipeline_cpy_f32_f16;
  3152. }
  3153. }
  3154. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  3155. if (contig) {
  3156. return ctx->device->pipeline_contig_cpy_f16_f16;
  3157. } else {
  3158. return ctx->device->pipeline_cpy_f16_f16;
  3159. }
  3160. }
  3161. if (src->type == GGML_TYPE_F32) {
  3162. switch (to) {
  3163. case GGML_TYPE_Q4_0:
  3164. case GGML_TYPE_Q4_1:
  3165. case GGML_TYPE_Q5_0:
  3166. case GGML_TYPE_Q5_1:
  3167. case GGML_TYPE_Q8_0:
  3168. case GGML_TYPE_IQ4_NL:
  3169. return ctx->device->pipeline_cpy_f32_quant[to];
  3170. default:
  3171. break;
  3172. }
  3173. }
  3174. if (to == GGML_TYPE_F32) {
  3175. switch (src->type) {
  3176. case GGML_TYPE_Q4_0:
  3177. case GGML_TYPE_Q4_1:
  3178. case GGML_TYPE_Q5_0:
  3179. case GGML_TYPE_Q5_1:
  3180. case GGML_TYPE_Q8_0:
  3181. case GGML_TYPE_IQ4_NL:
  3182. return ctx->device->pipeline_cpy_quant_f32[src->type];
  3183. default:
  3184. break;
  3185. }
  3186. }
  3187. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  3188. GGML_ABORT("fatal error");
  3189. }
  3190. 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) {
  3191. 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] << "), ";
  3192. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  3193. const int tensor_type_size = ggml_type_size(tensor->type);
  3194. const uint32_t ne = ggml_nelements(tensor);
  3195. std::array<uint32_t, 3> elements;
  3196. if (ne > 262144) {
  3197. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  3198. } else if (ne > 512) {
  3199. elements = { 512, CEIL_DIV(ne, 512), 1 };
  3200. } else {
  3201. elements = { ne, 1, 1 };
  3202. }
  3203. vk_op_unary_push_constants pc = {
  3204. (uint32_t)ne,
  3205. (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,
  3206. (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]),
  3207. 0,
  3208. 0.0f, 0.0f,
  3209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  3210. };
  3211. init_pushconst_fastdiv(pc);
  3212. ggml_vk_sync_buffers(subctx);
  3213. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, sizeof(vk_op_unary_push_constants), &pc, elements);
  3214. }
  3215. 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 dryrun = false) {
  3216. VK_LOG_DEBUG("ggml_vk_mul_mat_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];
  3217. 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];
  3218. 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];
  3219. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3220. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  3221. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3222. const uint64_t ne00 = src0->ne[0];
  3223. const uint64_t ne01 = src0->ne[1];
  3224. const uint64_t ne02 = src0->ne[2];
  3225. const uint64_t ne03 = src0->ne[3];
  3226. const uint64_t ne10 = src1->ne[0];
  3227. const uint64_t ne11 = src1->ne[1];
  3228. const uint64_t ne12 = src1->ne[2];
  3229. const uint64_t ne13 = src1->ne[3];
  3230. const uint64_t ne20 = dst->ne[0];
  3231. const uint64_t ne21 = dst->ne[1];
  3232. const uint64_t r2 = ne12 / ne02;
  3233. const uint64_t r3 = ne13 / ne03;
  3234. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3235. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3236. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3237. vk_buffer d_Qx = nullptr;
  3238. size_t qx_buf_offset = 0;
  3239. vk_buffer d_Qy = nullptr;
  3240. size_t qy_buf_offset = 0;
  3241. bool src0_uma = false;
  3242. bool src1_uma = false;
  3243. if (ctx->device->uma) {
  3244. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3245. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3246. src0_uma = d_Qx != nullptr;
  3247. src1_uma = d_Qy != nullptr;
  3248. }
  3249. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  3250. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  3251. !ggml_vk_dim01_contiguous(src0);
  3252. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  3253. !ggml_vk_dim01_contiguous(src1);
  3254. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  3255. vk_matmul_pipeline mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? GGML_TYPE_F16 : src1->type, (ggml_prec)dst->op_params[0]);
  3256. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  3257. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !y_f32_kernel) || y_non_contig;
  3258. if (qx_needs_dequant) {
  3259. // Fall back to dequant + f16 mulmat
  3260. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, GGML_TYPE_F16, y_f32_kernel ? GGML_TYPE_F32 : GGML_TYPE_F16, (ggml_prec)dst->op_params[0]);
  3261. }
  3262. // Not implemented
  3263. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3264. const int x_ne = ne01 * ne00;
  3265. const int y_ne = ne11 * ne10;
  3266. const int d_ne = ne11 * ne01;
  3267. const uint32_t kpad = ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align(ctx, mmp, ne01, ne11));
  3268. const bool aligned = ne10 == kpad && ne01 > 8 && ne11 > 8;
  3269. vk_pipeline pipeline = ggml_vk_guess_matmul_pipeline(ctx, mmp, ne01, ne11, aligned);
  3270. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, pipeline);
  3271. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  3272. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3273. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  3274. const uint64_t y_sz = y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3275. const uint64_t d_sz = sizeof(float) * d_ne;
  3276. vk_pipeline to_fp16_vk_0 = nullptr;
  3277. vk_pipeline to_fp16_vk_1 = nullptr;
  3278. if (x_non_contig) {
  3279. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, GGML_TYPE_F16);
  3280. } else {
  3281. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  3282. }
  3283. if (y_non_contig) {
  3284. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, GGML_TYPE_F16);
  3285. } else {
  3286. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3287. }
  3288. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3289. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3290. if (dryrun) {
  3291. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3292. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3293. const uint64_t split_k_size = split_k > 1 ? d_sz * ne12 * ne13 * split_k : 0;
  3294. if (
  3295. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3296. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size) ||
  3297. (split_k > 1 && split_k_size > ctx->device->max_memory_allocation_size)) {
  3298. GGML_ABORT("Requested preallocation size is too large");
  3299. }
  3300. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3301. ctx->prealloc_size_x = x_sz_upd;
  3302. }
  3303. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3304. ctx->prealloc_size_y = y_sz_upd;
  3305. }
  3306. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  3307. ctx->prealloc_size_split_k = split_k_size;
  3308. }
  3309. // Request descriptor sets
  3310. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  3311. if (qx_needs_dequant) {
  3312. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3313. }
  3314. if (qy_needs_dequant) {
  3315. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3316. }
  3317. if (split_k > 1) {
  3318. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_matmul_split_k_reduce, 1);
  3319. }
  3320. return;
  3321. }
  3322. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3323. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3324. GGML_ASSERT(d_D != nullptr);
  3325. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz * ne02 * ne03);
  3326. vk_buffer d_X;
  3327. uint64_t x_buf_offset = 0;
  3328. vk_buffer d_Y;
  3329. uint64_t y_buf_offset = 0;
  3330. if (!src0_uma) {
  3331. d_Qx = src0_buf_ctx->dev_buffer;
  3332. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3333. GGML_ASSERT(d_Qx != nullptr);
  3334. }
  3335. if (!src1_uma) {
  3336. d_Qy = src1_buf_ctx->dev_buffer;
  3337. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3338. GGML_ASSERT(d_Qy != nullptr);
  3339. }
  3340. if (qx_needs_dequant) {
  3341. d_X = ctx->prealloc_x;
  3342. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  3343. } else {
  3344. d_X = d_Qx;
  3345. x_buf_offset = qx_buf_offset;
  3346. GGML_ASSERT(qx_sz == x_sz);
  3347. }
  3348. if (qy_needs_dequant) {
  3349. d_Y = ctx->prealloc_y;
  3350. GGML_ASSERT(d_Y->size >= y_sz * ne02 * ne03);
  3351. } else {
  3352. d_Y = d_Qy;
  3353. y_buf_offset = qy_buf_offset;
  3354. GGML_ASSERT(qy_sz == y_sz);
  3355. }
  3356. if (x_non_contig) {
  3357. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, { d_Qx, qx_buf_offset, VK_WHOLE_SIZE }, { d_X, 0, VK_WHOLE_SIZE });
  3358. } else if (qx_needs_dequant) {
  3359. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  3360. ggml_vk_sync_buffers(subctx);
  3361. 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.size() * sizeof(uint32_t), pc.data(), { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  3362. }
  3363. if (y_non_contig) {
  3364. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE });
  3365. }
  3366. uint32_t stride_batch_x = ne00*ne01;
  3367. uint32_t stride_batch_y = ne10*ne11;
  3368. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  3369. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  3370. }
  3371. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  3372. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  3373. }
  3374. // compute
  3375. ggml_vk_matmul(
  3376. ctx, subctx, pipeline,
  3377. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz * ne12 * ne13 },
  3378. { d_D, d_buf_offset, d_sz * ne12 * ne13 }, { ctx->prealloc_split_k, 0, d_sz * ne12 * ne13 * split_k },
  3379. ne01, ne11, ne10,
  3380. ne10, ne10, ne01, stride_batch_x, stride_batch_y, ne20*ne21,
  3381. split_k, ne12*ne13, ne02, ne12, r2, r3
  3382. ); // NOLINT
  3383. }
  3384. 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) {
  3385. 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];
  3386. 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];
  3387. 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];
  3388. std::cerr << "), " << (dryrun ? "dryrun" : "") << "),)");
  3389. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  3390. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3391. const uint64_t ne00 = src0->ne[0];
  3392. const uint64_t ne01 = src0->ne[1];
  3393. const uint64_t ne02 = src0->ne[2];
  3394. const uint64_t ne03 = src0->ne[3];
  3395. const uint64_t ne10 = src1->ne[0];
  3396. const uint64_t ne11 = src1->ne[1];
  3397. const uint64_t ne12 = src1->ne[2];
  3398. const uint64_t ne13 = src1->ne[3];
  3399. const uint64_t ne20 = dst->ne[0];
  3400. const uint64_t ne21 = dst->ne[1];
  3401. const uint64_t ne22 = dst->ne[2];
  3402. const uint64_t ne23 = dst->ne[3];
  3403. const uint64_t r2 = ne12 / ne02;
  3404. const uint64_t r3 = ne13 / ne03;
  3405. // batch_n indicates that we need to compute a few vector results, and this assumes
  3406. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  3407. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  3408. bool batch_n = ne11 > 1;
  3409. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3410. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3411. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3412. vk_buffer d_Qx = nullptr;
  3413. size_t qx_buf_offset = 0;
  3414. vk_buffer d_Qy = nullptr;
  3415. size_t qy_buf_offset = 0;
  3416. bool src0_uma = false;
  3417. bool src1_uma = false;
  3418. if (ctx->device->uma) {
  3419. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3420. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3421. src0_uma = d_Qx != nullptr;
  3422. src1_uma = d_Qy != nullptr;
  3423. }
  3424. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  3425. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  3426. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  3427. const bool qx_needs_dequant = x_non_contig;
  3428. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  3429. // Not implemented
  3430. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3431. const uint64_t x_ne = ne01 * ne00;
  3432. const uint64_t y_ne = ne11 * ne10;
  3433. const uint64_t d_ne = ne11 * ne01;
  3434. 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);
  3435. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3436. 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;
  3437. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3438. const uint64_t d_sz = sizeof(float) * d_ne;
  3439. vk_pipeline to_fp16_vk_0 = nullptr;
  3440. vk_pipeline to_fp16_vk_1 = nullptr;
  3441. if (x_non_contig) {
  3442. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  3443. }
  3444. if (y_non_contig) {
  3445. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  3446. } else {
  3447. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3448. }
  3449. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11);
  3450. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3451. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3452. GGML_ASSERT(dmmv != nullptr);
  3453. if (dryrun) {
  3454. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3455. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3456. if (
  3457. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3458. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  3459. GGML_ABORT("Requested preallocation size is too large");
  3460. }
  3461. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3462. ctx->prealloc_size_x = x_sz_upd;
  3463. }
  3464. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3465. ctx->prealloc_size_y = y_sz_upd;
  3466. }
  3467. // Request descriptor sets
  3468. if (qx_needs_dequant) {
  3469. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3470. }
  3471. if (qy_needs_dequant) {
  3472. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3473. }
  3474. ggml_pipeline_request_descriptor_sets(ctx->device, dmmv, 1);
  3475. return;
  3476. }
  3477. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3478. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3479. GGML_ASSERT(d_D != nullptr);
  3480. vk_buffer d_X;
  3481. uint64_t x_buf_offset = 0;
  3482. vk_buffer d_Y;
  3483. uint64_t y_buf_offset = 0;
  3484. if(!src0_uma) {
  3485. d_Qx = src0_buf_ctx->dev_buffer;
  3486. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3487. GGML_ASSERT(d_Qx != nullptr);
  3488. }
  3489. if(!src1_uma) {
  3490. d_Qy = src1_buf_ctx->dev_buffer;
  3491. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3492. GGML_ASSERT(d_Qy != nullptr);
  3493. }
  3494. if (qx_needs_dequant) {
  3495. d_X = ctx->prealloc_x;
  3496. } else {
  3497. d_X = d_Qx;
  3498. x_buf_offset = qx_buf_offset;
  3499. GGML_ASSERT(qx_sz == x_sz);
  3500. }
  3501. if (qy_needs_dequant) {
  3502. d_Y = ctx->prealloc_y;
  3503. } else {
  3504. d_Y = d_Qy;
  3505. y_buf_offset = qy_buf_offset;
  3506. GGML_ASSERT(qy_sz == y_sz);
  3507. }
  3508. if (x_non_contig) {
  3509. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  3510. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, { d_Qx, qx_buf_offset, VK_WHOLE_SIZE }, { d_X, 0, VK_WHOLE_SIZE });
  3511. }
  3512. if (y_non_contig) {
  3513. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  3514. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE });
  3515. }
  3516. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  3517. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  3518. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  3519. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  3520. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  3521. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  3522. }
  3523. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  3524. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  3525. }
  3526. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  3527. uint32_t groups_x = ne01;
  3528. uint32_t groups_z = 1;
  3529. if (ne01 > max_groups_x) {
  3530. groups_z = 64;
  3531. groups_x = CEIL_DIV(groups_x, groups_z);
  3532. }
  3533. // compute
  3534. const vk_mat_vec_push_constants pc = {
  3535. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  3536. stride_batch_x, stride_batch_y, stride_batch_d,
  3537. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  3538. };
  3539. ggml_vk_sync_buffers(subctx);
  3540. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  3541. { vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 }, vk_subbuffer{ d_Y, y_buf_offset, y_sz * ne12 * ne13 }, vk_subbuffer{ d_D, d_buf_offset, d_sz * ne22 * ne23} },
  3542. sizeof(vk_mat_vec_push_constants), &pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  3543. }
  3544. 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) {
  3545. 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];
  3546. 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];
  3547. 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];
  3548. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3549. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  3550. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  3551. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  3552. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  3553. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  3554. const uint64_t ne00 = src0->ne[0];
  3555. const uint64_t ne01 = src0->ne[1];
  3556. const uint64_t ne02 = src0->ne[2];
  3557. // const uint64_t ne03 = src0->ne[3];
  3558. const uint64_t ne10 = src1->ne[0];
  3559. const uint64_t ne11 = src1->ne[1];
  3560. const uint64_t ne12 = src1->ne[2];
  3561. // const uint64_t ne13 = src1->ne[3];
  3562. GGML_ASSERT(ne11 == 1);
  3563. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3564. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3565. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3566. vk_buffer d_Qy = nullptr;
  3567. size_t qy_buf_offset = 0;
  3568. bool src1_uma = false;
  3569. if (ctx->device->uma) {
  3570. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3571. src1_uma = d_Qy != nullptr;
  3572. }
  3573. const uint64_t x_ne = ne00 * ne01 * ne02;
  3574. const uint64_t y_ne = ne10 * ne11 * ne12;
  3575. const uint64_t d_ne = ne01 * ne11 * ne12;
  3576. 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);
  3577. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3578. const uint64_t d_sz = sizeof(float) * d_ne;
  3579. if (dryrun) {
  3580. // Request descriptor sets
  3581. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_mul_mat_vec_p021_f16_f32, 1);
  3582. return;
  3583. }
  3584. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3585. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3586. GGML_ASSERT(d_D != nullptr);
  3587. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  3588. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3589. GGML_ASSERT(d_Qx != nullptr);
  3590. if (!src1_uma) {
  3591. d_Qy = src1_buf_ctx->dev_buffer;
  3592. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3593. GGML_ASSERT(d_Qx != nullptr);
  3594. }
  3595. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3596. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  3597. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3598. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  3599. // compute
  3600. 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)) };
  3601. ggml_vk_sync_buffers(subctx);
  3602. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32, { 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 } }, 6 * sizeof(uint32_t), &pc, { 1, (uint32_t)ne01, (uint32_t)ne12 });
  3603. }
  3604. 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) {
  3605. 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];
  3606. 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];
  3607. 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];
  3608. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3609. GGML_ASSERT(!ggml_is_transposed(src0));
  3610. GGML_ASSERT(!ggml_is_transposed(src1));
  3611. GGML_ASSERT(!ggml_is_permuted(src0));
  3612. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  3613. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  3614. const uint64_t ne00 = src0->ne[0];
  3615. const uint64_t ne01 = src0->ne[1];
  3616. const uint64_t ne02 = src0->ne[2];
  3617. // const uint64_t ne03 = src0->ne[3];
  3618. const uint64_t nb01 = src0->nb[1];
  3619. const uint64_t nb02 = src0->nb[2];
  3620. // const uint64_t ne10 = src1->ne[0];
  3621. const uint64_t ne11 = src1->ne[1];
  3622. const uint64_t ne12 = src1->ne[2];
  3623. // const uint64_t ne13 = src1->ne[3];
  3624. GGML_ASSERT(ne11 == 1);
  3625. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3626. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3627. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3628. vk_buffer d_Qy = nullptr;
  3629. size_t qy_buf_offset = 0;
  3630. bool src1_uma = false;
  3631. if (ctx->device->uma) {
  3632. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3633. src1_uma = d_Qy != nullptr;
  3634. }
  3635. const uint64_t d_ne = ne01 * ne11 * ne12;
  3636. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  3637. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  3638. const uint64_t qx_sz = ggml_nbytes(src0);
  3639. const uint64_t qy_sz = ggml_nbytes(src1);
  3640. const uint64_t d_sz = sizeof(float) * d_ne;
  3641. if (dryrun) {
  3642. // Request descriptor sets
  3643. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  3644. return;
  3645. }
  3646. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3647. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3648. GGML_ASSERT(d_D != nullptr);
  3649. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  3650. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3651. GGML_ASSERT(d_Qx != nullptr);
  3652. if (!src1_uma) {
  3653. d_Qy = src1_buf_ctx->dev_buffer;
  3654. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3655. GGML_ASSERT(d_Qx != nullptr);
  3656. }
  3657. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3658. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  3659. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  3660. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  3661. // compute
  3662. const std::array<uint32_t, 7> pc = { (uint32_t)ne00, (uint32_t)ne01, row_stride_x, channel_stride_x, (uint32_t)(ne12 / ne02), (uint32_t)(qy_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type)) };
  3663. ggml_vk_sync_buffers(subctx);
  3664. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  3665. { 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 } }, 7 * sizeof(uint32_t), &pc, { 1, (uint32_t)ne01, (uint32_t)ne12 });
  3666. }
  3667. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  3668. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  3669. if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  3670. // detect 0213 permutation, and batch size of 1
  3671. src0->nb[0] <= src0->nb[2] &&
  3672. src0->nb[2] <= src0->nb[1] &&
  3673. src0->nb[1] <= src0->nb[3] &&
  3674. src1->nb[0] <= src1->nb[2] &&
  3675. src1->nb[2] <= src1->nb[1] &&
  3676. src1->nb[1] <= src1->nb[3] &&
  3677. src0->ne[3] == 1 &&
  3678. src1->ne[3] == 1) {
  3679. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  3680. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  3681. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  3682. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  3683. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  3684. // when ne12 and ne13 are one.
  3685. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  3686. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type))) {
  3687. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, src0, src1, dst, dryrun);
  3688. } else {
  3689. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, dryrun);
  3690. }
  3691. }
  3692. 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) {
  3693. 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];
  3694. 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];
  3695. 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];
  3696. 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] << "),)");
  3697. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3698. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  3699. const uint64_t ne00 = src0->ne[0];
  3700. const uint64_t ne01 = src0->ne[1];
  3701. const uint64_t ne02 = src0->ne[2];
  3702. const uint64_t ne03 = src0->ne[3];
  3703. const uint64_t ne10 = src1->ne[0];
  3704. const uint64_t ne11 = src1->ne[1];
  3705. const uint64_t ne12 = src1->ne[2];
  3706. const uint64_t ne13 = src1->ne[3];
  3707. const uint64_t nei0 = ids->ne[0];
  3708. const uint64_t nei1 = ids->ne[1];
  3709. GGML_ASSERT(nei0 * nei1 <= 3072);
  3710. const uint32_t nbi1 = ids->nb[1];
  3711. const uint32_t nbi2 = ids->nb[2];
  3712. const uint64_t ne20 = dst->ne[0];
  3713. const uint64_t ne21 = dst->ne[1];
  3714. const uint64_t ne22 = dst->ne[2];
  3715. const uint64_t ne23 = dst->ne[3];
  3716. const uint64_t n_as = ne02;
  3717. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3718. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3719. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3720. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  3721. vk_buffer d_Qx = nullptr;
  3722. size_t qx_buf_offset = 0;
  3723. vk_buffer d_Qy = nullptr;
  3724. size_t qy_buf_offset = 0;
  3725. vk_buffer d_ids = nullptr;
  3726. size_t ids_buf_offset = 0;
  3727. bool src0_uma = false;
  3728. bool src1_uma = false;
  3729. bool ids_uma = false;
  3730. if (ctx->device->uma) {
  3731. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3732. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3733. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  3734. src0_uma = d_Qx != nullptr;
  3735. src1_uma = d_Qy != nullptr;
  3736. ids_uma = d_ids != nullptr;
  3737. }
  3738. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  3739. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  3740. !ggml_vk_dim01_contiguous(src0);
  3741. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  3742. !ggml_vk_dim01_contiguous(src1);
  3743. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  3744. vk_matmul_pipeline mmp = ggml_vk_get_mul_mat_mat_id_pipeline(ctx, src0->type, y_non_contig ? GGML_TYPE_F16 : src1->type, (ggml_prec)dst->op_params[0]);
  3745. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  3746. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !y_f32_kernel) || y_non_contig;
  3747. if (qx_needs_dequant) {
  3748. // Fall back to dequant + f16 mulmat
  3749. mmp = ggml_vk_get_mul_mat_mat_id_pipeline(ctx, GGML_TYPE_F16, y_f32_kernel ? GGML_TYPE_F32 : GGML_TYPE_F16, (ggml_prec)dst->op_params[0]);
  3750. }
  3751. // Not implemented
  3752. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3753. const uint64_t x_ne = ne01 * ne00;
  3754. const uint64_t y_ne = ne11 * ne10;
  3755. const uint64_t d_ne = ne21 * ne20;
  3756. const uint32_t kpad = ggml_vk_align_size(ne10, ggml_vk_guess_matmul_id_pipeline_align(ctx, mmp, ne01, nei1));
  3757. const bool aligned = ne10 == kpad && ne01 > 8 && nei1 > 8;
  3758. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned);
  3759. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  3760. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3761. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  3762. const uint64_t y_sz = y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3763. const uint64_t ids_sz = nbi2;
  3764. const uint64_t d_sz = sizeof(float) * d_ne;
  3765. vk_pipeline to_fp16_vk_0 = nullptr;
  3766. vk_pipeline to_fp16_vk_1 = nullptr;
  3767. if (x_non_contig) {
  3768. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, GGML_TYPE_F16);
  3769. } else {
  3770. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  3771. }
  3772. if (y_non_contig) {
  3773. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, GGML_TYPE_F16);
  3774. } else {
  3775. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3776. }
  3777. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3778. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3779. if (dryrun) {
  3780. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3781. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3782. if (
  3783. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3784. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  3785. GGML_ABORT("Requested preallocation size is too large");
  3786. }
  3787. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3788. ctx->prealloc_size_x = x_sz_upd;
  3789. }
  3790. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3791. ctx->prealloc_size_y = y_sz_upd;
  3792. }
  3793. // Request descriptor sets
  3794. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  3795. if (qx_needs_dequant) {
  3796. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3797. }
  3798. if (qy_needs_dequant) {
  3799. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3800. }
  3801. return;
  3802. }
  3803. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3804. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3805. GGML_ASSERT(d_D != nullptr);
  3806. vk_buffer d_X;
  3807. uint64_t x_buf_offset = 0;
  3808. vk_buffer d_Y;
  3809. uint64_t y_buf_offset = 0;
  3810. if (!src0_uma) {
  3811. d_Qx = src0_buf_ctx->dev_buffer;
  3812. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3813. GGML_ASSERT(d_Qx != nullptr);
  3814. }
  3815. if (!src1_uma) {
  3816. d_Qy = src1_buf_ctx->dev_buffer;
  3817. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3818. GGML_ASSERT(d_Qy != nullptr);
  3819. }
  3820. if (!ids_uma) {
  3821. d_ids = ids_buf_ctx->dev_buffer;
  3822. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  3823. GGML_ASSERT(d_ids != nullptr);
  3824. }
  3825. if (qx_needs_dequant) {
  3826. d_X = ctx->prealloc_x;
  3827. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  3828. } else {
  3829. d_X = d_Qx;
  3830. x_buf_offset = qx_buf_offset;
  3831. GGML_ASSERT(qx_sz == x_sz);
  3832. }
  3833. if (qy_needs_dequant) {
  3834. d_Y = ctx->prealloc_y;
  3835. GGML_ASSERT(d_Y->size >= y_sz * ne02 * ne03);
  3836. } else {
  3837. d_Y = d_Qy;
  3838. y_buf_offset = qy_buf_offset;
  3839. GGML_ASSERT(qy_sz == y_sz);
  3840. }
  3841. if (x_non_contig) {
  3842. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, { d_Qx, qx_buf_offset, VK_WHOLE_SIZE }, { d_X, 0, VK_WHOLE_SIZE });
  3843. } else if (qx_needs_dequant) {
  3844. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  3845. ggml_vk_sync_buffers(subctx);
  3846. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  3847. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, vk_subbuffer{ d_X, 0, x_sz * ne02 * ne03 } }, pc.size() * sizeof(uint32_t), pc.data(), { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  3848. }
  3849. if (y_non_contig) {
  3850. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE });
  3851. }
  3852. uint32_t stride_batch_x = ne00*ne01;
  3853. uint32_t stride_batch_y = ne10*ne11;
  3854. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  3855. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  3856. }
  3857. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  3858. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  3859. }
  3860. // compute
  3861. ggml_vk_matmul_id(
  3862. ctx, subctx, pipeline,
  3863. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz * ne12 * ne13 },
  3864. { d_D, d_buf_offset, d_sz * ne22 * ne23 }, { d_ids, ids_buf_offset, ids_sz },
  3865. ne01, ne21, ne10, ne10, ne10, ne01,
  3866. stride_batch_x, stride_batch_y, ne20*ne21,
  3867. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11
  3868. ); // NOLINT
  3869. }
  3870. 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) {
  3871. 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];
  3872. 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];
  3873. 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];
  3874. 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];
  3875. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  3876. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); // NOLINT
  3877. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  3878. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  3879. const uint64_t ne00 = src0->ne[0];
  3880. const uint64_t ne01 = src0->ne[1];
  3881. const uint64_t ne02 = src0->ne[2];
  3882. const uint64_t ne03 = src0->ne[3];
  3883. const uint64_t ne10 = src1->ne[0];
  3884. const uint64_t ne11 = src1->ne[1];
  3885. const uint64_t ne12 = src1->ne[2];
  3886. const uint64_t ne13 = src1->ne[3];
  3887. const uint64_t nei0 = ids->ne[0];
  3888. const uint64_t nei1 = ids->ne[1];
  3889. const uint64_t nbi2 = ids->nb[2];
  3890. GGML_ASSERT(nei1 == 1);
  3891. const uint64_t ne20 = dst->ne[0];
  3892. const uint64_t ne21 = dst->ne[1];
  3893. const uint64_t ne22 = dst->ne[2];
  3894. const uint64_t ne23 = dst->ne[3];
  3895. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  3896. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  3897. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  3898. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  3899. vk_buffer d_Qx = nullptr;
  3900. size_t qx_buf_offset = 0;
  3901. vk_buffer d_Qy = nullptr;
  3902. size_t qy_buf_offset = 0;
  3903. vk_buffer d_ids = nullptr;
  3904. size_t ids_buf_offset = 0;
  3905. bool src0_uma = false;
  3906. bool src1_uma = false;
  3907. bool ids_uma = false;
  3908. if (ctx->device->uma) {
  3909. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  3910. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  3911. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  3912. src0_uma = d_Qx != nullptr;
  3913. src1_uma = d_Qy != nullptr;
  3914. ids_uma = d_ids != nullptr;
  3915. }
  3916. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  3917. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  3918. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  3919. const bool qx_needs_dequant = x_non_contig;
  3920. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  3921. // Not implemented
  3922. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  3923. const uint64_t x_ne = ne01 * ne00;
  3924. const uint64_t y_ne = ne11 * ne10;
  3925. const uint64_t d_ne = ne21 * ne20;
  3926. 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);
  3927. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  3928. 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;
  3929. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  3930. const uint64_t ids_sz = nbi2;
  3931. const uint64_t d_sz = sizeof(float) * d_ne;
  3932. vk_pipeline to_fp16_vk_0 = nullptr;
  3933. vk_pipeline to_fp16_vk_1 = nullptr;
  3934. if (x_non_contig) {
  3935. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  3936. }
  3937. if (y_non_contig) {
  3938. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  3939. } else {
  3940. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  3941. }
  3942. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type);
  3943. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  3944. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  3945. GGML_ASSERT(dmmv != nullptr);
  3946. if (dryrun) {
  3947. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  3948. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  3949. if (
  3950. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  3951. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  3952. GGML_ABORT("Requested preallocation size is too large");
  3953. }
  3954. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  3955. ctx->prealloc_size_x = x_sz_upd;
  3956. }
  3957. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  3958. ctx->prealloc_size_y = y_sz_upd;
  3959. }
  3960. // Request descriptor sets
  3961. if (qx_needs_dequant) {
  3962. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_0, 1);
  3963. }
  3964. if (qy_needs_dequant) {
  3965. ggml_pipeline_request_descriptor_sets(ctx->device, to_fp16_vk_1, 1);
  3966. }
  3967. ggml_pipeline_request_descriptor_sets(ctx->device, dmmv, 1);
  3968. return;
  3969. }
  3970. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  3971. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  3972. GGML_ASSERT(d_D != nullptr);
  3973. vk_buffer d_X;
  3974. uint64_t x_buf_offset = 0;
  3975. vk_buffer d_Y;
  3976. uint64_t y_buf_offset = 0;
  3977. if(!src0_uma) {
  3978. d_Qx = src0_buf_ctx->dev_buffer;
  3979. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  3980. GGML_ASSERT(d_Qx != nullptr);
  3981. }
  3982. if(!src1_uma) {
  3983. d_Qy = src1_buf_ctx->dev_buffer;
  3984. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  3985. GGML_ASSERT(d_Qy != nullptr);
  3986. }
  3987. if(!ids_uma) {
  3988. d_ids = ids_buf_ctx->dev_buffer;
  3989. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  3990. GGML_ASSERT(d_ids != nullptr);
  3991. }
  3992. if (qx_needs_dequant) {
  3993. d_X = ctx->prealloc_x;
  3994. } else {
  3995. d_X = d_Qx;
  3996. x_buf_offset = qx_buf_offset;
  3997. GGML_ASSERT(qx_sz == x_sz);
  3998. }
  3999. if (qy_needs_dequant) {
  4000. d_Y = ctx->prealloc_y;
  4001. } else {
  4002. d_Y = d_Qy;
  4003. y_buf_offset = qy_buf_offset;
  4004. GGML_ASSERT(qy_sz == y_sz);
  4005. }
  4006. if (x_non_contig) {
  4007. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  4008. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, { d_Qx, qx_buf_offset, VK_WHOLE_SIZE }, { d_X, 0, VK_WHOLE_SIZE });
  4009. }
  4010. if (y_non_contig) {
  4011. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  4012. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE });
  4013. }
  4014. uint32_t stride_batch_y = ne10*ne11;
  4015. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  4016. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  4017. }
  4018. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  4019. uint32_t groups_x = ne01;
  4020. uint32_t groups_z = 1;
  4021. if (ne01 > max_groups_x) {
  4022. groups_z = 64;
  4023. groups_x = CEIL_DIV(groups_x, groups_z);
  4024. }
  4025. // compute
  4026. const vk_mat_vec_id_push_constants pc = {
  4027. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  4028. (uint32_t)x_ne, stride_batch_y, (uint32_t)(ne20*ne21),
  4029. (uint32_t)nei0, (uint32_t)ne11,
  4030. };
  4031. ggml_vk_sync_buffers(subctx);
  4032. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  4033. { vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 },
  4034. 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 } },
  4035. sizeof(vk_mat_vec_id_push_constants), &pc, { groups_x, (uint32_t)nei0, groups_z });
  4036. }
  4037. 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) {
  4038. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  4039. if (src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type))) {
  4040. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  4041. } else {
  4042. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  4043. }
  4044. }
  4045. 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, ggml_tensor * dst, bool dryrun = false) {
  4046. 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];
  4047. 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];
  4048. 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];
  4049. 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];
  4050. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  4051. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  4052. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  4053. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  4054. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  4055. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  4056. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  4057. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  4058. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  4059. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  4060. const uint32_t nbm1 = mask ? mask->nb[1] : 0;
  4061. const uint32_t D = neq0;
  4062. const uint32_t N = neq1;
  4063. const uint32_t KV = nek1;
  4064. GGML_ASSERT(ne0 == D);
  4065. GGML_ASSERT(ne2 == N);
  4066. // input tensor rows must be contiguous
  4067. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  4068. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  4069. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  4070. GGML_ASSERT(neq0 == D);
  4071. GGML_ASSERT(nek0 == D);
  4072. GGML_ASSERT(nev0 == D);
  4073. GGML_ASSERT(neq1 == N);
  4074. GGML_ASSERT(nev0 == D);
  4075. GGML_ASSERT(nev1 == nek1);
  4076. // dst cannot be transposed or permuted
  4077. GGML_ASSERT(nb0 == sizeof(float));
  4078. GGML_ASSERT(nb0 <= nb1);
  4079. GGML_ASSERT(nb1 <= nb2);
  4080. GGML_ASSERT(nb2 <= nb3);
  4081. assert(dst->type == GGML_TYPE_F32);
  4082. assert(q->type == GGML_TYPE_F32);
  4083. assert(k->type == v->type);
  4084. vk_pipeline *pipelines;
  4085. // XXX TODO other backends may be changing accumulator precision to default to f32 soon
  4086. bool f32acc = dst->op_params[3] == GGML_PREC_F32;
  4087. bool small_rows = N <= flash_attention_num_small_rows;
  4088. switch (D) {
  4089. case 64: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D64[k->type][f32acc][small_rows][0]; break;
  4090. case 80: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D80[k->type][f32acc][small_rows][0]; break;
  4091. case 96: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D96[k->type][f32acc][small_rows][0]; break;
  4092. case 112: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D112[k->type][f32acc][small_rows][0]; break;
  4093. case 128: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D128[k->type][f32acc][small_rows][0]; break;
  4094. case 256: pipelines = &ctx->device->pipeline_flash_attn_f32_f16_D256[k->type][f32acc][small_rows][0]; break;
  4095. default:
  4096. assert(!"unsupported D value");
  4097. return;
  4098. }
  4099. assert(pipelines);
  4100. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  4101. const uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  4102. const uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  4103. bool aligned = (KV % pipelines[1]->align) == 0 &&
  4104. // the "aligned" shader variant will forcibly align strides, for performance
  4105. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  4106. vk_pipeline pipeline = pipelines[aligned];
  4107. assert(pipeline);
  4108. if (dryrun) {
  4109. // Request descriptor sets
  4110. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  4111. return;
  4112. }
  4113. float scale = 1.0f;
  4114. float max_bias = 0.0f;
  4115. float logit_softcap = 0.0f;
  4116. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  4117. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  4118. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  4119. if (logit_softcap != 0) {
  4120. scale /= logit_softcap;
  4121. }
  4122. const uint32_t n_head_kv = neq2;
  4123. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  4124. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  4125. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  4126. ggml_vk_sync_buffers(subctx);
  4127. vk_buffer d_Q = nullptr, d_K = nullptr, d_V = nullptr, d_D = nullptr, d_M = nullptr;
  4128. size_t q_buf_offset = 0, k_buf_offset = 0, v_buf_offset = 0, d_buf_offset = 0, m_buf_offset = 0;
  4129. bool Q_uma = false, K_uma = false, V_uma = false, D_uma = false, M_uma = false;
  4130. if (ctx->device->uma) {
  4131. ggml_vk_host_get(ctx->device, q->data, d_Q, q_buf_offset);
  4132. ggml_vk_host_get(ctx->device, k->data, d_K, k_buf_offset);
  4133. ggml_vk_host_get(ctx->device, v->data, d_V, v_buf_offset);
  4134. ggml_vk_host_get(ctx->device, dst->data, d_D, d_buf_offset);
  4135. Q_uma = d_Q != nullptr;
  4136. K_uma = d_K != nullptr;
  4137. V_uma = d_V != nullptr;
  4138. D_uma = d_D != nullptr;
  4139. if (mask) {
  4140. ggml_vk_host_get(ctx->device, mask->data, d_M, m_buf_offset);
  4141. M_uma = d_M != nullptr;
  4142. }
  4143. }
  4144. ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  4145. ggml_backend_vk_buffer_context * q_buf_ctx = (ggml_backend_vk_buffer_context *)q->buffer->context;
  4146. ggml_backend_vk_buffer_context * k_buf_ctx = (ggml_backend_vk_buffer_context *)k->buffer->context;
  4147. ggml_backend_vk_buffer_context * v_buf_ctx = (ggml_backend_vk_buffer_context *)v->buffer->context;
  4148. if (!Q_uma) {
  4149. d_Q = q_buf_ctx->dev_buffer;
  4150. q_buf_offset = vk_tensor_offset(q) + q->view_offs;
  4151. }
  4152. if (!K_uma) {
  4153. d_K = k_buf_ctx->dev_buffer;
  4154. k_buf_offset = vk_tensor_offset(k) + k->view_offs;
  4155. }
  4156. if (!V_uma) {
  4157. d_V = v_buf_ctx->dev_buffer;
  4158. v_buf_offset = vk_tensor_offset(v) + v->view_offs;
  4159. }
  4160. if (!D_uma) {
  4161. d_D = d_buf_ctx->dev_buffer;
  4162. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  4163. }
  4164. if (!M_uma) {
  4165. d_M = d_Q;
  4166. m_buf_offset = q_buf_offset;
  4167. if (mask) {
  4168. ggml_backend_vk_buffer_context * m_buf_ctx = (ggml_backend_vk_buffer_context*)mask->buffer->context;
  4169. d_M = m_buf_ctx->dev_buffer;
  4170. m_buf_offset = vk_tensor_offset(mask) + mask->view_offs;
  4171. }
  4172. }
  4173. const vk_flash_attn_push_constants pc = { N, KV,
  4174. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  4175. (uint32_t)neq2, (uint32_t)neq3,
  4176. (uint32_t)nek2, (uint32_t)nek3,
  4177. (uint32_t)nev2, (uint32_t)nev3,
  4178. nem1,
  4179. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  4180. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  4181. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  4182. nbm1,
  4183. scale, max_bias, logit_softcap,
  4184. mask != nullptr, n_head_log2, m0, m1 };
  4185. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  4186. {
  4187. vk_subbuffer{d_Q, q_buf_offset, VK_WHOLE_SIZE},
  4188. vk_subbuffer{d_K, k_buf_offset, VK_WHOLE_SIZE},
  4189. vk_subbuffer{d_V, v_buf_offset, VK_WHOLE_SIZE},
  4190. vk_subbuffer{d_M, m_buf_offset, VK_WHOLE_SIZE},
  4191. vk_subbuffer{d_D, d_buf_offset, VK_WHOLE_SIZE},
  4192. },
  4193. sizeof(vk_flash_attn_push_constants), &pc, { (uint32_t)neq1, (uint32_t)neq2, (uint32_t)neq3 });
  4194. }
  4195. 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, ggml_tensor * dst, ggml_op op) {
  4196. switch (op) {
  4197. case GGML_OP_GET_ROWS:
  4198. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  4199. if (dst->type == GGML_TYPE_F16) {
  4200. return ctx->device->pipeline_get_rows[src0->type];
  4201. }
  4202. if (dst->type == GGML_TYPE_F32) {
  4203. return ctx->device->pipeline_get_rows_f32[src0->type];
  4204. }
  4205. return nullptr;
  4206. case GGML_OP_ACC:
  4207. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4208. return ctx->device->pipeline_acc_f32;
  4209. }
  4210. return nullptr;
  4211. case GGML_OP_ADD:
  4212. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4213. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_f32_norepeat : ctx->device->pipeline_add_f32;
  4214. }
  4215. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  4216. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_f16_f32_f16_norepeat : ctx->device->pipeline_add_f16_f32_f16;
  4217. }
  4218. return nullptr;
  4219. case GGML_OP_MUL:
  4220. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4221. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_f32_norepeat : ctx->device->pipeline_mul_f32;
  4222. }
  4223. return nullptr;
  4224. case GGML_OP_DIV:
  4225. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4226. return ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_f32_norepeat : ctx->device->pipeline_div_f32;
  4227. }
  4228. return nullptr;
  4229. case GGML_OP_CONCAT:
  4230. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4231. return ctx->device->pipeline_concat_f32;
  4232. }
  4233. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  4234. return ctx->device->pipeline_concat_f16;
  4235. }
  4236. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  4237. return ctx->device->pipeline_concat_i32;
  4238. }
  4239. return nullptr;
  4240. case GGML_OP_UPSCALE:
  4241. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4242. return ctx->device->pipeline_upscale_f32;
  4243. }
  4244. return nullptr;
  4245. case GGML_OP_SCALE:
  4246. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4247. return ctx->device->pipeline_scale_f32;
  4248. }
  4249. return nullptr;
  4250. case GGML_OP_SQR:
  4251. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4252. return ctx->device->pipeline_sqr_f32;
  4253. }
  4254. return nullptr;
  4255. case GGML_OP_SIN:
  4256. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4257. return ctx->device->pipeline_sin_f32;
  4258. }
  4259. return nullptr;
  4260. case GGML_OP_COS:
  4261. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4262. return ctx->device->pipeline_cos_f32;
  4263. }
  4264. return nullptr;
  4265. case GGML_OP_CLAMP:
  4266. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4267. return ctx->device->pipeline_clamp_f32;
  4268. }
  4269. return nullptr;
  4270. case GGML_OP_PAD:
  4271. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4272. return ctx->device->pipeline_pad_f32;
  4273. }
  4274. return nullptr;
  4275. case GGML_OP_REPEAT:
  4276. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  4277. return ctx->device->pipeline_repeat_f32;
  4278. }
  4279. return nullptr;
  4280. case GGML_OP_CPY:
  4281. case GGML_OP_CONT:
  4282. case GGML_OP_DUP:
  4283. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  4284. case GGML_OP_NORM:
  4285. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4286. return ctx->device->pipeline_norm_f32;
  4287. }
  4288. return nullptr;
  4289. case GGML_OP_GROUP_NORM:
  4290. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4291. return ctx->device->pipeline_group_norm_f32;
  4292. }
  4293. return nullptr;
  4294. case GGML_OP_RMS_NORM:
  4295. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4296. return ctx->device->pipeline_rms_norm_f32;
  4297. }
  4298. return nullptr;
  4299. case GGML_OP_UNARY:
  4300. switch (ggml_get_unary_op(dst)) {
  4301. case GGML_UNARY_OP_SILU:
  4302. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4303. return ctx->device->pipeline_silu_f32;
  4304. }
  4305. break;
  4306. case GGML_UNARY_OP_GELU:
  4307. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4308. return ctx->device->pipeline_gelu_f32;
  4309. }
  4310. break;
  4311. case GGML_UNARY_OP_GELU_QUICK:
  4312. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4313. return ctx->device->pipeline_gelu_quick_f32;
  4314. }
  4315. break;
  4316. case GGML_UNARY_OP_RELU:
  4317. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4318. return ctx->device->pipeline_relu_f32;
  4319. }
  4320. break;
  4321. case GGML_UNARY_OP_TANH:
  4322. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4323. return ctx->device->pipeline_tanh_f32;
  4324. }
  4325. break;
  4326. default:
  4327. break;
  4328. }
  4329. return nullptr;
  4330. case GGML_OP_DIAG_MASK_INF:
  4331. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4332. return ctx->device->pipeline_diag_mask_inf_f32;
  4333. }
  4334. return nullptr;
  4335. case GGML_OP_SOFT_MAX:
  4336. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  4337. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  4338. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  4339. }
  4340. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  4341. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  4342. }
  4343. return nullptr;
  4344. case GGML_OP_ROPE:
  4345. {
  4346. const int mode = ((const int32_t *) dst->op_params)[2];
  4347. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  4348. if (is_neox) {
  4349. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4350. return ctx->device->pipeline_rope_neox_f32;
  4351. }
  4352. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  4353. return ctx->device->pipeline_rope_neox_f16;
  4354. }
  4355. } else {
  4356. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4357. return ctx->device->pipeline_rope_norm_f32;
  4358. }
  4359. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  4360. return ctx->device->pipeline_rope_norm_f16;
  4361. }
  4362. }
  4363. return nullptr;
  4364. }
  4365. case GGML_OP_ARGSORT:
  4366. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  4367. return ctx->device->pipeline_argsort_f32;
  4368. }
  4369. return nullptr;
  4370. case GGML_OP_SUM_ROWS:
  4371. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4372. return ctx->device->pipeline_sum_rows_f32;
  4373. }
  4374. return nullptr;
  4375. case GGML_OP_IM2COL:
  4376. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4377. return ctx->device->pipeline_im2col_f32;
  4378. }
  4379. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  4380. return ctx->device->pipeline_im2col_f32_f16;
  4381. }
  4382. return nullptr;
  4383. case GGML_OP_TIMESTEP_EMBEDDING:
  4384. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4385. return ctx->device->pipeline_timestep_embedding_f32;
  4386. }
  4387. return nullptr;
  4388. case GGML_OP_POOL_2D:
  4389. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4390. return ctx->device->pipeline_pool2d_f32;
  4391. }
  4392. return nullptr;
  4393. case GGML_OP_RWKV_WKV6:
  4394. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4395. return ctx->device->pipeline_rwkv_wkv6_f32;
  4396. }
  4397. return nullptr;
  4398. case GGML_OP_LEAKY_RELU:
  4399. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  4400. return ctx->device->pipeline_leaky_relu_f32;
  4401. }
  4402. return nullptr;
  4403. default:
  4404. return nullptr;
  4405. }
  4406. GGML_UNUSED(src2);
  4407. }
  4408. static bool ggml_vk_op_supports_incontiguous(ggml_op op) {
  4409. switch (op) {
  4410. case GGML_OP_CPY:
  4411. case GGML_OP_GET_ROWS:
  4412. case GGML_OP_ADD:
  4413. case GGML_OP_MUL:
  4414. case GGML_OP_DIV:
  4415. case GGML_OP_CONCAT:
  4416. case GGML_OP_UPSCALE:
  4417. case GGML_OP_SQR:
  4418. case GGML_OP_SIN:
  4419. case GGML_OP_COS:
  4420. case GGML_OP_CLAMP:
  4421. case GGML_OP_PAD:
  4422. case GGML_OP_REPEAT:
  4423. return true;
  4424. default:
  4425. return false;
  4426. }
  4427. }
  4428. static uint32_t get_misalign_bytes(ggml_backend_vk_context * ctx, const ggml_tensor * t)
  4429. {
  4430. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  4431. }
  4432. 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, ggml_tensor * dst) {
  4433. GGML_UNUSED(p);
  4434. GGML_UNUSED(src0);
  4435. GGML_UNUSED(src1);
  4436. GGML_UNUSED(src2);
  4437. GGML_UNUSED(dst);
  4438. static_assert(!std::is_const<T>::value, "unexpected type");
  4439. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  4440. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  4441. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  4442. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  4443. }
  4444. 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, ggml_tensor * dst) {
  4445. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  4446. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  4447. p.misalign_offsets = (a_offset << 16) | d_offset;
  4448. GGML_UNUSED(src1);
  4449. GGML_UNUSED(src2);
  4450. }
  4451. 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, ggml_tensor * dst) {
  4452. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  4453. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  4454. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  4455. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  4456. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  4457. GGML_UNUSED(src2);
  4458. }
  4459. 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, ggml_tensor * dst) {
  4460. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  4461. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  4462. p.a_offset = a_offset;
  4463. p.d_offset = d_offset;
  4464. GGML_UNUSED(src1);
  4465. GGML_UNUSED(src2);
  4466. }
  4467. template<typename PC>
  4468. 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, ggml_tensor * dst, ggml_op op, PC&& pc, bool dryrun = false) {
  4469. 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];
  4470. if (src1 != nullptr) {
  4471. 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];
  4472. }
  4473. if (src2 != nullptr) {
  4474. 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];
  4475. }
  4476. 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];
  4477. std::cerr << "), " << ggml_op_name(op) << ", " << (dryrun ? "dryrun" : "") << ")");
  4478. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  4479. GGML_ASSERT(ggml_vk_op_supports_incontiguous(op) || ggml_vk_dim01_contiguous(src0)); // NOLINT
  4480. GGML_ASSERT(dst->buffer != nullptr);
  4481. const uint64_t ne00 = src0->ne[0];
  4482. const uint64_t ne01 = src0->ne[1];
  4483. const uint64_t ne02 = src0->ne[2];
  4484. const uint64_t ne03 = src0->ne[3];
  4485. const uint64_t ne0 = ne00 * ne01;
  4486. const bool use_src1 = src1 != nullptr;
  4487. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  4488. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  4489. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  4490. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  4491. const uint64_t ne1 = ne10 * ne11;
  4492. // const uint64_t nb10 = use_src1 ? src1->nb[0] : 0;
  4493. const bool use_src2 = src2 != nullptr;
  4494. const uint64_t ne20 = use_src2 ? src2->ne[0] : 0;
  4495. const uint64_t ne21 = use_src2 ? src2->ne[1] : 0;
  4496. const uint64_t ne22 = use_src2 ? src2->ne[2] : 0;
  4497. const uint64_t ne23 = use_src2 ? src2->ne[3] : 0;
  4498. const uint64_t ne2 = ne20 * ne21;
  4499. const uint64_t ned0 = dst->ne[0];
  4500. const uint64_t ned1 = dst->ne[1];
  4501. const uint64_t ned2 = dst->ne[2];
  4502. const uint64_t ned3 = dst->ne[3];
  4503. const uint64_t ned = ned0 * ned1;
  4504. init_pushconst_fastdiv(pc);
  4505. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  4506. if (pipeline == nullptr) {
  4507. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  4508. if (src1 != nullptr) {
  4509. std::cerr << " and " << ggml_type_name(src1->type);
  4510. }
  4511. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  4512. GGML_ABORT("fatal error");
  4513. }
  4514. if (dryrun) {
  4515. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  4516. return;
  4517. }
  4518. const bool op_supports_incontiguous = ggml_vk_op_supports_incontiguous(op);
  4519. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  4520. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  4521. ggml_backend_vk_buffer_context * src1_buf_ctx = use_src1 ? (ggml_backend_vk_buffer_context *)src1->buffer->context : nullptr;
  4522. ggml_backend_vk_buffer_context * src2_buf_ctx = use_src2 ? (ggml_backend_vk_buffer_context *)src2->buffer->context : nullptr;
  4523. vk_buffer d_X = nullptr;
  4524. size_t x_buf_offset = 0;
  4525. vk_buffer d_Y = nullptr;
  4526. size_t y_buf_offset = 0;
  4527. vk_buffer d_Z = nullptr;
  4528. size_t z_buf_offset = 0;
  4529. bool src0_uma = false;
  4530. bool src1_uma = false;
  4531. bool src2_uma = false;
  4532. if (ctx->device->uma) {
  4533. ggml_vk_host_get(ctx->device, src0->data, d_X, x_buf_offset);
  4534. src0_uma = d_X != nullptr;
  4535. if (use_src1) {
  4536. ggml_vk_host_get(ctx->device, src1->data, d_Y, y_buf_offset);
  4537. src1_uma = d_Y != nullptr;
  4538. }
  4539. if (use_src2) {
  4540. ggml_vk_host_get(ctx->device, src2->data, d_Z, z_buf_offset);
  4541. src2_uma = d_Z != nullptr;
  4542. }
  4543. }
  4544. uint64_t x_sz = ggml_type_size(src0->type)/ggml_blck_size(src0->type) * ne0;
  4545. uint64_t y_sz = use_src1 ? ggml_type_size(src1->type) * ne1 : 0;
  4546. uint64_t z_sz = use_src2 ? ggml_type_size(src2->type) * ne2 : 0;
  4547. uint64_t d_sz = ggml_type_size(dst->type) * ned;
  4548. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  4549. // Workaround for tiny tensor inputs on ROPE
  4550. if (op == GGML_OP_ROPE && use_src1 && y_sz > d_D->size) {
  4551. y_sz = VK_WHOLE_SIZE;
  4552. }
  4553. GGML_ASSERT(d_D != nullptr);
  4554. uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  4555. if(!src0_uma) {
  4556. d_X = src0_buf_ctx->dev_buffer;
  4557. x_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  4558. GGML_ASSERT(d_X != nullptr);
  4559. }
  4560. if (use_src1 && !src1_uma) {
  4561. d_Y = src1_buf_ctx->dev_buffer;
  4562. y_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  4563. GGML_ASSERT(d_Y != nullptr);
  4564. }
  4565. if (use_src2 && !src2_uma) {
  4566. d_Z = src2_buf_ctx->dev_buffer;
  4567. z_buf_offset = vk_tensor_offset(src2) + src2->view_offs;
  4568. GGML_ASSERT(d_Z != nullptr);
  4569. }
  4570. // Compute misalignment offset for descriptors and store it in in push constants, then align the descriptor offsets.
  4571. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, dst);
  4572. x_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  4573. y_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  4574. z_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  4575. d_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  4576. if (op_supports_incontiguous) {
  4577. x_sz = ggml_nbytes(src0);
  4578. y_sz = use_src1 ? ggml_nbytes(src1) : 0;
  4579. z_sz = use_src2 ? ggml_nbytes(src2) : 0;
  4580. d_sz = ggml_nbytes(dst);
  4581. if (x_buf_offset + x_sz >= d_X->size) {
  4582. x_sz = VK_WHOLE_SIZE;
  4583. }
  4584. if (use_src1 && y_buf_offset + y_sz >= d_Y->size) {
  4585. y_sz = VK_WHOLE_SIZE;
  4586. }
  4587. if (use_src2 && z_buf_offset + z_sz >= d_Z->size) {
  4588. z_sz = VK_WHOLE_SIZE;
  4589. }
  4590. if (d_buf_offset + d_sz >= d_D->size) {
  4591. d_sz = VK_WHOLE_SIZE;
  4592. }
  4593. }
  4594. std::array<uint32_t, 3> elements;
  4595. // Single call if dimension 2 is contiguous
  4596. GGML_ASSERT(op_supports_incontiguous || (ggml_is_contiguous(src0) && (src1 == nullptr || ggml_is_contiguous(src1))));
  4597. switch (op) {
  4598. case GGML_OP_NORM:
  4599. case GGML_OP_RMS_NORM:
  4600. case GGML_OP_SOFT_MAX:
  4601. case GGML_OP_SUM_ROWS:
  4602. {
  4603. const uint32_t nr = ggml_nrows(src0);
  4604. if (nr > 262144) {
  4605. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  4606. } else if (nr > 512) {
  4607. elements = { 512, CEIL_DIV(nr, 512), 1 };
  4608. } else {
  4609. elements = { nr, 1, 1 };
  4610. }
  4611. } break;
  4612. case GGML_OP_GROUP_NORM:
  4613. {
  4614. const uint32_t num_groups = dst->op_params[0];
  4615. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  4616. } break;
  4617. case GGML_OP_DIAG_MASK_INF:
  4618. case GGML_OP_ROPE:
  4619. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  4620. break;
  4621. case GGML_OP_GET_ROWS:
  4622. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  4623. break;
  4624. case GGML_OP_ARGSORT:
  4625. elements = { (uint32_t)ne00, (uint32_t)ggml_nrows(src0), 1 };
  4626. break;
  4627. case GGML_OP_IM2COL:
  4628. {
  4629. const bool is_2D = dst->op_params[6] == 1;
  4630. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  4631. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  4632. const uint32_t KW = src0->ne[0];
  4633. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  4634. const uint32_t OW = dst->ne[1];
  4635. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  4636. elements = { OW * KW * KH, OH, batch * IC };
  4637. } break;
  4638. case GGML_OP_TIMESTEP_EMBEDDING:
  4639. {
  4640. const uint32_t dim = dst->op_params[0];
  4641. uint32_t half_ceil = (dim + 1) / 2;
  4642. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  4643. } break;
  4644. case GGML_OP_POOL_2D:
  4645. {
  4646. const uint32_t N = dst->ne[3];
  4647. const uint32_t OC = dst->ne[2];
  4648. const uint32_t OH = dst->ne[1];
  4649. const uint32_t OW = dst->ne[0];
  4650. elements = { N * OC * OH * OW, 1, 1};
  4651. } break;
  4652. case GGML_OP_ADD:
  4653. case GGML_OP_DIV:
  4654. case GGML_OP_MUL:
  4655. case GGML_OP_SCALE:
  4656. case GGML_OP_SQR:
  4657. case GGML_OP_SIN:
  4658. case GGML_OP_COS:
  4659. case GGML_OP_CLAMP:
  4660. case GGML_OP_PAD:
  4661. case GGML_OP_REPEAT:
  4662. case GGML_OP_CPY:
  4663. case GGML_OP_CONCAT:
  4664. case GGML_OP_UPSCALE:
  4665. case GGML_OP_UNARY:
  4666. {
  4667. const uint32_t ne = ggml_nelements(dst);
  4668. if (ne > 262144) {
  4669. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  4670. } else if (ne > 512) {
  4671. elements = { 512, CEIL_DIV(ne, 512), 1 };
  4672. } else {
  4673. elements = { ne, 1, 1 };
  4674. }
  4675. } break;
  4676. default:
  4677. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  4678. break;
  4679. }
  4680. if (!op_supports_incontiguous) {
  4681. if (x_sz != VK_WHOLE_SIZE) {
  4682. x_sz *= ne02 * ne03;
  4683. }
  4684. if (use_src1 && y_sz != VK_WHOLE_SIZE) {
  4685. y_sz *= ne12 * ne13;
  4686. }
  4687. if (use_src2 && z_sz != VK_WHOLE_SIZE) {
  4688. z_sz *= ne22 * ne23;
  4689. }
  4690. if (d_sz != VK_WHOLE_SIZE) {
  4691. d_sz *= ned2 * ned3;
  4692. }
  4693. }
  4694. if (op == GGML_OP_SOFT_MAX) {
  4695. // Empty src1 is possible in soft_max, but the shader needs a buffer
  4696. vk_subbuffer subbuf_y;
  4697. if (use_src1) {
  4698. subbuf_y = { d_Y, y_buf_offset, y_sz };
  4699. } else {
  4700. subbuf_y = { d_X, 0, x_sz };
  4701. }
  4702. ggml_vk_sync_buffers(subctx);
  4703. 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 } }, sizeof(PC), &pc, elements);
  4704. } else if (op == GGML_OP_ROPE) {
  4705. // Empty src2 is possible in rope, but the shader needs a buffer
  4706. vk_subbuffer subbuf_z;
  4707. if (use_src2) {
  4708. subbuf_z = { d_Z, z_buf_offset, z_sz };
  4709. } else {
  4710. subbuf_z = { d_X, 0, x_sz };
  4711. }
  4712. ggml_vk_sync_buffers(subctx);
  4713. 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 } }, sizeof(PC), &pc, elements);
  4714. } else if (op == GGML_OP_IM2COL) {
  4715. // im2col uses only src1 and dst buffers
  4716. ggml_vk_sync_buffers(subctx);
  4717. 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 } }, sizeof(PC), &pc, elements);
  4718. } else if (use_src2) {
  4719. ggml_vk_sync_buffers(subctx);
  4720. 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 } }, sizeof(PC), &pc, elements);
  4721. } else if (use_src1) {
  4722. ggml_vk_sync_buffers(subctx);
  4723. 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 } }, sizeof(PC), &pc, elements);
  4724. } else {
  4725. ggml_vk_sync_buffers(subctx);
  4726. 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 } }, sizeof(PC), &pc, elements);
  4727. }
  4728. }
  4729. 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) {
  4730. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4731. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4732. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4733. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_GET_ROWS, {
  4734. (uint32_t)ggml_nelements(src0),
  4735. (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,
  4736. (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,
  4737. (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,
  4738. 0,
  4739. 0.0f, 0.0f, 0,
  4740. }, dryrun);
  4741. }
  4742. 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) {
  4743. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4744. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4745. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4746. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  4747. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  4748. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  4749. int offset = dst->op_params[3] / 4; // offset in bytes
  4750. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ACC, {
  4751. (uint32_t)ggml_nelements(src0),
  4752. (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,
  4753. (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,
  4754. (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,
  4755. 0,
  4756. 0.0f, 0.0f, offset,
  4757. }, dryrun);
  4758. }
  4759. 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) {
  4760. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4761. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4762. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4763. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ADD, {
  4764. (uint32_t)ggml_nelements(src0),
  4765. (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,
  4766. (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,
  4767. (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,
  4768. 0,
  4769. 0.0f, 0.0f, 0,
  4770. }, dryrun);
  4771. }
  4772. 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) {
  4773. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4774. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4775. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4776. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_MUL, {
  4777. (uint32_t)ggml_nelements(src0),
  4778. (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,
  4779. (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,
  4780. (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,
  4781. 0,
  4782. 0.0f, 0.0f, 0,
  4783. }, dryrun);
  4784. }
  4785. 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) {
  4786. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4787. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4788. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4789. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_DIV, {
  4790. (uint32_t)ggml_nelements(src0),
  4791. (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,
  4792. (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,
  4793. (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,
  4794. 0,
  4795. 0.0f, 0.0f, 0,
  4796. }, dryrun);
  4797. }
  4798. static void ggml_vk_op_f32_rwkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, const vk_op_rwkv_wkv6_push_constants&& pc, bool dryrun = false) {
  4799. const ggml_tensor * k = dst->src[0];
  4800. const ggml_tensor * v = dst->src[1];
  4801. const ggml_tensor * r = dst->src[2];
  4802. const ggml_tensor * tf = dst->src[3];
  4803. const ggml_tensor * td = dst->src[4];
  4804. const ggml_tensor * state = dst->src[5];
  4805. GGML_ASSERT(!ggml_is_quantized(k->type));
  4806. GGML_ASSERT(!ggml_is_quantized(v->type));
  4807. GGML_ASSERT(!ggml_is_quantized(r->type));
  4808. GGML_ASSERT(!ggml_is_quantized(tf->type));
  4809. GGML_ASSERT(!ggml_is_quantized(td->type));
  4810. GGML_ASSERT(!ggml_is_quantized(state->type));
  4811. GGML_ASSERT(dst->buffer != nullptr);
  4812. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, k, v, r, dst, GGML_OP_RWKV_WKV6);
  4813. GGML_ASSERT(pipeline != nullptr);
  4814. if (dryrun) {
  4815. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  4816. return;
  4817. }
  4818. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  4819. ggml_backend_vk_buffer_context * k_buf_ctx = (ggml_backend_vk_buffer_context *)k->buffer->context;
  4820. ggml_backend_vk_buffer_context * v_buf_ctx = (ggml_backend_vk_buffer_context *)v->buffer->context;
  4821. ggml_backend_vk_buffer_context * r_buf_ctx = (ggml_backend_vk_buffer_context *)r->buffer->context;
  4822. ggml_backend_vk_buffer_context * tf_buf_ctx = (ggml_backend_vk_buffer_context *)tf->buffer->context;
  4823. ggml_backend_vk_buffer_context * td_buf_ctx = (ggml_backend_vk_buffer_context *)td->buffer->context;
  4824. ggml_backend_vk_buffer_context * state_buf_ctx = (ggml_backend_vk_buffer_context *)state->buffer->context;
  4825. ggml_vk_sync_buffers(subctx);
  4826. vk_buffer d_D = nullptr, d_K = nullptr, d_V = nullptr, d_R = nullptr, d_TF = nullptr, d_TD = nullptr, d_State = nullptr;
  4827. size_t k_offset = 0, v_offset = 0, r_offset = 0, tf_offset = 0, td_offset = 0, state_offset = 0, dst_offset = 0;
  4828. bool K_uma = false, V_uma = false, R_uma = false, TF_uma = false, TD_uma = false, STATE_uma = false, DST_uma = false;
  4829. if (ctx->device->uma) {
  4830. ggml_vk_host_get(ctx->device, k->data, d_K, k_offset);
  4831. ggml_vk_host_get(ctx->device, v->data, d_V, v_offset);
  4832. ggml_vk_host_get(ctx->device, r->data, d_R, r_offset);
  4833. ggml_vk_host_get(ctx->device, tf->data, d_TF, tf_offset);
  4834. ggml_vk_host_get(ctx->device, td->data, d_TD, td_offset);
  4835. ggml_vk_host_get(ctx->device, state->data, d_State, state_offset);
  4836. ggml_vk_host_get(ctx->device, dst->data, d_D, dst_offset);
  4837. K_uma = d_K != nullptr;
  4838. V_uma = d_V != nullptr;
  4839. R_uma = d_R != nullptr;
  4840. TF_uma = d_TF != nullptr;
  4841. TD_uma = d_TD != nullptr;
  4842. STATE_uma = d_State != nullptr;
  4843. DST_uma = d_D != nullptr;
  4844. }
  4845. if (!K_uma) {
  4846. d_K = k_buf_ctx->dev_buffer;
  4847. k_offset = vk_tensor_offset(k) + k->view_offs;
  4848. }
  4849. if (!V_uma) {
  4850. d_V = v_buf_ctx->dev_buffer;
  4851. v_offset = vk_tensor_offset(v) + v->view_offs;
  4852. }
  4853. if (!R_uma) {
  4854. d_R = r_buf_ctx->dev_buffer;
  4855. r_offset = vk_tensor_offset(r) + r->view_offs;
  4856. }
  4857. if (!TF_uma) {
  4858. d_TF = tf_buf_ctx->dev_buffer;
  4859. tf_offset = vk_tensor_offset(tf) + tf->view_offs;
  4860. }
  4861. if (!TD_uma) {
  4862. d_TD = td_buf_ctx->dev_buffer;
  4863. td_offset = vk_tensor_offset(td) + td->view_offs;
  4864. }
  4865. if (!STATE_uma) {
  4866. d_State = state_buf_ctx->dev_buffer;
  4867. state_offset = vk_tensor_offset(state) + state->view_offs;
  4868. }
  4869. if (!DST_uma) {
  4870. d_D = dst_buf_ctx->dev_buffer;
  4871. dst_offset = vk_tensor_offset(dst) + dst->view_offs;
  4872. }
  4873. const uint64_t k_size = ggml_nbytes(k);
  4874. const uint64_t v_size = ggml_nbytes(v);
  4875. const uint64_t r_size = ggml_nbytes(r);
  4876. const uint64_t tf_size = ggml_nbytes(tf);
  4877. const uint64_t td_size = ggml_nbytes(td);
  4878. const uint64_t state_size = ggml_nbytes(state);
  4879. const uint64_t dst_size = ggml_nbytes(dst);
  4880. std::array<uint32_t, 3> elements = {
  4881. (uint32_t)(pc.B * pc.H),
  4882. 1,
  4883. 1
  4884. };
  4885. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  4886. vk_subbuffer{ d_K, k_offset, k_size },
  4887. vk_subbuffer{ d_V, v_offset, v_size },
  4888. vk_subbuffer{ d_R, r_offset, r_size },
  4889. vk_subbuffer{ d_TF, tf_offset, tf_size },
  4890. vk_subbuffer{ d_TD, td_offset, td_size },
  4891. vk_subbuffer{ d_State, state_offset, state_size },
  4892. vk_subbuffer{ d_D, dst_offset, dst_size }
  4893. }, sizeof(vk_op_rwkv_wkv6_push_constants), &pc, elements);
  4894. }
  4895. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  4896. const size_t seq_length = dst->src[0]->ne[2];
  4897. const size_t n_embed = dst->ne[0];
  4898. const size_t n_heads = dst->src[0]->ne[1];
  4899. const size_t n_seqs = dst->src[5]->ne[1];
  4900. ggml_vk_op_f32_rwkv6(
  4901. ctx, subctx, dst,
  4902. {
  4903. (uint32_t)n_seqs,
  4904. (uint32_t)seq_length,
  4905. (uint32_t)n_embed,
  4906. (uint32_t)n_heads,
  4907. },
  4908. dryrun
  4909. );
  4910. }
  4911. 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) {
  4912. int * op_params = (int *)dst->op_params;
  4913. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4914. const uint32_t src1_type_size = ggml_type_size(src1->type);
  4915. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4916. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONCAT, {
  4917. (uint32_t)ggml_nelements(dst),
  4918. (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,
  4919. (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,
  4920. (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,
  4921. 0,
  4922. 0.0f, 0.0f, op_params[0],
  4923. }, dryrun);
  4924. }
  4925. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4926. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4927. const float sf0 = (float)dst->ne[0] / src0->ne[0];
  4928. const float sf1 = (float)dst->ne[1] / src0->ne[1];
  4929. const float sf2 = (float)dst->ne[2] / src0->ne[2];
  4930. const float sf3 = (float)dst->ne[3] / src0->ne[3];
  4931. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  4932. (uint32_t)ggml_nelements(dst), 0, 0,
  4933. (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,
  4934. (uint32_t)dst->ne[0], (uint32_t)dst->ne[1], (uint32_t)dst->ne[2],(uint32_t)dst->ne[3],
  4935. sf0, sf1, sf2, sf3,
  4936. }, dryrun);
  4937. }
  4938. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4939. float * op_params = (float *)dst->op_params;
  4940. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4941. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4942. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SCALE, {
  4943. (uint32_t)ggml_nelements(src0),
  4944. (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,
  4945. (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,
  4946. 0,
  4947. op_params[0], 0.0f,
  4948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4949. }, dryrun);
  4950. }
  4951. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4952. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4953. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4954. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SQR, {
  4955. (uint32_t)ggml_nelements(src0),
  4956. (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,
  4957. (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,
  4958. 0,
  4959. 0.0f, 0.0f,
  4960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4961. }, dryrun);
  4962. }
  4963. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4964. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4965. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4966. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SIN, {
  4967. (uint32_t)ggml_nelements(src0),
  4968. (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,
  4969. (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,
  4970. 0,
  4971. 0.0f, 0.0f,
  4972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4973. }, dryrun);
  4974. }
  4975. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4976. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4977. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4978. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_COS, {
  4979. (uint32_t)ggml_nelements(src0),
  4980. (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,
  4981. (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,
  4982. 0,
  4983. 0.0f, 0.0f,
  4984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4985. }, dryrun);
  4986. }
  4987. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  4988. float * op_params = (float *)dst->op_params;
  4989. const uint32_t src0_type_size = ggml_type_size(src0->type);
  4990. const uint32_t dst_type_size = ggml_type_size(dst->type);
  4991. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CLAMP, {
  4992. (uint32_t)ggml_nelements(src0),
  4993. (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,
  4994. (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,
  4995. 0,
  4996. op_params[0], op_params[1],
  4997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4998. }, dryrun);
  4999. }
  5000. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5001. const uint32_t src0_type_size = ggml_type_size(src0->type);
  5002. const uint32_t dst_type_size = ggml_type_size(dst->type);
  5003. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_PAD, {
  5004. (uint32_t)ggml_nelements(dst),
  5005. (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,
  5006. (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,
  5007. 0,
  5008. 0.0f, 0.0f,
  5009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5010. }, dryrun);
  5011. }
  5012. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5013. const uint32_t src0_type_size = ggml_type_size(src0->type);
  5014. const uint32_t dst_type_size = ggml_type_size(dst->type);
  5015. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_REPEAT, {
  5016. (uint32_t)ggml_nelements(dst),
  5017. (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,
  5018. (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,
  5019. 0,
  5020. 0.0f, 0.0f,
  5021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5022. }, dryrun);
  5023. }
  5024. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5025. const uint32_t src0_type_size = ggml_type_size(src0->type);
  5026. const uint32_t dst_type_size = ggml_type_size(dst->type);
  5027. ggml_vk_op_f32<vk_op_unary_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CPY, {
  5028. (uint32_t)ggml_nelements(src0),
  5029. (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,
  5030. (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,
  5031. 0,
  5032. 0.0f, 0.0f,
  5033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5034. }, dryrun);
  5035. }
  5036. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5037. float * op_params = (float *)dst->op_params;
  5038. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f }, dryrun);
  5039. }
  5040. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5041. const int * int_op_params = (const int *)dst->op_params;
  5042. const float * float_op_params = (const float *)dst->op_params;
  5043. const uint32_t num_groups = int_op_params[0];
  5044. const float eps = float_op_params[1];
  5045. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  5046. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_GROUP_NORM, { group_size, 0, eps, 0.0f }, dryrun);
  5047. }
  5048. static void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5049. float * op_params = (float *)dst->op_params;
  5050. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_RMS_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f }, dryrun);
  5051. }
  5052. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5053. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_UNARY, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f }, dryrun);
  5054. }
  5055. 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) {
  5056. int32_t * op_params = (int32_t *)dst->op_params;
  5057. ggml_vk_op_f32<vk_op_diag_mask_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_DIAG_MASK_INF, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0] }, dryrun);
  5058. }
  5059. static void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  5060. float * op_params = (float *)dst->op_params;
  5061. float scale = op_params[0];
  5062. float max_bias = op_params[1];
  5063. const uint32_t ncols = (uint32_t)src0->ne[0];
  5064. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  5065. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  5066. const uint32_t n_head_kv = nrows_x/nrows_y;
  5067. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  5068. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  5069. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  5070. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_SOFT_MAX, {
  5071. ncols,
  5072. src1 != nullptr ? nrows_y : (uint32_t)0,
  5073. scale, max_bias,
  5074. m0, m1,
  5075. n_head_log2,
  5076. nrows_x,
  5077. }, dryrun);
  5078. }
  5079. static void ggml_vk_rope(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) {
  5080. const int n_dims = ((int32_t *) dst->op_params)[1];
  5081. // const int mode = ((int32_t *) dst->op_params)[2];
  5082. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  5083. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  5084. const float freq_base = ((float *) dst->op_params)[5];
  5085. const float freq_scale = ((float *) dst->op_params)[6];
  5086. const float ext_factor = ((float *) dst->op_params)[7];
  5087. const float attn_factor = ((float *) dst->op_params)[8];
  5088. const float beta_fast = ((float *) dst->op_params)[9];
  5089. const float beta_slow = ((float *) dst->op_params)[10];
  5090. float corr_dims[2];
  5091. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  5092. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  5093. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, dst, GGML_OP_ROPE, {
  5094. (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  5095. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  5096. src2 != nullptr,
  5097. }, dryrun);
  5098. }
  5099. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5100. int32_t * op_params = (int32_t *)dst->op_params;
  5101. uint32_t ncols = src0->ne[0];
  5102. uint32_t ncols_pad = 1;
  5103. while (ncols_pad < ncols) {
  5104. ncols_pad *= 2;
  5105. }
  5106. GGML_ASSERT(ncols_pad <= 1024);
  5107. ggml_vk_op_f32<vk_op_argsort_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_ARGSORT, {
  5108. ncols,
  5109. ncols_pad,
  5110. op_params[0],
  5111. }, dryrun);
  5112. }
  5113. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5114. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, { (uint32_t)src0->ne[0], 0, 0.0f, 0.0f }, dryrun);
  5115. }
  5116. 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) {
  5117. const int32_t s0 = dst->op_params[0];
  5118. const int32_t s1 = dst->op_params[1];
  5119. const int32_t p0 = dst->op_params[2];
  5120. const int32_t p1 = dst->op_params[3];
  5121. const int32_t d0 = dst->op_params[4];
  5122. const int32_t d1 = dst->op_params[5];
  5123. const bool is_2D = dst->op_params[6] == 1;
  5124. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  5125. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  5126. const uint32_t IW = src1->ne[0];
  5127. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  5128. const uint32_t KW = src0->ne[0];
  5129. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  5130. const uint32_t OW = dst->ne[1];
  5131. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  5132. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  5133. const uint32_t pelements = OW * KW * KH;
  5134. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_IM2COL, {
  5135. batch_offset, offset_delta,
  5136. IC, IW, IH, OW, OH, KW, KH,
  5137. pelements,
  5138. IC * KH * KW,
  5139. s0, s1, p0, p1, d0, d1,
  5140. }, dryrun);
  5141. }
  5142. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5143. const uint32_t dim = dst->op_params[0];
  5144. const uint32_t max_period = dst->op_params[1];
  5145. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  5146. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  5147. nb1, dim, max_period,
  5148. }, dryrun);
  5149. }
  5150. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5151. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  5152. const int32_t k1 = dst->op_params[1];
  5153. const int32_t k0 = dst->op_params[2];
  5154. const int32_t s1 = dst->op_params[3];
  5155. const int32_t s0 = dst->op_params[4];
  5156. const int32_t p1 = dst->op_params[5];
  5157. const int32_t p0 = dst->op_params[6];
  5158. const uint32_t IH = src0->ne[1];
  5159. const uint32_t IW = src0->ne[0];
  5160. const uint32_t N = dst->ne[3];
  5161. const uint32_t OC = dst->ne[2];
  5162. const uint32_t OH = dst->ne[1];
  5163. const uint32_t OW = dst->ne[0];
  5164. const uint32_t parallel_elements = N * OC * OH * OW;
  5165. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  5166. IW, IH, OW, OH, OC,
  5167. parallel_elements,
  5168. op,
  5169. k0, k1, s0, s1, p0, p1,
  5170. }, dryrun);
  5171. }
  5172. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  5173. const float * op_params = (const float *)dst->op_params;
  5174. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_LEAKY_RELU, { (uint32_t)ggml_nelements(src0), 0, op_params[0], 0.0f }, dryrun);
  5175. }
  5176. #ifdef GGML_VULKAN_RUN_TESTS
  5177. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  5178. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  5179. return;
  5180. }
  5181. i0 = std::max(i0, 5);
  5182. i1 = std::max(i1, 5);
  5183. i2 = std::max(i2, 0);
  5184. fprintf(stderr, " ");
  5185. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  5186. fprintf(stderr, "%7d ", idx1);
  5187. }
  5188. fprintf(stderr, "\n");
  5189. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  5190. fprintf(stderr, "%7d: ", idx0);
  5191. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  5192. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  5193. float val;
  5194. if (type == GGML_TYPE_F32) {
  5195. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  5196. } else if (type == GGML_TYPE_F16) {
  5197. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  5198. } else {
  5199. GGML_ABORT("fatal error");
  5200. }
  5201. fprintf(stderr, "% 7.2f ", val);
  5202. } else {
  5203. fprintf(stderr, " ");
  5204. }
  5205. }
  5206. fprintf(stderr, "\n");
  5207. }
  5208. }
  5209. template <typename X_TYPE, typename Y_TYPE>
  5210. 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) {
  5211. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  5212. const size_t x_ne = m * k * batch;
  5213. const size_t y_ne = k * n * batch;
  5214. const size_t d_ne = m * n * batch;
  5215. vk_pipeline p;
  5216. std::string shname;
  5217. if (shader_size == 0) {
  5218. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5219. p = ctx->device->pipeline_matmul_f32->a_s;
  5220. shname = "F32_ALIGNED_S";
  5221. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5222. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  5223. shname = "F32_F16_ALIGNED_S";
  5224. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5225. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  5226. shname = "F16_F32_ALIGNED_S";
  5227. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5228. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  5229. shname = "F16_ALIGNED_S";
  5230. } else {
  5231. GGML_ABORT("fatal error");
  5232. }
  5233. } else if (shader_size == 1) {
  5234. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5235. p = ctx->device->pipeline_matmul_f32->a_m;
  5236. shname = "F32_ALIGNED_M";
  5237. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5238. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  5239. shname = "F32_F16_ALIGNED_M";
  5240. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5241. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  5242. shname = "F16_F32_ALIGNED_M";
  5243. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5244. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  5245. shname = "F16_ALIGNED_M";
  5246. } else {
  5247. GGML_ABORT("fatal error");
  5248. }
  5249. } else if (shader_size == 2) {
  5250. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5251. p = ctx->device->pipeline_matmul_f32->a_l;
  5252. shname = "F32_ALIGNED_L";
  5253. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5254. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  5255. shname = "F32_F16_ALIGNED_L";
  5256. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5257. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  5258. shname = "F16_F32_ALIGNED_L";
  5259. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5260. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  5261. shname = "F16_ALIGNED_L";
  5262. } else {
  5263. GGML_ABORT("fatal error");
  5264. }
  5265. } else {
  5266. GGML_ASSERT(0);
  5267. }
  5268. const size_t kpad = ggml_vk_align_size(k, p->align);
  5269. if (k != kpad) {
  5270. if (shader_size == 0) {
  5271. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5272. p = ctx->device->pipeline_matmul_f32->s;
  5273. shname = "F32_S";
  5274. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5275. p = ctx->device->pipeline_matmul_f32_f16->s;
  5276. shname = "F32_F16_S";
  5277. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5278. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  5279. shname = "F16_F32_S";
  5280. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5281. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  5282. shname = "F16_S";
  5283. }
  5284. } else if (shader_size == 1) {
  5285. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5286. p = ctx->device->pipeline_matmul_f32->m;
  5287. shname = "F32_M";
  5288. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5289. p = ctx->device->pipeline_matmul_f32_f16->m;
  5290. shname = "F32_F16_M";
  5291. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5292. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  5293. shname = "F16_F32_M";
  5294. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5295. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  5296. shname = "F16_M";
  5297. }
  5298. } else if (shader_size == 2) {
  5299. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5300. p = ctx->device->pipeline_matmul_f32->l;
  5301. shname = "F32_L";
  5302. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5303. p = ctx->device->pipeline_matmul_f32_f16->l;
  5304. shname = "F32_F16_L";
  5305. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  5306. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  5307. shname = "F16_F32_L";
  5308. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5309. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  5310. shname = "F16_L";
  5311. }
  5312. }
  5313. }
  5314. ggml_pipeline_request_descriptor_sets(ctx->device, p, num_it);
  5315. if (split_k > 1) {
  5316. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  5317. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  5318. // Resize buffer
  5319. if (ctx->prealloc_split_k != nullptr) {
  5320. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  5321. }
  5322. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5323. }
  5324. }
  5325. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  5326. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5327. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5328. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5329. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  5330. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  5331. float* d = (float *) malloc(sizeof(float) * d_ne);
  5332. for (size_t i = 0; i < x_ne; i++) {
  5333. if (std::is_same<float, X_TYPE>()) {
  5334. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  5335. // x[i] = 1.0f;
  5336. // x[i] = i + 1;
  5337. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  5338. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  5339. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  5340. // x[i] = ggml_fp32_to_fp16(1.0f);
  5341. // x[i] = ggml_fp32_to_fp16(i + 1);
  5342. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  5343. } else {
  5344. GGML_ABORT("fatal error");
  5345. }
  5346. }
  5347. for (size_t i = 0; i < y_ne; i++) {
  5348. if (std::is_same<float, Y_TYPE>()) {
  5349. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  5350. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  5351. // y[i] = i + 1;
  5352. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5353. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  5354. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  5355. // y[i] = ggml_fp32_to_fp16(i + 1);
  5356. } else {
  5357. GGML_ABORT("fatal error");
  5358. }
  5359. }
  5360. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  5361. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  5362. vk_context subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  5363. ggml_vk_ctx_begin(ctx->device, subctx);
  5364. for (size_t i = 0; i < num_it; i++) {
  5365. ggml_vk_matmul(
  5366. ctx, subctx, p, ggml_vk_subbuffer(d_X), ggml_vk_subbuffer(d_Y), ggml_vk_subbuffer(d_D), ggml_vk_subbuffer(ctx->prealloc_split_k),
  5367. m, n, k,
  5368. k, k, m, k*m, k*n, m*n,
  5369. split_k, batch, batch, batch, 1, 1
  5370. );
  5371. }
  5372. ggml_vk_ctx_end(subctx);
  5373. auto begin = std::chrono::high_resolution_clock::now();
  5374. ggml_vk_submit(subctx, ctx->fence);
  5375. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  5376. ctx->device->device.resetFences({ ctx->fence });
  5377. auto end = std::chrono::high_resolution_clock::now();
  5378. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  5379. // copy dst to host
  5380. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  5381. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  5382. ggml_init_params iparams = {
  5383. /*.mem_size =*/ 1024*1024*1024,
  5384. /*.mem_buffer =*/ NULL,
  5385. /*.no_alloc =*/ true,
  5386. };
  5387. ggml_context * ggml_ctx = ggml_init(iparams);
  5388. ggml_type src0_type;
  5389. ggml_type src1_type;
  5390. if (std::is_same<float, X_TYPE>()) {
  5391. src0_type = GGML_TYPE_F32;
  5392. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  5393. src0_type = GGML_TYPE_F16;
  5394. } else {
  5395. GGML_ABORT("fatal error");
  5396. }
  5397. if (std::is_same<float, Y_TYPE>()) {
  5398. src1_type = GGML_TYPE_F32;
  5399. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  5400. src1_type = GGML_TYPE_F16;
  5401. } else {
  5402. GGML_ABORT("fatal error");
  5403. }
  5404. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  5405. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  5406. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  5407. src0_ggml->data = x;
  5408. src1_ggml->data = y;
  5409. tensor_ggml->data = d_chk;
  5410. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  5411. ggml_build_forward_expand(cgraph, tensor_ggml);
  5412. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  5413. ggml_free(ggml_ctx);
  5414. double avg_err = 0.0;
  5415. int first_err_n = -1;
  5416. int first_err_m = -1;
  5417. int first_err_b = -1;
  5418. for (size_t i = 0; i < m*n*batch; i++) {
  5419. double err = std::fabs(d[i] - d_chk[i]);
  5420. avg_err += err;
  5421. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  5422. first_err_b = i / (m * n);
  5423. first_err_n = (i % (m * n)) / m;
  5424. first_err_m = (i % (m * n)) % m;
  5425. }
  5426. }
  5427. avg_err /= m * n;
  5428. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  5429. 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;
  5430. if (avg_err > 0.1 || std::isnan(avg_err)) {
  5431. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  5432. std::cerr << "Actual result: " << std::endl << std::endl;
  5433. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5434. std::cerr << "Expected result: " << std::endl << std::endl;
  5435. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5436. if (split_k > 1) {
  5437. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  5438. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  5439. std::cerr << "d_buf0: " << std::endl << std::endl;
  5440. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5441. std::cerr << "d_buf1: " << std::endl << std::endl;
  5442. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5443. std::cerr << "d_buf2: " << std::endl << std::endl;
  5444. 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);
  5445. std::cerr << "d_buf3: " << std::endl << std::endl;
  5446. 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);
  5447. free(split_k_buf);
  5448. }
  5449. }
  5450. free(d_chk);
  5451. ggml_vk_queue_cleanup(ctx->device, ctx->device->transfer_queue);
  5452. ggml_vk_queue_cleanup(ctx->device, ctx->device->compute_queue);
  5453. ggml_vk_destroy_buffer(d_X);
  5454. ggml_vk_destroy_buffer(d_Y);
  5455. ggml_vk_destroy_buffer(d_D);
  5456. ggml_pipeline_cleanup(p);
  5457. ggml_pipeline_cleanup(ctx->device->pipeline_matmul_split_k_reduce);
  5458. free(x);
  5459. free(y);
  5460. free(d);
  5461. }
  5462. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  5463. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  5464. return;
  5465. }
  5466. i0 = std::max(i0, 5);
  5467. i1 = std::max(i1, 5);
  5468. i2 = std::max(i2, 0);
  5469. i3 = std::max(i3, 0);
  5470. fprintf(stderr, " ");
  5471. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  5472. fprintf(stderr, "%7d ", idx1);
  5473. }
  5474. fprintf(stderr, "\n");
  5475. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  5476. fprintf(stderr, "%7d: ", idx0);
  5477. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  5478. 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]) {
  5479. float val;
  5480. if (tensor->type == GGML_TYPE_F32) {
  5481. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  5482. } else if (tensor->type == GGML_TYPE_F16) {
  5483. 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]));
  5484. } else {
  5485. GGML_ABORT("fatal error");
  5486. }
  5487. fprintf(stderr, "% 7.2f ", val);
  5488. } else {
  5489. fprintf(stderr, " ");
  5490. }
  5491. }
  5492. fprintf(stderr, "\n");
  5493. }
  5494. }
  5495. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  5496. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  5497. }
  5498. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  5499. if (quant == GGML_TYPE_F32) {
  5500. memcpy(to, from, sizeof(float) * ne);
  5501. return;
  5502. }
  5503. const auto * tt = ggml_get_type_traits(quant);
  5504. ggml_to_float_t dequant_fn = tt->to_float;
  5505. dequant_fn(from, to, ne);
  5506. }
  5507. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  5508. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  5509. const size_t x_sz = sizeof(float) * ne;
  5510. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  5511. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  5512. float * x = (float *) malloc(x_sz);
  5513. void * qx = malloc(qx_sz);
  5514. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5515. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5516. float * x_ref = (float *) malloc(x_sz);
  5517. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  5518. for (size_t i = 0; i < ne; i++) {
  5519. x[i] = rand() / (float)RAND_MAX;
  5520. }
  5521. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  5522. ggml_vk_quantize_data(x, qx, ne, quant);
  5523. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  5524. ggml_pipeline_request_descriptor_sets(ctx->device, p, 1);
  5525. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  5526. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  5527. vk_context subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  5528. ggml_vk_ctx_begin(ctx->device, subctx);
  5529. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  5530. ggml_vk_dispatch_pipeline(ctx, subctx, p, { vk_subbuffer{ qx_buf, 0, qx_sz }, vk_subbuffer{ x_buf, 0, x_sz_f16 } }, pc.size() * sizeof(int), pc.data(), { (uint32_t)ne, 1, 1});
  5531. ggml_vk_ctx_end(subctx);
  5532. auto begin = std::chrono::high_resolution_clock::now();
  5533. ggml_vk_submit(subctx, ctx->fence);
  5534. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  5535. ctx->device->device.resetFences({ ctx->fence });
  5536. auto end = std::chrono::high_resolution_clock::now();
  5537. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  5538. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  5539. int first_err = -1;
  5540. double avg_err = 0.0;
  5541. for (size_t i = 0; i < ne; i++) {
  5542. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  5543. avg_err += error;
  5544. if (first_err < 0 && error > 0.05) {
  5545. first_err = i;
  5546. }
  5547. }
  5548. avg_err /= ne;
  5549. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  5550. if (avg_err > 0.1) {
  5551. std::cerr << "first_error = " << first_err << std::endl;
  5552. std::cerr << "Actual result: " << std::endl << std::endl;
  5553. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  5554. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  5555. }
  5556. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  5557. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  5558. std::cerr << x_ref[i] << ", ";
  5559. }
  5560. std::cerr << std::endl;
  5561. }
  5562. ggml_vk_destroy_buffer(x_buf);
  5563. ggml_vk_destroy_buffer(qx_buf);
  5564. free(x);
  5565. free(qx);
  5566. free(x_ref);
  5567. free(x_chk);
  5568. }
  5569. 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) {
  5570. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  5571. const size_t x_ne = m * k * batch;
  5572. const size_t y_ne = k * n * batch;
  5573. const size_t d_ne = m * n * batch;
  5574. vk_pipeline p;
  5575. std::string shname;
  5576. if (shader_size == 0) {
  5577. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->a_s : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->a_s;
  5578. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  5579. } else if (shader_size == 1) {
  5580. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->a_m : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->a_m;
  5581. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  5582. } else if (shader_size == 2) {
  5583. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->a_l : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->a_l;
  5584. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  5585. } else {
  5586. GGML_ASSERT(0);
  5587. }
  5588. const size_t kpad = ggml_vk_align_size(k, p->align);
  5589. if (k != kpad) {
  5590. if (shader_size == 0) {
  5591. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->s : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->s;
  5592. shname = std::string(ggml_type_name(quant)) + "_S";
  5593. } else if (shader_size == 1) {
  5594. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->m : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->m;
  5595. shname = std::string(ggml_type_name(quant)) + "_M";
  5596. } else if (shader_size == 2) {
  5597. p = ctx->device->fp16 ? ctx->device->pipeline_dequant_mul_mat_mat[quant].f16acc->l : ctx->device->pipeline_dequant_mul_mat_mat[quant].f32acc->l;
  5598. shname = std::string(ggml_type_name(quant)) + "_L";
  5599. } else {
  5600. GGML_ASSERT(0);
  5601. }
  5602. }
  5603. const size_t x_sz = sizeof(float) * x_ne;
  5604. const size_t y_sz = sizeof(float) * y_ne;
  5605. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  5606. const size_t d_sz = sizeof(float) * d_ne;
  5607. float * x = (float *) malloc(x_sz);
  5608. float * y = (float *) malloc(y_sz);
  5609. void * qx = malloc(qx_sz);
  5610. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5611. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5612. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5613. float * d = (float *) malloc(d_sz);
  5614. float * d_chk = (float *) malloc(d_sz);
  5615. for (size_t i = 0; i < x_ne; i++) {
  5616. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  5617. }
  5618. ggml_vk_quantize_data(x, qx, x_ne, quant);
  5619. for (size_t i = 0; i < y_ne; i++) {
  5620. // y[i] = rand() / (float)RAND_MAX;
  5621. y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  5622. }
  5623. ggml_pipeline_request_descriptor_sets(ctx->device, p, num_it);
  5624. if (split_k > 1) {
  5625. ggml_pipeline_request_descriptor_sets(ctx->device, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  5626. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  5627. // Resize buffer
  5628. if (ctx->prealloc_split_k != nullptr) {
  5629. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  5630. }
  5631. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, vk::MemoryPropertyFlagBits::eDeviceLocal);
  5632. }
  5633. }
  5634. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  5635. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  5636. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  5637. vk_context subctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  5638. ggml_vk_ctx_begin(ctx->device, subctx);
  5639. for (size_t i = 0; i < num_it; i++) {
  5640. ggml_vk_matmul(
  5641. ctx, subctx, p, ggml_vk_subbuffer(qx_buf), ggml_vk_subbuffer(y_buf), ggml_vk_subbuffer(d_buf), ggml_vk_subbuffer(ctx->prealloc_split_k),
  5642. m, n, k,
  5643. k, k, m, k*m, k*n, m*n,
  5644. split_k, batch, batch, batch, 1, 1
  5645. );
  5646. }
  5647. ggml_vk_ctx_end(subctx);
  5648. auto begin = std::chrono::high_resolution_clock::now();
  5649. ggml_vk_submit(subctx, ctx->fence);
  5650. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  5651. ctx->device->device.resetFences({ ctx->fence });
  5652. auto end = std::chrono::high_resolution_clock::now();
  5653. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  5654. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  5655. ggml_init_params iparams = {
  5656. /*.mem_size =*/ 1024*1024*1024,
  5657. /*.mem_buffer =*/ NULL,
  5658. /*.no_alloc =*/ true,
  5659. };
  5660. ggml_context * ggml_ctx = ggml_init(iparams);
  5661. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  5662. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  5663. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  5664. src0_ggml->data = qx;
  5665. src1_ggml->data = y;
  5666. tensor_ggml->data = d_chk;
  5667. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  5668. ggml_build_forward_expand(cgraph, tensor_ggml);
  5669. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  5670. ggml_free(ggml_ctx);
  5671. double avg_err = 0.0;
  5672. int first_err_n = -1;
  5673. int first_err_m = -1;
  5674. int first_err_b = -1;
  5675. for (size_t i = 0; i < m*n*batch; i++) {
  5676. double err = std::fabs(d[i] - d_chk[i]);
  5677. avg_err += err;
  5678. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  5679. first_err_b = i / (m * n);
  5680. first_err_n = (i % (m * n)) / m;
  5681. first_err_m = (i % (m * n)) % m;
  5682. }
  5683. }
  5684. avg_err /= m * n;
  5685. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  5686. std::cerr << "TEST MMQ " << shname << " 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;
  5687. if (avg_err > 0.01 || std::isnan(avg_err)) {
  5688. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  5689. std::cerr << "Actual result: " << std::endl << std::endl;
  5690. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5691. std::cerr << std::endl;
  5692. std::cerr << "Expected result: " << std::endl << std::endl;
  5693. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5694. if (split_k > 1) {
  5695. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  5696. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  5697. std::cerr << "d_buf0: " << std::endl << std::endl;
  5698. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5699. std::cerr << "d_buf1: " << std::endl << std::endl;
  5700. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  5701. std::cerr << "d_buf2: " << std::endl << std::endl;
  5702. 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);
  5703. std::cerr << "d_buf3: " << std::endl << std::endl;
  5704. 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);
  5705. free(split_k_buf);
  5706. }
  5707. }
  5708. ggml_vk_destroy_buffer(qx_buf);
  5709. ggml_vk_destroy_buffer(y_buf);
  5710. ggml_vk_destroy_buffer(d_buf);
  5711. free(x);
  5712. free(qx);
  5713. free(y);
  5714. free(d);
  5715. free(d_chk);
  5716. }
  5717. #endif
  5718. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx) {
  5719. #if defined(GGML_VULKAN_RUN_TESTS)
  5720. const std::vector<size_t> vals {
  5721. 512, 512, 128,
  5722. 128, 512, 512,
  5723. 4096, 512, 4096,
  5724. 11008, 512, 4096,
  5725. 4096, 512, 11008,
  5726. 32000, 512, 4096,
  5727. 8, 8, 8,
  5728. 100, 46, 576,
  5729. 623, 111, 128,
  5730. 100, 46, 558,
  5731. 512, 1, 256,
  5732. 128, 110, 622,
  5733. 511, 511, 127,
  5734. 511, 511, 7,
  5735. 511, 511, 17,
  5736. 49, 49, 128,
  5737. 128, 49, 49,
  5738. 4096, 49, 4096,
  5739. };
  5740. const size_t num_it = 100;
  5741. for (size_t i = 0; i < vals.size(); i += 3) {
  5742. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  5743. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  5744. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  5745. std::cerr << '\n';
  5746. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  5747. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  5748. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  5749. std::cerr << '\n';
  5750. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  5751. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  5752. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  5753. std::cerr << '\n' << std::endl;
  5754. if (vals[i + 2] % 32 == 0) {
  5755. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  5756. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  5757. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  5758. std::cerr << '\n';
  5759. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  5760. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  5761. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  5762. std::cerr << '\n';
  5763. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  5764. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  5765. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  5766. std::cerr << '\n' << std::endl;
  5767. }
  5768. if (vals[i + 2] % 256 == 0) {
  5769. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  5770. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  5771. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  5772. std::cerr << '\n';
  5773. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  5774. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  5775. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  5776. std::cerr << '\n';
  5777. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  5778. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  5779. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  5780. std::cerr << '\n' << std::endl;
  5781. }
  5782. }
  5783. GGML_ABORT("fatal error");
  5784. #endif
  5785. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  5786. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  5787. // Resize buffer
  5788. if (ctx->prealloc_x != nullptr) {
  5789. ggml_vk_destroy_buffer(ctx->prealloc_x);
  5790. }
  5791. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  5792. }
  5793. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  5794. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  5795. // Resize buffer
  5796. if (ctx->prealloc_y != nullptr) {
  5797. ggml_vk_destroy_buffer(ctx->prealloc_y);
  5798. }
  5799. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  5800. }
  5801. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  5802. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  5803. // Resize buffer
  5804. if (ctx->prealloc_split_k != nullptr) {
  5805. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  5806. }
  5807. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  5808. }
  5809. }
  5810. static bool ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_tensor* tensor, int tensor_idx, bool use_fence);
  5811. // Returns true if node has enqueued work into the queue, false otherwise
  5812. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  5813. static bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_tensor * node, int node_idx, ggml_tensor *node_begin, int node_idx_begin, bool dryrun, bool last_node, bool submit){
  5814. if (ggml_is_empty(node) || !node->buffer) {
  5815. return false;
  5816. }
  5817. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  5818. ctx->semaphore_idx = 0;
  5819. const ggml_tensor * src0 = node->src[0];
  5820. const ggml_tensor * src1 = node->src[1];
  5821. const ggml_tensor * src2 = node->src[2];
  5822. const ggml_tensor * src3 = node->src[3];
  5823. switch (node->op) {
  5824. // Return on empty ops to avoid generating a compute_ctx and setting exit_tensor
  5825. case GGML_OP_RESHAPE:
  5826. case GGML_OP_VIEW:
  5827. case GGML_OP_PERMUTE:
  5828. case GGML_OP_TRANSPOSE:
  5829. case GGML_OP_NONE:
  5830. return false;
  5831. case GGML_OP_UNARY:
  5832. switch (ggml_get_unary_op(node)) {
  5833. case GGML_UNARY_OP_SILU:
  5834. case GGML_UNARY_OP_GELU:
  5835. case GGML_UNARY_OP_GELU_QUICK:
  5836. case GGML_UNARY_OP_RELU:
  5837. case GGML_UNARY_OP_TANH:
  5838. break;
  5839. default:
  5840. return false;
  5841. }
  5842. break;
  5843. case GGML_OP_REPEAT:
  5844. case GGML_OP_GET_ROWS:
  5845. case GGML_OP_ADD:
  5846. case GGML_OP_ACC:
  5847. case GGML_OP_MUL:
  5848. case GGML_OP_DIV:
  5849. case GGML_OP_CONCAT:
  5850. case GGML_OP_UPSCALE:
  5851. case GGML_OP_SCALE:
  5852. case GGML_OP_SQR:
  5853. case GGML_OP_SIN:
  5854. case GGML_OP_COS:
  5855. case GGML_OP_CLAMP:
  5856. case GGML_OP_PAD:
  5857. case GGML_OP_CPY:
  5858. case GGML_OP_CONT:
  5859. case GGML_OP_DUP:
  5860. case GGML_OP_NORM:
  5861. case GGML_OP_GROUP_NORM:
  5862. case GGML_OP_RMS_NORM:
  5863. case GGML_OP_DIAG_MASK_INF:
  5864. case GGML_OP_SOFT_MAX:
  5865. case GGML_OP_ROPE:
  5866. case GGML_OP_MUL_MAT:
  5867. case GGML_OP_MUL_MAT_ID:
  5868. case GGML_OP_ARGSORT:
  5869. case GGML_OP_SUM_ROWS:
  5870. case GGML_OP_IM2COL:
  5871. case GGML_OP_TIMESTEP_EMBEDDING:
  5872. case GGML_OP_POOL_2D:
  5873. case GGML_OP_RWKV_WKV6:
  5874. case GGML_OP_LEAKY_RELU:
  5875. case GGML_OP_FLASH_ATTN_EXT:
  5876. break;
  5877. default:
  5878. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(node->op) << std::endl;
  5879. GGML_ABORT("fatal error");
  5880. return false;
  5881. }
  5882. vk_context compute_ctx;
  5883. if (!dryrun) {
  5884. if (ctx->compute_ctx.expired()) {
  5885. compute_ctx = ggml_vk_create_context(ctx, ctx->device->compute_queue);
  5886. ctx->compute_ctx = compute_ctx;
  5887. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  5888. } else {
  5889. compute_ctx = ctx->compute_ctx.lock();
  5890. }
  5891. } else {
  5892. switch (node->op) {
  5893. case GGML_OP_REPEAT:
  5894. case GGML_OP_ACC:
  5895. case GGML_OP_GET_ROWS:
  5896. case GGML_OP_ADD:
  5897. case GGML_OP_MUL:
  5898. case GGML_OP_DIV:
  5899. case GGML_OP_CONCAT:
  5900. case GGML_OP_UPSCALE:
  5901. case GGML_OP_SCALE:
  5902. case GGML_OP_SQR:
  5903. case GGML_OP_SIN:
  5904. case GGML_OP_COS:
  5905. case GGML_OP_CLAMP:
  5906. case GGML_OP_PAD:
  5907. case GGML_OP_CPY:
  5908. case GGML_OP_CONT:
  5909. case GGML_OP_DUP:
  5910. case GGML_OP_NORM:
  5911. case GGML_OP_GROUP_NORM:
  5912. case GGML_OP_RMS_NORM:
  5913. case GGML_OP_UNARY:
  5914. case GGML_OP_DIAG_MASK_INF:
  5915. case GGML_OP_SOFT_MAX:
  5916. case GGML_OP_ROPE:
  5917. case GGML_OP_ARGSORT:
  5918. case GGML_OP_SUM_ROWS:
  5919. case GGML_OP_IM2COL:
  5920. case GGML_OP_TIMESTEP_EMBEDDING:
  5921. case GGML_OP_POOL_2D:
  5922. case GGML_OP_LEAKY_RELU:
  5923. {
  5924. // These operations all go through ggml_vk_op_f32, so short-circuit and
  5925. // do the only thing needed for the dryrun.
  5926. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, node, node->op);
  5927. ggml_pipeline_request_descriptor_sets(ctx->device, pipeline, 1);
  5928. return false;
  5929. }
  5930. default:
  5931. break;
  5932. }
  5933. }
  5934. switch (node->op) {
  5935. case GGML_OP_REPEAT:
  5936. ggml_vk_repeat(ctx, compute_ctx, src0, node, dryrun);
  5937. break;
  5938. case GGML_OP_ACC:
  5939. ggml_vk_acc(ctx, compute_ctx, src0, src1, node, dryrun);
  5940. break;
  5941. case GGML_OP_GET_ROWS:
  5942. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node, dryrun);
  5943. break;
  5944. case GGML_OP_ADD:
  5945. ggml_vk_add(ctx, compute_ctx, src0, src1, node, dryrun);
  5946. break;
  5947. case GGML_OP_MUL:
  5948. ggml_vk_mul(ctx, compute_ctx, src0, src1, node, dryrun);
  5949. break;
  5950. case GGML_OP_DIV:
  5951. ggml_vk_div(ctx, compute_ctx, src0, src1, node, dryrun);
  5952. break;
  5953. case GGML_OP_CONCAT:
  5954. ggml_vk_concat(ctx, compute_ctx, src0, src1, node, dryrun);
  5955. break;
  5956. case GGML_OP_UPSCALE:
  5957. ggml_vk_upscale(ctx, compute_ctx, src0, node, dryrun);
  5958. break;
  5959. case GGML_OP_SCALE:
  5960. ggml_vk_scale(ctx, compute_ctx, src0, node, dryrun);
  5961. break;
  5962. case GGML_OP_SQR:
  5963. ggml_vk_sqr(ctx, compute_ctx, src0, node, dryrun);
  5964. break;
  5965. case GGML_OP_SIN:
  5966. ggml_vk_sin(ctx, compute_ctx, src0, node, dryrun);
  5967. break;
  5968. case GGML_OP_COS:
  5969. ggml_vk_cos(ctx, compute_ctx, src0, node, dryrun);
  5970. break;
  5971. case GGML_OP_CLAMP:
  5972. ggml_vk_clamp(ctx, compute_ctx, src0, node, dryrun);
  5973. break;
  5974. case GGML_OP_PAD:
  5975. ggml_vk_pad(ctx, compute_ctx, src0, node, dryrun);
  5976. break;
  5977. case GGML_OP_CPY:
  5978. case GGML_OP_CONT:
  5979. case GGML_OP_DUP:
  5980. ggml_vk_cpy(ctx, compute_ctx, src0, node, dryrun);
  5981. break;
  5982. case GGML_OP_NORM:
  5983. ggml_vk_norm(ctx, compute_ctx, src0, node, dryrun);
  5984. break;
  5985. case GGML_OP_GROUP_NORM:
  5986. ggml_vk_group_norm(ctx, compute_ctx, src0, node, dryrun);
  5987. break;
  5988. case GGML_OP_RMS_NORM:
  5989. ggml_vk_rms_norm(ctx, compute_ctx, src0, node, dryrun);
  5990. break;
  5991. case GGML_OP_UNARY:
  5992. switch (ggml_get_unary_op(node)) {
  5993. case GGML_UNARY_OP_SILU:
  5994. case GGML_UNARY_OP_GELU:
  5995. case GGML_UNARY_OP_GELU_QUICK:
  5996. case GGML_UNARY_OP_RELU:
  5997. case GGML_UNARY_OP_TANH:
  5998. ggml_vk_unary(ctx, compute_ctx, src0, node, dryrun);
  5999. break;
  6000. default:
  6001. return false;
  6002. }
  6003. break;
  6004. case GGML_OP_DIAG_MASK_INF:
  6005. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node, dryrun);
  6006. break;
  6007. case GGML_OP_SOFT_MAX:
  6008. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, node, dryrun);
  6009. break;
  6010. case GGML_OP_ROPE:
  6011. ggml_vk_rope(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  6012. break;
  6013. case GGML_OP_ARGSORT:
  6014. ggml_vk_argsort(ctx, compute_ctx, src0, node, dryrun);
  6015. break;
  6016. case GGML_OP_SUM_ROWS:
  6017. ggml_vk_sum_rows(ctx, compute_ctx, src0, node, dryrun);
  6018. break;
  6019. case GGML_OP_IM2COL:
  6020. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node, dryrun);
  6021. break;
  6022. case GGML_OP_TIMESTEP_EMBEDDING:
  6023. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node, dryrun);
  6024. break;
  6025. case GGML_OP_POOL_2D:
  6026. ggml_vk_pool_2d(ctx, compute_ctx, src0, node, dryrun);
  6027. break;
  6028. case GGML_OP_LEAKY_RELU:
  6029. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node, dryrun);
  6030. break;
  6031. case GGML_OP_MUL_MAT:
  6032. ggml_vk_mul_mat(ctx, compute_ctx, src0, src1, node, dryrun);
  6033. break;
  6034. case GGML_OP_MUL_MAT_ID:
  6035. ggml_vk_mul_mat_id(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  6036. break;
  6037. case GGML_OP_FLASH_ATTN_EXT:
  6038. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node, dryrun);
  6039. break;
  6040. case GGML_OP_RWKV_WKV6:
  6041. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node, dryrun);
  6042. break;
  6043. default:
  6044. return false;
  6045. }
  6046. if (dryrun) {
  6047. return false;
  6048. }
  6049. ctx->tensor_ctxs[node_idx] = compute_ctx;
  6050. #if defined(GGML_VULKAN_CHECK_RESULTS) || defined(GGML_VULKAN_PERF)
  6051. // Force context reset on each node so that each tensor ends up in its own context
  6052. // and can be run and compared to its CPU equivalent separately
  6053. last_node = true;
  6054. #endif
  6055. if (submit || last_node) {
  6056. ggml_vk_ctx_end(compute_ctx);
  6057. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  6058. if (last_node) {
  6059. compute_ctx->exit_tensor_idx = node_idx_begin;
  6060. }
  6061. else {
  6062. compute_ctx->exit_tensor_idx = -1;
  6063. }
  6064. ctx->compute_ctx.reset();
  6065. bool ok = ggml_vk_compute_forward(ctx, node_begin, node_idx_begin, false);
  6066. if (!ok) {
  6067. if (node->op == GGML_OP_UNARY) {
  6068. 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;
  6069. }
  6070. else {
  6071. std::cerr << __func__ << ": error: op not supported " << node->name << " (" << ggml_op_name(node->op) << ")" << std::endl;
  6072. }
  6073. }
  6074. }
  6075. return true;
  6076. }
  6077. static bool ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_tensor * tensor, int tensor_idx, bool use_fence = true){
  6078. ggml_backend_buffer * buf = nullptr;
  6079. switch (tensor->op) {
  6080. case GGML_OP_ADD:
  6081. case GGML_OP_ACC:
  6082. case GGML_OP_GET_ROWS:
  6083. case GGML_OP_MUL:
  6084. case GGML_OP_DIV:
  6085. case GGML_OP_CONCAT:
  6086. case GGML_OP_UPSCALE:
  6087. case GGML_OP_SCALE:
  6088. case GGML_OP_SQR:
  6089. case GGML_OP_SIN:
  6090. case GGML_OP_COS:
  6091. case GGML_OP_CLAMP:
  6092. case GGML_OP_PAD:
  6093. case GGML_OP_CPY:
  6094. case GGML_OP_CONT:
  6095. case GGML_OP_DUP:
  6096. case GGML_OP_NORM:
  6097. case GGML_OP_GROUP_NORM:
  6098. case GGML_OP_RMS_NORM:
  6099. case GGML_OP_DIAG_MASK_INF:
  6100. case GGML_OP_SOFT_MAX:
  6101. case GGML_OP_ROPE:
  6102. case GGML_OP_RESHAPE:
  6103. case GGML_OP_VIEW:
  6104. case GGML_OP_PERMUTE:
  6105. case GGML_OP_TRANSPOSE:
  6106. case GGML_OP_NONE:
  6107. case GGML_OP_ARGSORT:
  6108. case GGML_OP_SUM_ROWS:
  6109. case GGML_OP_IM2COL:
  6110. case GGML_OP_TIMESTEP_EMBEDDING:
  6111. case GGML_OP_POOL_2D:
  6112. case GGML_OP_RWKV_WKV6:
  6113. case GGML_OP_LEAKY_RELU:
  6114. case GGML_OP_REPEAT:
  6115. buf = tensor->buffer;
  6116. break;
  6117. case GGML_OP_UNARY:
  6118. switch (ggml_get_unary_op(tensor)) {
  6119. case GGML_UNARY_OP_SILU:
  6120. case GGML_UNARY_OP_GELU:
  6121. case GGML_UNARY_OP_GELU_QUICK:
  6122. case GGML_UNARY_OP_RELU:
  6123. case GGML_UNARY_OP_TANH:
  6124. buf = tensor->buffer;
  6125. break;
  6126. default:
  6127. return false;
  6128. }
  6129. break;
  6130. case GGML_OP_MUL_MAT:
  6131. case GGML_OP_MUL_MAT_ID:
  6132. case GGML_OP_FLASH_ATTN_EXT:
  6133. buf = tensor->buffer;
  6134. break;
  6135. default:
  6136. return false;
  6137. }
  6138. if (buf == nullptr) {
  6139. return false;
  6140. }
  6141. 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 << ")");
  6142. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  6143. // always wait for the GPU work to be done for the last submit
  6144. if (tensor_idx == subctx->exit_tensor_idx) {
  6145. use_fence = true;
  6146. }
  6147. // Only run if ctx hasn't been submitted yet
  6148. if (!subctx->seqs.empty()) {
  6149. #ifdef GGML_VULKAN_CHECK_RESULTS
  6150. ggml_vk_check_results_0(tensor);
  6151. use_fence = true;
  6152. #endif
  6153. // Do staging buffer copies
  6154. for (auto& cpy : subctx->in_memcpys) {
  6155. memcpy(cpy.dst, cpy.src, cpy.n);
  6156. }
  6157. ggml_vk_submit(subctx, use_fence ? ctx->fence : vk::Fence{});
  6158. if (use_fence) {
  6159. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_compute_forward waitForFences");
  6160. ctx->device->device.resetFences({ ctx->fence });
  6161. }
  6162. #ifdef GGML_VULKAN_CHECK_RESULTS
  6163. ggml_vk_check_results_1(tensor);
  6164. #endif
  6165. }
  6166. if (tensor_idx == subctx->exit_tensor_idx) {
  6167. // Do staging buffer copies
  6168. for (auto& cpy : subctx->out_memcpys) {
  6169. memcpy(cpy.dst, cpy.src, cpy.n);
  6170. }
  6171. subctx->in_memcpys.clear();
  6172. subctx->out_memcpys.clear();
  6173. }
  6174. return true;
  6175. }
  6176. // Clean up after graph processing is done
  6177. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  6178. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  6179. for (auto& buffer : ctx->gc.temp_buffers) {
  6180. ggml_vk_pool_free(ctx, buffer);
  6181. }
  6182. ctx->gc.temp_buffers.clear();
  6183. for (auto& dsr : ctx->device->pipeline_descriptor_set_requirements) {
  6184. vk_pipeline_ref plr = ctx->device->pipelines[dsr.first];
  6185. if (plr.expired()) {
  6186. continue;
  6187. }
  6188. vk_pipeline pl = plr.lock();
  6189. ggml_pipeline_cleanup(pl);
  6190. }
  6191. ggml_vk_queue_cleanup(ctx->device, ctx->device->compute_queue);
  6192. ggml_vk_queue_cleanup(ctx->device, ctx->device->transfer_queue);
  6193. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  6194. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  6195. }
  6196. ctx->gc.semaphores.clear();
  6197. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  6198. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  6199. }
  6200. ctx->gc.tl_semaphores.clear();
  6201. ctx->semaphore_idx = 0;
  6202. ctx->event_idx = 0;
  6203. for (auto& event : ctx->gc.events) {
  6204. ctx->device->device.resetEvent(event);
  6205. }
  6206. ctx->tensor_ctxs.clear();
  6207. ctx->gc.contexts.clear();
  6208. ctx->device->pipeline_descriptor_set_requirements.clear();
  6209. }
  6210. // Clean up on backend free
  6211. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  6212. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  6213. ggml_vk_graph_cleanup(ctx);
  6214. ggml_vk_destroy_buffer(ctx->prealloc_x);
  6215. ggml_vk_destroy_buffer(ctx->prealloc_y);
  6216. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  6217. for (auto& buffer : ctx->buffer_pool) {
  6218. ggml_vk_destroy_buffer(buffer);
  6219. }
  6220. ctx->prealloc_size_x = 0;
  6221. ctx->prealloc_size_y = 0;
  6222. ctx->prealloc_size_split_k = 0;
  6223. for (auto& event : ctx->gc.events) {
  6224. ctx->device->device.destroyEvent(event);
  6225. }
  6226. ctx->gc.events.clear();
  6227. ctx->device->device.destroyFence(ctx->fence);
  6228. }
  6229. static int ggml_vk_get_device_count() {
  6230. ggml_vk_instance_init();
  6231. return vk_instance.device_indices.size();
  6232. }
  6233. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  6234. ggml_vk_instance_init();
  6235. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  6236. vk::PhysicalDeviceProperties props;
  6237. devices[device].getProperties(&props);
  6238. snprintf(description, description_size, "%s", props.deviceName.data());
  6239. }
  6240. // backend interface
  6241. #define UNUSED GGML_UNUSED
  6242. // device backend
  6243. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  6244. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  6245. }
  6246. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  6247. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  6248. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  6249. ggml_vk_destroy_buffer(ctx->dev_buffer);
  6250. delete ctx;
  6251. }
  6252. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  6253. return vk_ptr_base;
  6254. UNUSED(buffer);
  6255. }
  6256. static void ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  6257. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  6258. if (tensor->view_src != nullptr) {
  6259. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  6260. }
  6261. }
  6262. 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) {
  6263. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  6264. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  6265. vk_buffer buf = buf_ctx->dev_buffer;
  6266. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  6267. }
  6268. 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) {
  6269. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  6270. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  6271. vk_buffer buf = buf_ctx->dev_buffer;
  6272. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  6273. }
  6274. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  6275. if (ggml_backend_buffer_is_vk(src->buffer)) {
  6276. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  6277. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6278. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  6279. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  6280. 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));
  6281. return true;
  6282. }
  6283. return false;
  6284. UNUSED(buffer);
  6285. }
  6286. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  6287. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  6288. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  6289. }
  6290. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  6291. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  6292. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  6293. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  6294. /* .memset_tensor = */ NULL,
  6295. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  6296. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  6297. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  6298. /* .clear = */ ggml_backend_vk_buffer_clear,
  6299. /* .reset = */ NULL,
  6300. };
  6301. // vk buffer type
  6302. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  6303. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  6304. return ctx->name.c_str();
  6305. }
  6306. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  6307. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  6308. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  6309. vk_buffer dev_buffer = nullptr;
  6310. try {
  6311. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  6312. } catch (const vk::SystemError& e) {
  6313. return nullptr;
  6314. }
  6315. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  6316. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  6317. }
  6318. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  6319. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  6320. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  6321. }
  6322. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  6323. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  6324. return ctx->device->max_memory_allocation_size;
  6325. }
  6326. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  6327. return ggml_nbytes(tensor);
  6328. UNUSED(buft);
  6329. }
  6330. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  6331. ggml_vk_instance_init();
  6332. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  6333. vk_device dev = ggml_vk_get_device(dev_num);
  6334. return &dev->buffer_type;
  6335. }
  6336. // host buffer type
  6337. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  6338. return GGML_VK_NAME "_Host";
  6339. UNUSED(buft);
  6340. }
  6341. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  6342. return GGML_VK_NAME "_Host";
  6343. UNUSED(buffer);
  6344. }
  6345. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  6346. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  6347. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  6348. }
  6349. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  6350. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  6351. size += 32; // Behave like the CPU buffer type
  6352. void * ptr = nullptr;
  6353. try {
  6354. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  6355. } catch (vk::SystemError& e) {
  6356. std::cerr << "ggml_vulkan: Failed to allocate pinned memory." << std::endl;
  6357. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  6358. // fallback to cpu buffer
  6359. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  6360. }
  6361. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  6362. buffer->buft = buft;
  6363. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  6364. return buffer;
  6365. UNUSED(buft);
  6366. }
  6367. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  6368. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  6369. UNUSED(buft);
  6370. }
  6371. // Should be changed to return device-specific host buffer type
  6372. // but that probably requires changes in llama.cpp
  6373. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  6374. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  6375. /* .iface = */ {
  6376. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  6377. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  6378. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  6379. /* .get_max_size = */ NULL, // defaults to SIZE_MAX
  6380. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  6381. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  6382. },
  6383. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  6384. /* .context = */ nullptr,
  6385. };
  6386. // Make sure device 0 is initialized
  6387. ggml_vk_instance_init();
  6388. ggml_vk_get_device(0);
  6389. return &ggml_backend_vk_buffer_type_host;
  6390. }
  6391. // backend
  6392. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  6393. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6394. return ctx->name.c_str();
  6395. }
  6396. static void ggml_backend_vk_free(ggml_backend_t backend) {
  6397. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6398. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  6399. ggml_vk_cleanup(ctx);
  6400. delete ctx;
  6401. delete backend;
  6402. }
  6403. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  6404. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6405. return &ctx->device->buffer_type;
  6406. }
  6407. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  6408. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  6409. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6410. 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");
  6411. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  6412. vk_context transfer_ctx;
  6413. if (ctx->transfer_ctx.expired()) {
  6414. // Initialize new transfer context
  6415. transfer_ctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  6416. ctx->transfer_ctx = transfer_ctx;
  6417. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  6418. } else {
  6419. transfer_ctx = ctx->transfer_ctx.lock();
  6420. }
  6421. vk_buffer buf = buf_ctx->dev_buffer;
  6422. ggml_vk_buffer_write_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  6423. }
  6424. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  6425. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  6426. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6427. 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");
  6428. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  6429. vk_context transfer_ctx;
  6430. if (ctx->transfer_ctx.expired()) {
  6431. // Initialize new transfer context
  6432. transfer_ctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  6433. ctx->transfer_ctx = transfer_ctx;
  6434. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  6435. } else {
  6436. transfer_ctx = ctx->transfer_ctx.lock();
  6437. }
  6438. vk_buffer buf = buf_ctx->dev_buffer;
  6439. ggml_vk_buffer_read_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  6440. }
  6441. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  6442. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  6443. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6444. 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)) {
  6445. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  6446. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6447. vk_context transfer_ctx;
  6448. if (ctx->transfer_ctx.expired()) {
  6449. // Initialize new transfer context
  6450. transfer_ctx = ggml_vk_create_context(ctx, ctx->device->transfer_queue);
  6451. ctx->transfer_ctx = transfer_ctx;
  6452. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  6453. } else {
  6454. transfer_ctx = ctx->transfer_ctx.lock();
  6455. }
  6456. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  6457. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  6458. 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));
  6459. return true;
  6460. }
  6461. return false;
  6462. }
  6463. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  6464. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  6465. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6466. if(ctx->transfer_ctx.expired()) {
  6467. return;
  6468. }
  6469. vk_context transfer_ctx = ctx->transfer_ctx.lock();
  6470. ggml_vk_ctx_end(transfer_ctx);
  6471. for (auto& cpy : transfer_ctx->in_memcpys) {
  6472. memcpy(cpy.dst, cpy.src, cpy.n);
  6473. }
  6474. ggml_vk_submit(transfer_ctx, ctx->fence);
  6475. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_backend_vk_synchronize waitForFences");
  6476. ctx->device->device.resetFences({ ctx->fence });
  6477. for (auto& cpy : transfer_ctx->out_memcpys) {
  6478. memcpy(cpy.dst, cpy.src, cpy.n);
  6479. }
  6480. ctx->transfer_ctx.reset();
  6481. }
  6482. static bool ggml_vk_is_empty(ggml_tensor * node) {
  6483. 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;
  6484. }
  6485. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  6486. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  6487. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  6488. for (int i = 0; i < cgraph->n_nodes; i++) {
  6489. ggml_vk_build_graph(ctx, cgraph->nodes[i], i, nullptr, 0, true, false, false);
  6490. }
  6491. if (ctx->device->need_compiles) {
  6492. ggml_vk_load_shaders(ctx->device);
  6493. }
  6494. ggml_vk_preallocate_buffers(ctx);
  6495. ggml_pipeline_allocate_descriptor_sets(ctx->device);
  6496. int last_node = cgraph->n_nodes - 1;
  6497. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  6498. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  6499. last_node -= 1;
  6500. }
  6501. // Reserve tensor context space for all nodes
  6502. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  6503. bool first_node_in_batch = true; // true if next node will be first node in a batch
  6504. int submit_node_idx = 0; // index to first node in a batch
  6505. // Submit work every nodes_per_submit nodes to overlap CPU cmdbuffer generation with GPU execution.
  6506. // Start with a smaller count to get work submitted right away, and increase it after each submit.
  6507. int nodes_per_submit = 20;
  6508. int submitted_nodes = 0;
  6509. int submit_count = 0;
  6510. for (int i = 0; i < cgraph->n_nodes; i++) {
  6511. if (first_node_in_batch) {
  6512. submit_node_idx = i;
  6513. }
  6514. bool submit = (submitted_nodes >= nodes_per_submit) || (i == last_node);
  6515. bool enqueued = ggml_vk_build_graph(ctx, cgraph->nodes[i], i, cgraph->nodes[submit_node_idx], submit_node_idx, false, i == last_node, submit);
  6516. if (enqueued) {
  6517. ++submitted_nodes;
  6518. #ifndef GGML_VULKAN_CHECK_RESULTS
  6519. if (first_node_in_batch) {
  6520. first_node_in_batch = false;
  6521. }
  6522. #endif
  6523. }
  6524. if (submit) {
  6525. first_node_in_batch = true;
  6526. submitted_nodes = 0;
  6527. switch (submit_count) {
  6528. case 0:
  6529. nodes_per_submit = 50;
  6530. break;
  6531. default:
  6532. nodes_per_submit = 100;
  6533. break;
  6534. }
  6535. submit_count++;
  6536. }
  6537. }
  6538. #ifdef GGML_VULKAN_PERF
  6539. ctx->device->perf_logger->print_timings();
  6540. #endif
  6541. ggml_vk_graph_cleanup(ctx);
  6542. return GGML_STATUS_SUCCESS;
  6543. UNUSED(backend);
  6544. }
  6545. // TODO: enable async and synchronize
  6546. static ggml_backend_i ggml_backend_vk_interface = {
  6547. /* .get_name = */ ggml_backend_vk_name,
  6548. /* .free = */ ggml_backend_vk_free,
  6549. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  6550. /* .get_tensor_async = */ NULL, // ggml_backend_vk_get_tensor_async,
  6551. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  6552. /* .synchronize = */ NULL, // ggml_backend_vk_synchronize,
  6553. /* .graph_plan_create = */ NULL,
  6554. /* .graph_plan_free = */ NULL,
  6555. /* .graph_plan_update = */ NULL,
  6556. /* .graph_plan_compute = */ NULL,
  6557. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  6558. /* .event_record = */ NULL,
  6559. /* .event_wait = */ NULL,
  6560. };
  6561. static ggml_guid_t ggml_backend_vk_guid() {
  6562. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  6563. return &guid;
  6564. }
  6565. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  6566. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  6567. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  6568. ggml_vk_init(ctx, dev_num);
  6569. ggml_backend_t vk_backend = new ggml_backend {
  6570. /* .guid = */ ggml_backend_vk_guid(),
  6571. /* .interface = */ ggml_backend_vk_interface,
  6572. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  6573. /* .context = */ ctx,
  6574. };
  6575. return vk_backend;
  6576. }
  6577. bool ggml_backend_is_vk(ggml_backend_t backend) {
  6578. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  6579. }
  6580. int ggml_backend_vk_get_device_count() {
  6581. return ggml_vk_get_device_count();
  6582. }
  6583. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  6584. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  6585. int dev_idx = vk_instance.device_indices[device];
  6586. ggml_vk_get_device_description(dev_idx, description, description_size);
  6587. }
  6588. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  6589. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  6590. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  6591. vk::PhysicalDeviceMemoryProperties memprops = vkdev.getMemoryProperties();
  6592. for (const vk::MemoryHeap& heap : memprops.memoryHeaps) {
  6593. if (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
  6594. *total = heap.size;
  6595. *free = heap.size;
  6596. break;
  6597. }
  6598. }
  6599. }
  6600. //////////////////////////
  6601. struct ggml_backend_vk_device_context {
  6602. size_t device;
  6603. std::string name;
  6604. std::string description;
  6605. };
  6606. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  6607. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6608. return ctx->name.c_str();
  6609. }
  6610. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  6611. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6612. return ctx->description.c_str();
  6613. }
  6614. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  6615. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  6616. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  6617. }
  6618. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  6619. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6620. return ggml_backend_vk_buffer_type(ctx->device);
  6621. }
  6622. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  6623. UNUSED(dev);
  6624. return ggml_backend_vk_host_buffer_type();
  6625. }
  6626. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  6627. UNUSED(dev);
  6628. return GGML_BACKEND_DEVICE_TYPE_GPU;
  6629. }
  6630. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  6631. props->name = ggml_backend_vk_device_get_name(dev);
  6632. props->description = ggml_backend_vk_device_get_description(dev);
  6633. props->type = ggml_backend_vk_device_get_type(dev);
  6634. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  6635. props->caps = {
  6636. /* .async = */ false,
  6637. /* .host_buffer = */ true,
  6638. /* .buffer_from_host_ptr = */ false,
  6639. /* .events = */ false,
  6640. };
  6641. }
  6642. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  6643. UNUSED(params);
  6644. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6645. return ggml_backend_vk_init(ctx->device);
  6646. }
  6647. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  6648. switch (op->op) {
  6649. case GGML_OP_UNARY:
  6650. switch (ggml_get_unary_op(op)) {
  6651. case GGML_UNARY_OP_GELU:
  6652. case GGML_UNARY_OP_GELU_QUICK:
  6653. case GGML_UNARY_OP_SILU:
  6654. case GGML_UNARY_OP_RELU:
  6655. case GGML_UNARY_OP_TANH:
  6656. return ggml_is_contiguous(op->src[0]);
  6657. default:
  6658. return false;
  6659. }
  6660. break;
  6661. case GGML_OP_MUL_MAT:
  6662. case GGML_OP_MUL_MAT_ID:
  6663. {
  6664. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6665. const vk_device& device = ggml_vk_get_device(ctx->device);
  6666. if (op->op == GGML_OP_MUL_MAT_ID && !device->mul_mat_id_s && !device->mul_mat_id_m && !device->mul_mat_id_l) {
  6667. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  6668. return false;
  6669. }
  6670. switch (op->src[0]->type) {
  6671. case GGML_TYPE_F32:
  6672. case GGML_TYPE_F16:
  6673. case GGML_TYPE_Q4_0:
  6674. case GGML_TYPE_Q4_1:
  6675. case GGML_TYPE_Q5_0:
  6676. case GGML_TYPE_Q5_1:
  6677. case GGML_TYPE_Q8_0:
  6678. case GGML_TYPE_Q2_K:
  6679. case GGML_TYPE_Q3_K:
  6680. case GGML_TYPE_Q4_K:
  6681. case GGML_TYPE_Q5_K:
  6682. case GGML_TYPE_Q6_K:
  6683. case GGML_TYPE_IQ4_NL:
  6684. break;
  6685. default:
  6686. return false;
  6687. }
  6688. struct ggml_tensor * a;
  6689. struct ggml_tensor * b;
  6690. if (op->op == GGML_OP_MUL_MAT) {
  6691. a = op->src[0];
  6692. b = op->src[1];
  6693. } else {
  6694. a = op->src[2];
  6695. b = op->src[1];
  6696. }
  6697. if (a->ne[3] != b->ne[3]) {
  6698. return false;
  6699. }
  6700. if (!(ggml_vk_dim01_contiguous(op->src[0]) || op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) ||
  6701. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  6702. return false;
  6703. }
  6704. return true;
  6705. } break;
  6706. case GGML_OP_FLASH_ATTN_EXT:
  6707. {
  6708. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6709. if (!ggml_vk_get_device(ctx->device)->coopmat2) {
  6710. return false;
  6711. }
  6712. switch (op->src[0]->ne[0]) {
  6713. case 64:
  6714. case 80:
  6715. case 96:
  6716. case 112:
  6717. case 128:
  6718. case 256:
  6719. break;
  6720. default:
  6721. return false;
  6722. }
  6723. if (op->src[0]->type != GGML_TYPE_F32) {
  6724. return false;
  6725. }
  6726. if (op->type != GGML_TYPE_F32) {
  6727. return false;
  6728. }
  6729. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  6730. return false;
  6731. }
  6732. // It's straightforward to support different K/V dequant, but would
  6733. // significantly increase the number of pipelines
  6734. if (op->src[1]->type != op->src[2]->type) {
  6735. return false;
  6736. }
  6737. switch (op->src[1]->type) {
  6738. case GGML_TYPE_F16:
  6739. case GGML_TYPE_Q4_0:
  6740. case GGML_TYPE_Q4_1:
  6741. case GGML_TYPE_Q5_0:
  6742. case GGML_TYPE_Q5_1:
  6743. case GGML_TYPE_Q8_0:
  6744. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  6745. //case GGML_TYPE_Q2_K:
  6746. //case GGML_TYPE_Q3_K:
  6747. //case GGML_TYPE_Q4_K:
  6748. //case GGML_TYPE_Q5_K:
  6749. //case GGML_TYPE_Q6_K:
  6750. case GGML_TYPE_IQ4_NL:
  6751. break;
  6752. default:
  6753. return false;
  6754. }
  6755. return true;
  6756. }
  6757. case GGML_OP_GET_ROWS:
  6758. {
  6759. switch (op->src[0]->type) {
  6760. case GGML_TYPE_F32:
  6761. case GGML_TYPE_F16:
  6762. case GGML_TYPE_Q4_0:
  6763. case GGML_TYPE_Q4_1:
  6764. case GGML_TYPE_Q5_0:
  6765. case GGML_TYPE_Q5_1:
  6766. case GGML_TYPE_Q8_0:
  6767. case GGML_TYPE_IQ4_NL:
  6768. return true;
  6769. default:
  6770. return false;
  6771. }
  6772. } break;
  6773. case GGML_OP_CONT:
  6774. case GGML_OP_CPY:
  6775. case GGML_OP_DUP:
  6776. {
  6777. ggml_type src0_type = op->src[0]->type;
  6778. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  6779. if (src0_type == GGML_TYPE_F32) {
  6780. switch (src1_type) {
  6781. case GGML_TYPE_F32:
  6782. case GGML_TYPE_F16:
  6783. case GGML_TYPE_Q4_0:
  6784. case GGML_TYPE_Q4_1:
  6785. case GGML_TYPE_Q5_0:
  6786. case GGML_TYPE_Q5_1:
  6787. case GGML_TYPE_Q8_0:
  6788. case GGML_TYPE_IQ4_NL:
  6789. return true;
  6790. default:
  6791. break;
  6792. }
  6793. }
  6794. if (src1_type == GGML_TYPE_F32) {
  6795. switch (src0_type) {
  6796. case GGML_TYPE_Q4_0:
  6797. case GGML_TYPE_Q4_1:
  6798. case GGML_TYPE_Q5_0:
  6799. case GGML_TYPE_Q5_1:
  6800. case GGML_TYPE_Q8_0:
  6801. case GGML_TYPE_IQ4_NL:
  6802. return true;
  6803. default:
  6804. break;
  6805. }
  6806. }
  6807. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  6808. return true;
  6809. }
  6810. return false;
  6811. } break;
  6812. case GGML_OP_REPEAT:
  6813. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  6814. case GGML_OP_ROPE:
  6815. {
  6816. const int mode = ((const int32_t *) op->op_params)[2];
  6817. if (mode & GGML_ROPE_TYPE_MROPE) {
  6818. return false;
  6819. }
  6820. if (mode & GGML_ROPE_TYPE_VISION) {
  6821. return false;
  6822. }
  6823. return ggml_is_contiguous(op->src[0]);
  6824. }
  6825. case GGML_OP_NONE:
  6826. case GGML_OP_RESHAPE:
  6827. case GGML_OP_VIEW:
  6828. case GGML_OP_PERMUTE:
  6829. case GGML_OP_TRANSPOSE:
  6830. case GGML_OP_NORM:
  6831. case GGML_OP_GROUP_NORM:
  6832. case GGML_OP_RMS_NORM:
  6833. case GGML_OP_ADD:
  6834. case GGML_OP_ACC:
  6835. case GGML_OP_MUL:
  6836. case GGML_OP_DIV:
  6837. case GGML_OP_CONCAT:
  6838. case GGML_OP_UPSCALE:
  6839. case GGML_OP_SCALE:
  6840. case GGML_OP_SQR:
  6841. case GGML_OP_SIN:
  6842. case GGML_OP_COS:
  6843. case GGML_OP_CLAMP:
  6844. case GGML_OP_PAD:
  6845. case GGML_OP_DIAG_MASK_INF:
  6846. case GGML_OP_SOFT_MAX:
  6847. case GGML_OP_ARGSORT:
  6848. case GGML_OP_SUM_ROWS:
  6849. case GGML_OP_IM2COL:
  6850. case GGML_OP_TIMESTEP_EMBEDDING:
  6851. case GGML_OP_POOL_2D:
  6852. case GGML_OP_RWKV_WKV6:
  6853. case GGML_OP_LEAKY_RELU:
  6854. return true;
  6855. default:
  6856. return false;
  6857. }
  6858. UNUSED(dev);
  6859. }
  6860. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  6861. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  6862. return false;
  6863. }
  6864. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  6865. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  6866. return buft_ctx->device->idx == ctx->device;
  6867. }
  6868. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  6869. const int min_batch_size = 32;
  6870. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  6871. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  6872. UNUSED(dev);
  6873. }
  6874. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  6875. /* .get_name = */ ggml_backend_vk_device_get_name,
  6876. /* .get_description = */ ggml_backend_vk_device_get_description,
  6877. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  6878. /* .get_type = */ ggml_backend_vk_device_get_type,
  6879. /* .get_props = */ ggml_backend_vk_device_get_props,
  6880. /* .init_backend = */ ggml_backend_vk_device_init,
  6881. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  6882. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  6883. /* .buffer_from_host_ptr = */ NULL,
  6884. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  6885. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  6886. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  6887. /* .event_new = */ NULL,
  6888. /* .event_free = */ NULL,
  6889. /* .event_synchronize = */ NULL,
  6890. };
  6891. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  6892. UNUSED(reg);
  6893. return GGML_VK_NAME;
  6894. }
  6895. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  6896. UNUSED(reg);
  6897. return ggml_backend_vk_get_device_count();
  6898. }
  6899. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  6900. static std::vector<ggml_backend_dev_t> devices;
  6901. static bool initialized = false;
  6902. {
  6903. static std::mutex mutex;
  6904. std::lock_guard<std::mutex> lock(mutex);
  6905. if (!initialized) {
  6906. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  6907. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  6908. char desc[256];
  6909. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  6910. ctx->device = i;
  6911. ctx->name = GGML_VK_NAME + std::to_string(i);
  6912. ctx->description = desc;
  6913. devices.push_back(new ggml_backend_device {
  6914. /* .iface = */ ggml_backend_vk_device_i,
  6915. /* .reg = */ reg,
  6916. /* .context = */ ctx,
  6917. });
  6918. }
  6919. initialized = true;
  6920. }
  6921. }
  6922. GGML_ASSERT(device < devices.size());
  6923. return devices[device];
  6924. }
  6925. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  6926. /* .get_name = */ ggml_backend_vk_reg_get_name,
  6927. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  6928. /* .get_device = */ ggml_backend_vk_reg_get_device,
  6929. /* .get_proc_address = */ NULL,
  6930. };
  6931. ggml_backend_reg_t ggml_backend_vk_reg() {
  6932. static ggml_backend_reg reg = {
  6933. /* .api_version = */ GGML_BACKEND_API_VERSION,
  6934. /* .iface = */ ggml_backend_vk_reg_i,
  6935. /* .context = */ nullptr,
  6936. };
  6937. return &reg;
  6938. }
  6939. // Extension availability
  6940. static bool ggml_vk_instance_validation_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  6941. #ifdef GGML_VULKAN_VALIDATE
  6942. bool portability_enumeration_ext = false;
  6943. // Check for portability enumeration extension for MoltenVK support
  6944. for (const auto& properties : instance_extensions) {
  6945. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  6946. return true;
  6947. }
  6948. }
  6949. if (!portability_enumeration_ext) {
  6950. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  6951. }
  6952. #endif
  6953. return false;
  6954. UNUSED(instance_extensions);
  6955. }
  6956. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  6957. #ifdef __APPLE__
  6958. bool portability_enumeration_ext = false;
  6959. // Check for portability enumeration extension for MoltenVK support
  6960. for (const auto& properties : instance_extensions) {
  6961. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  6962. return true;
  6963. }
  6964. }
  6965. if (!portability_enumeration_ext) {
  6966. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  6967. }
  6968. #endif
  6969. return false;
  6970. UNUSED(instance_extensions);
  6971. }
  6972. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props) {
  6973. switch (props.vendorID) {
  6974. case VK_VENDOR_ID_INTEL:
  6975. // Intel drivers don't support coopmat properly yet
  6976. return false;
  6977. case VK_VENDOR_ID_AMD:
  6978. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  6979. // Workaround for AMD proprietary driver reporting support on all GPUs
  6980. const std::string name = props.deviceName;
  6981. return name.rfind("AMD Radeon RX 7", 0) == 0 || name.rfind("AMD Radeon(TM) RX 7", 0) == 0 || // RDNA 3 consumer GPUs
  6982. name.rfind("AMD Radeon PRO W7", 0) == 0 || name.rfind("AMD Radeon(TM) PRO W7", 0) == 0 || // RDNA 3 workstation GPUs
  6983. name.rfind("AMD Radeon 7", 0) == 0 || name.rfind("AMD Radeon(TM) 7", 0) == 0; // RDNA 3 APUs
  6984. }
  6985. return true;
  6986. default:
  6987. return true;
  6988. }
  6989. }
  6990. // checks
  6991. #ifdef GGML_VULKAN_CHECK_RESULTS
  6992. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  6993. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  6994. return;
  6995. }
  6996. for (int j = 0; j < level; j++) {
  6997. std::cerr << " ";
  6998. }
  6999. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  7000. done.push_back(tensor);
  7001. for (int i = 0; i < GGML_MAX_SRC; i++) {
  7002. if (tensor->src[i] != nullptr) {
  7003. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  7004. }
  7005. }
  7006. }
  7007. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  7008. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  7009. return;
  7010. }
  7011. i0 = std::max(i0, 5);
  7012. i1 = std::max(i1, 5);
  7013. i2 = std::max(i2, 0);
  7014. i3 = std::max(i3, 0);
  7015. fprintf(stderr, " ");
  7016. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  7017. fprintf(stderr, "%7d ", idx1);
  7018. }
  7019. fprintf(stderr, "\n");
  7020. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  7021. fprintf(stderr, "%7d: ", idx0);
  7022. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  7023. 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]) {
  7024. float val;
  7025. if (tensor->type == GGML_TYPE_F32) {
  7026. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  7027. } else if (tensor->type == GGML_TYPE_F16) {
  7028. 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]));
  7029. } else if (tensor->type == GGML_TYPE_I32) {
  7030. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  7031. } else {
  7032. GGML_ABORT("fatal error");
  7033. }
  7034. fprintf(stderr, "% 7.2f ", val);
  7035. } else {
  7036. fprintf(stderr, " ");
  7037. }
  7038. }
  7039. fprintf(stderr, "\n");
  7040. }
  7041. }
  7042. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  7043. void * tensor_data = tensor->data;
  7044. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  7045. if (is_gpu) {
  7046. const size_t tensor_size = ggml_nbytes(tensor);
  7047. tensor_data = malloc(tensor_size);
  7048. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  7049. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  7050. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  7051. }
  7052. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  7053. 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;
  7054. if (tensor->src[0] != nullptr) {
  7055. 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;
  7056. }
  7057. if (tensor->src[1] != nullptr) {
  7058. 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;
  7059. }
  7060. std::cerr << std::endl << "Result:" << std::endl;
  7061. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  7062. std::cerr << std::endl;
  7063. std::vector<const ggml_tensor *> done;
  7064. ggml_vk_print_graph_origin(tensor, done);
  7065. if (is_gpu) {
  7066. free(tensor_data);
  7067. }
  7068. }
  7069. void * comp_result;
  7070. size_t comp_size;
  7071. size_t comp_nb[GGML_MAX_DIMS];
  7072. size_t check_counter = 0;
  7073. static void ggml_vk_check_results_0(ggml_tensor * tensor) {
  7074. if (tensor->op == GGML_OP_TRANSPOSE) {
  7075. return;
  7076. }
  7077. check_counter++;
  7078. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  7079. return;
  7080. }
  7081. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  7082. ggml_tensor * src0 = tensor->src[0];
  7083. ggml_tensor * src1 = tensor->src[1];
  7084. ggml_tensor * src2 = tensor->src[2];
  7085. ggml_tensor * src3 = tensor->src[3];
  7086. struct ggml_init_params iparams = {
  7087. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  7088. /*.mem_buffer =*/ NULL,
  7089. /*.no_alloc =*/ false,
  7090. };
  7091. struct ggml_context * ggml_ctx = ggml_init(iparams);
  7092. struct ggml_tensor * src0_clone = nullptr;
  7093. struct ggml_tensor * src1_clone = nullptr;
  7094. struct ggml_tensor * src2_clone = nullptr;
  7095. struct ggml_tensor * src3_clone = nullptr;
  7096. struct ggml_tensor * tensor_clone = nullptr;
  7097. size_t src0_size;
  7098. size_t src1_size;
  7099. size_t src2_size;
  7100. size_t src3_size;
  7101. void * src0_buffer = nullptr;
  7102. void * src1_buffer = nullptr;
  7103. void * src2_buffer = nullptr;
  7104. void * src3_buffer = nullptr;
  7105. if (src0 != nullptr) {
  7106. src0_clone = ggml_dup_tensor(ggml_ctx, src0);
  7107. src0_size = ggml_nbytes(src0);
  7108. src0_buffer = malloc(src0_size);
  7109. src0_clone->data = src0_buffer;
  7110. if (ggml_backend_buffer_is_host(src0->buffer)) {
  7111. memcpy(src0_clone->data, src0->data, src0_size);
  7112. memcpy(src0_clone->nb, src0->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7113. } else if (ggml_backend_buffer_is_vk(src0->buffer)) {
  7114. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  7115. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  7116. uint64_t offset = vk_tensor_offset(src0) + src0->view_offs;
  7117. if (!ggml_is_contiguous(src0) && ggml_vk_dim01_contiguous(src0)) {
  7118. for (int i3 = 0; i3 < src0->ne[3]; i3++) {
  7119. for (int i2 = 0; i2 < src0->ne[2]; i2++) {
  7120. const int idx = i3*src0->ne[2] + i2;
  7121. ggml_vk_buffer_read(buffer_gpu, offset + idx * src0->nb[2], ((char *)src0_clone->data + idx * src0_clone->nb[2]), src0->ne[1] * src0->nb[1]);
  7122. }
  7123. }
  7124. src0_clone->nb[0] = src0->nb[0];
  7125. src0_clone->nb[1] = src0->nb[1];
  7126. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  7127. src0_clone->nb[i] = src0_clone->nb[i - 1]*src0_clone->ne[i - 1];
  7128. }
  7129. } else {
  7130. if (offset + src0_size >= buffer_gpu->size) {
  7131. src0_size = buffer_gpu->size - offset;
  7132. }
  7133. ggml_vk_buffer_read(buffer_gpu, offset, src0_clone->data, src0_size);
  7134. memcpy(src0_clone->nb, src0->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7135. }
  7136. } else {
  7137. GGML_ABORT("fatal error");
  7138. }
  7139. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  7140. ggml_vk_print_tensor(src0, "src0");
  7141. }
  7142. }
  7143. if (src1 != nullptr) {
  7144. src1_clone = ggml_dup_tensor(ggml_ctx, src1);
  7145. src1_size = ggml_nbytes(src1);
  7146. src1_buffer = malloc(src1_size);
  7147. src1_clone->data = src1_buffer;
  7148. if (ggml_backend_buffer_is_host(src1->buffer)) {
  7149. memcpy(src1_clone->data, src1->data, src1_size);
  7150. memcpy(src1_clone->nb, src1->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7151. } else if (ggml_backend_buffer_is_vk(src1->buffer)) {
  7152. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  7153. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  7154. uint64_t offset = vk_tensor_offset(src1) + src1->view_offs;
  7155. if (!ggml_is_contiguous(src1) && ggml_vk_dim01_contiguous(src1)) {
  7156. for (int i3 = 0; i3 < src1->ne[3]; i3++) {
  7157. for (int i2 = 0; i2 < src1->ne[2]; i2++) {
  7158. const int idx = i3*src1->ne[2] + i2;
  7159. ggml_vk_buffer_read(buffer_gpu, offset + idx * src1->nb[2], ((char *)src1_clone->data + idx * src1_clone->nb[2]), src1->ne[1] * src1->nb[1]);
  7160. }
  7161. }
  7162. src1_clone->nb[0] = src1->nb[0];
  7163. src1_clone->nb[1] = src1->nb[1];
  7164. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  7165. src1_clone->nb[i] = src1_clone->nb[i - 1]*src1_clone->ne[i - 1];
  7166. }
  7167. } else {
  7168. if (offset + src1_size >= buffer_gpu->size) {
  7169. src1_size = buffer_gpu->size - offset;
  7170. }
  7171. ggml_vk_buffer_read(buffer_gpu, offset, src1_clone->data, src1_size);
  7172. memcpy(src1_clone->nb, src1->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7173. }
  7174. } else {
  7175. GGML_ABORT("fatal error");
  7176. }
  7177. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  7178. ggml_vk_print_tensor(src1, "src1");
  7179. }
  7180. }
  7181. if (src2 != nullptr) {
  7182. src2_clone = ggml_dup_tensor(ggml_ctx, src2);
  7183. src2_size = ggml_nbytes(src2);
  7184. src2_buffer = malloc(src2_size);
  7185. src2_clone->data = src2_buffer;
  7186. if (ggml_backend_buffer_is_host(src2->buffer)) {
  7187. memcpy(src2_clone->data, src2->data, src2_size);
  7188. memcpy(src2_clone->nb, src2->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7189. } else if (ggml_backend_buffer_is_vk(src2->buffer)) {
  7190. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src2->buffer->context;
  7191. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  7192. uint64_t offset = vk_tensor_offset(src2) + src2->view_offs;
  7193. if (!ggml_is_contiguous(src2) && ggml_vk_dim01_contiguous(src2)) {
  7194. for (int i3 = 0; i3 < src2->ne[3]; i3++) {
  7195. for (int i2 = 0; i2 < src2->ne[2]; i2++) {
  7196. const int idx = i3*src2->ne[2] + i2;
  7197. ggml_vk_buffer_read(buffer_gpu, offset + idx * src2->nb[2], ((char *)src2_clone->data + idx * src2_clone->nb[2]), src2->ne[1] * src2->nb[1]);
  7198. }
  7199. }
  7200. src2_clone->nb[0] = src2->nb[0];
  7201. src2_clone->nb[1] = src2->nb[1];
  7202. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  7203. src2_clone->nb[i] = src2_clone->nb[i - 1]*src2_clone->ne[i - 1];
  7204. }
  7205. } else {
  7206. if (offset + src2_size >= buffer_gpu->size) {
  7207. src2_size = buffer_gpu->size - offset;
  7208. }
  7209. ggml_vk_buffer_read(buffer_gpu, offset, src2_clone->data, src2_size);
  7210. memcpy(src2_clone->nb, src2->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7211. }
  7212. } else {
  7213. GGML_ABORT("fatal error");
  7214. }
  7215. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  7216. ggml_vk_print_tensor(src2, "src2");
  7217. }
  7218. }
  7219. if (src3 != nullptr) {
  7220. src3_clone = ggml_dup_tensor(ggml_ctx, src3);
  7221. src3_size = ggml_nbytes(src3);
  7222. src3_buffer = malloc(src3_size);
  7223. src3_clone->data = src3_buffer;
  7224. if (ggml_backend_buffer_is_host(src3->buffer)) {
  7225. memcpy(src3_clone->data, src3->data, src3_size);
  7226. memcpy(src3_clone->nb, src3->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7227. } else if (ggml_backend_buffer_is_vk(src3->buffer)) {
  7228. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)src3->buffer->context;
  7229. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  7230. uint64_t offset = vk_tensor_offset(src3) + src3->view_offs;
  7231. if (!ggml_is_contiguous(src3) && ggml_vk_dim01_contiguous(src3)) {
  7232. for (int i3 = 0; i3 < src3->ne[3]; i3++) {
  7233. for (int i2 = 0; i2 < src3->ne[2]; i2++) {
  7234. const int idx = i3*src3->ne[2] + i2;
  7235. ggml_vk_buffer_read(buffer_gpu, offset + idx * src3->nb[2], ((char *)src3_clone->data + idx * src3_clone->nb[2]), src3->ne[1] * src3->nb[1]);
  7236. }
  7237. }
  7238. src3_clone->nb[0] = src3->nb[0];
  7239. src3_clone->nb[1] = src3->nb[1];
  7240. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  7241. src3_clone->nb[i] = src3_clone->nb[i - 1]*src3_clone->ne[i - 1];
  7242. }
  7243. } else {
  7244. if (offset + src3_size >= buffer_gpu->size) {
  7245. src3_size = buffer_gpu->size - offset;
  7246. }
  7247. ggml_vk_buffer_read(buffer_gpu, offset, src3_clone->data, src3_size);
  7248. memcpy(src3_clone->nb, src3->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7249. }
  7250. } else {
  7251. GGML_ABORT("fatal error");
  7252. }
  7253. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  7254. ggml_vk_print_tensor(src3, "src3");
  7255. }
  7256. }
  7257. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  7258. const float *params = (const float *)tensor->op_params;
  7259. tensor_clone = ggml_flash_attn_ext(ggml_ctx, src0_clone, src1_clone, src2_clone, src3_clone, params[0], params[1], params[2]);
  7260. } else if (tensor->op == GGML_OP_MUL_MAT) {
  7261. tensor_clone = ggml_mul_mat(ggml_ctx, src0_clone, src1_clone);
  7262. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  7263. tensor_clone = ggml_mul_mat_id(ggml_ctx, src0_clone, src1_clone, src2_clone);
  7264. } else if (tensor->op == GGML_OP_MUL) {
  7265. tensor_clone = ggml_mul(ggml_ctx, src0_clone, src1_clone);
  7266. } else if (tensor->op == GGML_OP_DIV) {
  7267. tensor_clone = ggml_div(ggml_ctx, src0_clone, src1_clone);
  7268. } else if (tensor->op == GGML_OP_CONCAT) {
  7269. tensor_clone = ggml_concat(ggml_ctx, src0_clone, src1_clone, *(int *)tensor->op_params);
  7270. } else if (tensor->op == GGML_OP_UPSCALE) {
  7271. tensor_clone = ggml_upscale_ext(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  7272. } else if (tensor->op == GGML_OP_SCALE) {
  7273. tensor_clone = ggml_scale(ggml_ctx, src0_clone, ((float *)tensor->op_params)[0]);
  7274. } else if (tensor->op == GGML_OP_SQR) {
  7275. tensor_clone = ggml_sqr(ggml_ctx, src0_clone);
  7276. } else if (tensor->op == GGML_OP_SIN) {
  7277. tensor_clone = ggml_sin(ggml_ctx, src0_clone);
  7278. } else if (tensor->op == GGML_OP_COS) {
  7279. tensor_clone = ggml_cos(ggml_ctx, src0_clone);
  7280. } else if (tensor->op == GGML_OP_CLAMP) {
  7281. tensor_clone = ggml_clamp(ggml_ctx, src0_clone, ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]);
  7282. } else if (tensor->op == GGML_OP_PAD) {
  7283. tensor_clone = ggml_pad(ggml_ctx, src0_clone, tensor->ne[0] - src0_clone->ne[0], tensor->ne[1] - src0_clone->ne[1], tensor->ne[2] - src0_clone->ne[2], tensor->ne[3] - src0_clone->ne[3]);
  7284. } else if (tensor->op == GGML_OP_REPEAT) {
  7285. tensor_clone = ggml_repeat(ggml_ctx, src0_clone, tensor);
  7286. } else if (tensor->op == GGML_OP_ADD) {
  7287. tensor_clone = ggml_add(ggml_ctx, src0_clone, src1_clone);
  7288. } else if (tensor->op == GGML_OP_ACC) {
  7289. tensor_clone = ggml_acc(ggml_ctx, src0_clone, src1_clone, tensor->op_params[0], tensor->op_params[1], tensor->op_params[2], tensor->op_params[3]);
  7290. } else if (tensor->op == GGML_OP_NORM) {
  7291. tensor_clone = ggml_norm(ggml_ctx, src0_clone, *(float *)tensor->op_params);
  7292. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  7293. tensor_clone = ggml_group_norm(ggml_ctx, src0_clone, *(int *)tensor->op_params, ((float *)tensor->op_params)[1]);
  7294. } else if (tensor->op == GGML_OP_RMS_NORM) {
  7295. tensor_clone = ggml_rms_norm(ggml_ctx, src0_clone, *(float *)tensor->op_params);
  7296. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  7297. if (src1 != nullptr) {
  7298. tensor_clone = ggml_soft_max_ext(ggml_ctx, src0_clone, src1_clone, ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]);
  7299. } else {
  7300. tensor_clone = ggml_soft_max(ggml_ctx, src0_clone);
  7301. }
  7302. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  7303. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src0_clone, *(int *)tensor->op_params);
  7304. } else if (tensor->op == GGML_OP_ROPE) {
  7305. const int n_dims = ((int32_t *) tensor->op_params)[1];
  7306. const int mode = ((int32_t *) tensor->op_params)[2];
  7307. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  7308. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  7309. const float freq_base = ((float *) tensor->op_params)[5];
  7310. const float freq_scale = ((float *) tensor->op_params)[6];
  7311. const float ext_factor = ((float *) tensor->op_params)[7];
  7312. const float attn_factor = ((float *) tensor->op_params)[8];
  7313. const float beta_fast = ((float *) tensor->op_params)[9];
  7314. const float beta_slow = ((float *) tensor->op_params)[10];
  7315. tensor_clone = ggml_rope_ext(ggml_ctx, src0_clone, src1_clone, src2_clone, n_dims, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  7316. } else if (tensor->op == GGML_OP_UNARY) {
  7317. switch (ggml_get_unary_op(tensor)) {
  7318. case GGML_UNARY_OP_SILU:
  7319. tensor_clone = ggml_silu(ggml_ctx, src0_clone);
  7320. break;
  7321. case GGML_UNARY_OP_GELU:
  7322. tensor_clone = ggml_gelu(ggml_ctx, src0_clone);
  7323. break;
  7324. case GGML_UNARY_OP_GELU_QUICK:
  7325. tensor_clone = ggml_gelu_quick(ggml_ctx, src0_clone);
  7326. break;
  7327. case GGML_UNARY_OP_RELU:
  7328. tensor_clone = ggml_relu(ggml_ctx, src0_clone);
  7329. break;
  7330. case GGML_UNARY_OP_TANH:
  7331. tensor_clone = ggml_tanh(ggml_ctx, src0_clone);
  7332. break;
  7333. default:
  7334. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  7335. GGML_ABORT("fatal error");
  7336. }
  7337. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  7338. if (src1 == nullptr) {
  7339. tensor_clone = ggml_dup(ggml_ctx, src0_clone);
  7340. tensor_clone->type = tensor->type;
  7341. } else {
  7342. tensor_clone = ggml_cpy(ggml_ctx, src0_clone, src1_clone);
  7343. }
  7344. } else if (tensor->op == GGML_OP_CONT) {
  7345. tensor_clone = ggml_cont_4d(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  7346. } else if (tensor->op == GGML_OP_RESHAPE) {
  7347. tensor_clone = ggml_reshape_4d(ggml_ctx, src0_clone, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  7348. } else if (tensor->op == GGML_OP_VIEW) {
  7349. tensor_clone = ggml_view_4d(ggml_ctx, src0_clone, 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]);
  7350. } else if (tensor->op == GGML_OP_PERMUTE) {
  7351. int32_t * params = (int32_t *)tensor->op_params;
  7352. tensor_clone = ggml_permute(ggml_ctx, src0_clone, params[0], params[1], params[2], params[3]);
  7353. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  7354. tensor_clone = ggml_transpose(ggml_ctx, src0_clone);
  7355. } else if (tensor->op == GGML_OP_GET_ROWS) {
  7356. tensor_clone = ggml_get_rows(ggml_ctx, src0_clone, src1_clone);
  7357. } else if (tensor->op == GGML_OP_ARGSORT) {
  7358. tensor_clone = ggml_argsort(ggml_ctx, src0_clone, (ggml_sort_order) *(int *)tensor->op_params);
  7359. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  7360. tensor_clone = ggml_sum_rows(ggml_ctx, src0_clone);
  7361. } else if (tensor->op == GGML_OP_IM2COL) {
  7362. const int32_t s0 = tensor->op_params[0];
  7363. const int32_t s1 = tensor->op_params[1];
  7364. const int32_t p0 = tensor->op_params[2];
  7365. const int32_t p1 = tensor->op_params[3];
  7366. const int32_t d0 = tensor->op_params[4];
  7367. const int32_t d1 = tensor->op_params[5];
  7368. const bool is_2D = tensor->op_params[6] == 1;
  7369. tensor_clone = ggml_im2col(ggml_ctx, src0_clone, src1_clone, s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  7370. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  7371. const int32_t dim = tensor->op_params[0];
  7372. const int32_t max_period = tensor->op_params[1];
  7373. tensor_clone = ggml_timestep_embedding(ggml_ctx, src0_clone, dim, max_period);
  7374. } else if (tensor->op == GGML_OP_POOL_2D) {
  7375. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  7376. const int32_t k0 = tensor->op_params[1];
  7377. const int32_t k1 = tensor->op_params[2];
  7378. const int32_t s0 = tensor->op_params[3];
  7379. const int32_t s1 = tensor->op_params[4];
  7380. const int32_t p0 = tensor->op_params[5];
  7381. const int32_t p1 = tensor->op_params[6];
  7382. tensor_clone = ggml_pool_2d(ggml_ctx, src0_clone, op, k0, k1, s0, s1, p0, p1);
  7383. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  7384. const float * op_params = (const float *)tensor->op_params;
  7385. tensor_clone = ggml_leaky_relu(ggml_ctx, src0_clone, op_params[0], false);
  7386. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  7387. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, tensor->src[0], tensor->src[1], tensor->src[2], tensor->src[3],
  7388. tensor->src[4], tensor->src[5]);
  7389. }
  7390. else {
  7391. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  7392. GGML_ABORT("fatal error");
  7393. }
  7394. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  7395. ggml_build_forward_expand(cgraph, tensor_clone);
  7396. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 8);
  7397. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  7398. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  7399. }
  7400. comp_size = ggml_nbytes(tensor_clone);
  7401. comp_result = malloc(comp_size);
  7402. memcpy(comp_result, tensor_clone->data, comp_size);
  7403. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  7404. if (src0 != nullptr) {
  7405. free(src0_buffer);
  7406. }
  7407. if (src1 != nullptr) {
  7408. free(src1_buffer);
  7409. }
  7410. ggml_free(ggml_ctx);
  7411. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  7412. }
  7413. static void ggml_vk_check_results_1(ggml_tensor * tensor) {
  7414. if (tensor->op == GGML_OP_TRANSPOSE) {
  7415. return;
  7416. }
  7417. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  7418. return;
  7419. }
  7420. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  7421. ggml_tensor * src0 = tensor->src[0];
  7422. ggml_tensor * src1 = tensor->src[1];
  7423. ggml_tensor * src2 = tensor->src[2];
  7424. ggml_tensor * src3 = tensor->src[3];
  7425. void * tensor_data = tensor->data;
  7426. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  7427. size_t tensor_size = ggml_nbytes(tensor);
  7428. tensor_data = malloc(tensor_size);
  7429. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  7430. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  7431. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  7432. if (offset + tensor_size >= buffer_gpu->size) {
  7433. tensor_size = buffer_gpu->size - offset;
  7434. }
  7435. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  7436. }
  7437. float first_error_result = -1.0f;
  7438. float first_error_correct = -1.0f;
  7439. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  7440. double avg_err = 0.0;
  7441. size_t counter = 0;
  7442. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  7443. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  7444. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  7445. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  7446. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  7447. float correct = 0.0f;
  7448. float result = 0.0f;
  7449. if (buffer_size_fit) {
  7450. if (tensor->type == GGML_TYPE_F32) {
  7451. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  7452. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  7453. } else if (tensor->type == GGML_TYPE_F16) {
  7454. 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]));
  7455. 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]));
  7456. } else if (tensor->type == GGML_TYPE_I32) {
  7457. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  7458. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  7459. } else {
  7460. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  7461. }
  7462. } else {
  7463. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  7464. GGML_ABORT("fatal error");
  7465. }
  7466. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  7467. 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;
  7468. 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;
  7469. if (src0 != nullptr) {
  7470. 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;
  7471. }
  7472. if (src1 != nullptr) {
  7473. 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;
  7474. }
  7475. if (src2 != nullptr) {
  7476. 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;
  7477. }
  7478. if (src3 != nullptr) {
  7479. 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;
  7480. }
  7481. 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;
  7482. std::cerr << std::endl << "Result:" << std::endl;
  7483. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  7484. std::cerr << std::endl << "Correct:" << std::endl;
  7485. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  7486. std::cerr << std::endl;
  7487. std::vector<const ggml_tensor *> done;
  7488. ggml_vk_print_graph_origin(tensor, done);
  7489. GGML_ABORT("fatal error");
  7490. }
  7491. if (first_error[0] == -1 && std::fabs(correct - result) > 0.1f) {
  7492. first_error[0] = i0;
  7493. first_error[1] = i1;
  7494. first_error[2] = i2;
  7495. first_error[3] = i3;
  7496. first_error_result = result;
  7497. first_error_correct = correct;
  7498. }
  7499. // Special case, value is infinite, avoid NaN result in avg_err
  7500. // NaN also appears in results, if both are nan error is 0
  7501. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  7502. avg_err += std::fabs(correct - result);
  7503. }
  7504. counter++;
  7505. }
  7506. }
  7507. }
  7508. }
  7509. avg_err /= counter;
  7510. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  7511. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  7512. 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;
  7513. if (src0 != nullptr) {
  7514. 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;
  7515. }
  7516. if (src1 != nullptr) {
  7517. 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;
  7518. }
  7519. if (src2 != nullptr) {
  7520. 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;
  7521. }
  7522. if (src3 != nullptr) {
  7523. 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;
  7524. }
  7525. 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;
  7526. std::cerr << std::endl << "Result:" << std::endl;
  7527. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  7528. std::cerr << std::endl << "Correct:" << std::endl;
  7529. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  7530. std::cerr << std::endl;
  7531. std::vector<const ggml_tensor *> done;
  7532. ggml_vk_print_graph_origin(tensor, done);
  7533. }
  7534. if (avg_err > 0.05 || std::isnan(avg_err)) {
  7535. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  7536. 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;
  7537. if (src0 != nullptr) {
  7538. 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;
  7539. }
  7540. if (src1 != nullptr) {
  7541. 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;
  7542. }
  7543. if (src2 != nullptr) {
  7544. 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;
  7545. }
  7546. if (src3 != nullptr) {
  7547. 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;
  7548. }
  7549. 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;
  7550. std::cerr << std::endl << "Result:" << std::endl;
  7551. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  7552. std::cerr << std::endl << "Correct:" << std::endl;
  7553. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  7554. std::cerr << std::endl;
  7555. std::vector<const ggml_tensor *> done;
  7556. ggml_vk_print_graph_origin(tensor, done);
  7557. GGML_ABORT("fatal error");
  7558. } else {
  7559. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  7560. }
  7561. free(comp_result);
  7562. comp_result = nullptr;
  7563. comp_size = 0;
  7564. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  7565. free(tensor_data);
  7566. }
  7567. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  7568. }
  7569. #endif
  7570. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)