ggml-vulkan.cpp 675 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645
  1. #include "ggml-vulkan.h"
  2. #include <vulkan/vulkan_core.h>
  3. #if defined(GGML_VULKAN_RUN_TESTS) || defined(GGML_VULKAN_CHECK_RESULTS)
  4. #include <chrono>
  5. #include "ggml-cpu.h"
  6. #endif
  7. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  8. #define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
  9. #include <vulkan/vulkan.hpp>
  10. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  11. VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
  12. #include <algorithm>
  13. #include <cmath>
  14. #include <iomanip>
  15. #include <iostream>
  16. #include <tuple>
  17. #include <vector>
  18. #include <sstream>
  19. #include <utility>
  20. #include <memory>
  21. #include <limits>
  22. #include <map>
  23. #include <unordered_map>
  24. #include <memory>
  25. #include <mutex>
  26. #include <future>
  27. #include <thread>
  28. #if defined(_MSC_VER)
  29. # define NOMINMAX 1
  30. # include <windows.h>
  31. # define YIELD() YieldProcessor()
  32. #elif defined(__clang__) || defined(__GNUC__)
  33. # if defined(__x86_64__) ||defined(__i386__)
  34. # include <immintrin.h>
  35. # define YIELD() _mm_pause()
  36. # elif defined(__arm__) || defined(__aarch64__)
  37. # if defined(__clang__)
  38. # include <arm_acle.h>
  39. # define YIELD() __yield()
  40. # else
  41. # define YIELD() asm volatile("yield")
  42. # endif
  43. # endif
  44. #endif
  45. #if !defined(YIELD)
  46. #define YIELD()
  47. #endif
  48. #include "ggml-impl.h"
  49. #include "ggml-backend-impl.h"
  50. #include "ggml-vulkan-shaders.hpp"
  51. // remove this once it's more widely available in the SDK
  52. #if !defined(VK_KHR_shader_bfloat16)
  53. #define VK_KHR_shader_bfloat16 1
  54. #define VK_KHR_SHADER_BFLOAT16_SPEC_VERSION 1
  55. #define VK_KHR_SHADER_BFLOAT16_EXTENSION_NAME "VK_KHR_shader_bfloat16"
  56. #define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR ((VkStructureType)1000141000)
  57. #define VK_COMPONENT_TYPE_BFLOAT16_KHR ((VkComponentTypeKHR)1000141000)
  58. typedef struct VkPhysicalDeviceShaderBfloat16FeaturesKHR {
  59. VkStructureType sType;
  60. void* pNext;
  61. VkBool32 shaderBFloat16Type;
  62. VkBool32 shaderBFloat16DotProduct;
  63. VkBool32 shaderBFloat16CooperativeMatrix;
  64. } VkPhysicalDeviceShaderBfloat16FeaturesKHR;
  65. #endif
  66. #define ROUNDUP_POW2(M, N) (((M) + (N) - 1) & ~((N) - 1))
  67. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  68. static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; }
  69. #define VK_VENDOR_ID_AMD 0x1002
  70. #define VK_VENDOR_ID_APPLE 0x106b
  71. #define VK_VENDOR_ID_INTEL 0x8086
  72. #define VK_VENDOR_ID_NVIDIA 0x10de
  73. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 256
  74. #define GGML_VK_MAX_NODES 8192
  75. #define MAX_VK_BUFFERS 256
  76. #define VK_CHECK(err, msg) \
  77. do { \
  78. vk::Result err_ = (err); \
  79. if (err_ != vk::Result::eSuccess) { \
  80. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  81. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  82. exit(1); \
  83. } \
  84. } while (0)
  85. #ifdef GGML_VULKAN_DEBUG
  86. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  87. #else
  88. #define VK_LOG_DEBUG(msg) ((void) 0)
  89. #endif // GGML_VULKAN_DEBUG
  90. struct ggml_backend_vk_context;
  91. #define MAX_PARAMETER_COUNT 12
  92. // Max number of adds that can be fused without exceeding MAX_PARAMETER_COUNT.
  93. #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3)
  94. struct vk_pipeline_struct {
  95. std::string name;
  96. vk::ShaderModule shader_module;
  97. vk::PipelineLayout layout;
  98. vk::Pipeline pipeline;
  99. uint32_t push_constant_size;
  100. uint32_t parameter_count;
  101. std::array<uint32_t, 3> wg_denoms;
  102. uint32_t align;
  103. // true if fields have been set by ggml_vk_create_pipeline
  104. bool initialized {};
  105. // set to true to request the pipeline is compiled after the dryrun
  106. bool needed {};
  107. // set to true when the shader has been compiled
  108. bool compiled {};
  109. // number of registers used, extracted from pipeline executable properties
  110. uint32_t register_count {};
  111. };
  112. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  113. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  114. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  115. struct vk_matmul_pipeline_struct {
  116. vk_pipeline l, m, s;
  117. vk_pipeline a_l, a_m, a_s;
  118. };
  119. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  120. struct vk_matmul_pipeline2 {
  121. vk_matmul_pipeline2() {
  122. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  123. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  124. }
  125. vk_matmul_pipeline f32acc;
  126. vk_matmul_pipeline f16acc;
  127. };
  128. struct vk_device_struct;
  129. typedef std::shared_ptr<vk_device_struct> vk_device;
  130. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  131. struct vk_buffer_struct;
  132. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  133. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  134. struct ggml_backend_vk_buffer_type_context {
  135. std::string name;
  136. vk_device device;
  137. };
  138. struct vk_queue;
  139. // Stores command pool/buffers. There's an instance of this
  140. // for each (context,queue) pair and for each (device,queue) pair.
  141. struct vk_command_pool {
  142. void init(vk_device& device, vk_queue *q_);
  143. void destroy(vk::Device& device);
  144. vk::CommandPool pool;
  145. uint32_t cmd_buffer_idx;
  146. std::vector<vk::CommandBuffer> cmd_buffers;
  147. vk_queue *q;
  148. };
  149. // Prevent simultaneous submissions to the same queue.
  150. // This could be per vk_queue if we stopped having two vk_queue structures
  151. // sharing the same vk::Queue.
  152. static std::mutex queue_mutex;
  153. struct vk_queue {
  154. uint32_t queue_family_index;
  155. vk::Queue queue;
  156. vk_command_pool cmd_pool;
  157. vk::PipelineStageFlags stage_flags;
  158. bool transfer_only;
  159. // copy everything except the cmd_pool
  160. void copyFrom(vk_queue &other) {
  161. queue_family_index = other.queue_family_index;
  162. queue = other.queue;
  163. stage_flags = other.stage_flags;
  164. transfer_only = other.transfer_only;
  165. }
  166. };
  167. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  168. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  169. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  170. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  171. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  172. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  173. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  174. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  175. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  176. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  177. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  178. /* .is_host = */ NULL,
  179. };
  180. #ifdef GGML_VULKAN_MEMORY_DEBUG
  181. class vk_memory_logger;
  182. #endif
  183. class vk_perf_logger;
  184. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  185. static constexpr uint32_t mul_mat_vec_max_cols = 8;
  186. static constexpr uint32_t p021_max_gqa_ratio = 8;
  187. enum vk_device_architecture {
  188. OTHER,
  189. AMD_GCN,
  190. AMD_RDNA1,
  191. AMD_RDNA2,
  192. AMD_RDNA3,
  193. INTEL_XE2,
  194. NVIDIA_PRE_TURING,
  195. };
  196. static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) {
  197. vk::PhysicalDeviceProperties props = device.getProperties();
  198. if (props.vendorID == VK_VENDOR_ID_AMD) {
  199. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  200. bool amd_shader_core_properties = false;
  201. bool integer_dot_product = false;
  202. bool subgroup_size_control = false;
  203. for (const auto& properties : ext_props) {
  204. if (strcmp("VK_AMD_shader_core_properties", properties.extensionName) == 0) {
  205. amd_shader_core_properties = true;
  206. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0) {
  207. integer_dot_product = true;
  208. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  209. subgroup_size_control = true;
  210. }
  211. }
  212. if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) {
  213. return vk_device_architecture::OTHER;
  214. }
  215. vk::PhysicalDeviceProperties2 props2;
  216. vk::PhysicalDeviceShaderCorePropertiesAMD shader_core_props_amd;
  217. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR integer_dot_props;
  218. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  219. props2.pNext = &shader_core_props_amd;
  220. shader_core_props_amd.pNext = &integer_dot_props;
  221. integer_dot_props.pNext = &subgroup_size_control_props;
  222. device.getProperties2(&props2);
  223. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 64) {
  224. return vk_device_architecture::AMD_GCN;
  225. }
  226. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 32) {
  227. // RDNA
  228. if (shader_core_props_amd.wavefrontsPerSimd == 20) {
  229. return vk_device_architecture::AMD_RDNA1;
  230. }
  231. if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
  232. return vk_device_architecture::AMD_RDNA3;
  233. }
  234. return vk_device_architecture::AMD_RDNA2;
  235. }
  236. } else if (props.vendorID == VK_VENDOR_ID_INTEL) {
  237. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  238. bool subgroup_size_control = false;
  239. for (const auto& properties : ext_props) {
  240. if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  241. subgroup_size_control = true;
  242. }
  243. }
  244. if (!subgroup_size_control) {
  245. return vk_device_architecture::OTHER;
  246. }
  247. vk::PhysicalDeviceProperties2 props2;
  248. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  249. props2.pNext = &subgroup_size_control_props;
  250. device.getProperties2(&props2);
  251. if (subgroup_size_control_props.minSubgroupSize == 16) {
  252. // Xe2 architecture uses SIMD16 while previous Xe and Gen architecture uses SIMD8.
  253. // Minimum subgroup size matches the SIMD width so we distinguish architecture by checking this value.
  254. // https://www.intel.com/content/www/us/en/content-details/824434/2024-intel-tech-tour-xe2-and-lunar-lake-s-gpu.html
  255. // https://www.intel.com/content/www/us/en/docs/oneapi/optimization-guide-gpu/2025-0/intel-xe-gpu-architecture.html
  256. return vk_device_architecture::INTEL_XE2;
  257. }
  258. } else if (props.vendorID == VK_VENDOR_ID_NVIDIA) {
  259. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  260. bool cooperative_matrix = false;
  261. // Detect "pre-turing" based on lack of coopmat support.
  262. for (const auto& properties : ext_props) {
  263. if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0) {
  264. cooperative_matrix = true;
  265. break;
  266. }
  267. }
  268. if (!cooperative_matrix) {
  269. return vk_device_architecture::NVIDIA_PRE_TURING;
  270. }
  271. }
  272. return vk_device_architecture::OTHER;
  273. }
  274. enum vk_conv_shapes {
  275. CONV_SHAPE_128x128,
  276. CONV_SHAPE_64x32,
  277. CONV_SHAPE_32x256,
  278. CONV_SHAPE_COUNT,
  279. };
  280. enum dmmv_wg_sizes {
  281. DMMV_WG_SIZE_SUBGROUP,
  282. DMMV_WG_SIZE_LARGE,
  283. DMMV_WG_SIZE_COUNT,
  284. };
  285. enum FaCodePath {
  286. FA_SCALAR,
  287. FA_COOPMAT1,
  288. FA_COOPMAT2,
  289. };
  290. struct vk_fa_pipeline_state {
  291. vk_fa_pipeline_state(uint32_t HSK, uint32_t HSV, bool small_rows, FaCodePath path, bool aligned, bool f32acc)
  292. : HSK(HSK), HSV(HSV), small_rows(small_rows), path(path), aligned(aligned), f32acc(f32acc) {}
  293. uint32_t HSK, HSV;
  294. bool small_rows;
  295. FaCodePath path;
  296. bool aligned;
  297. bool f32acc;
  298. bool operator<(const vk_fa_pipeline_state &b) const {
  299. return std::tie(HSK, HSV, small_rows, path, aligned, f32acc) <
  300. std::tie(b.HSK, b.HSV, b.small_rows, b.path, b.aligned, b.f32acc);
  301. }
  302. };
  303. enum shader_reduction_mode {
  304. SHADER_REDUCTION_MODE_SHMEM,
  305. SHADER_REDUCTION_MODE_HYBRID,
  306. SHADER_REDUCTION_MODE_SUBGROUP,
  307. SHADER_REDUCTION_MODE_COUNT,
  308. };
  309. static constexpr uint32_t num_argsort_pipelines = 11;
  310. static constexpr uint32_t max_argsort_cols = 1 << (num_argsort_pipelines-1);
  311. struct vk_device_struct {
  312. std::recursive_mutex mutex;
  313. vk::PhysicalDevice physical_device;
  314. vk::PhysicalDeviceProperties properties;
  315. std::string name;
  316. uint64_t max_memory_allocation_size;
  317. uint64_t suballocation_block_size;
  318. bool fp16;
  319. bool bf16;
  320. bool pipeline_robustness;
  321. vk::Device device;
  322. uint32_t vendor_id;
  323. vk::DriverId driver_id;
  324. vk_device_architecture architecture;
  325. vk_queue compute_queue;
  326. vk_queue transfer_queue;
  327. bool single_queue;
  328. uint32_t subgroup_size;
  329. uint32_t shader_core_count;
  330. bool uma;
  331. bool prefer_host_memory;
  332. bool float_controls_rte_fp16;
  333. bool subgroup_arithmetic;
  334. bool subgroup_shuffle;
  335. bool subgroup_ballot;
  336. bool subgroup_clustered;
  337. bool multi_add;
  338. bool add_rms_fusion;
  339. uint32_t partials_binding_alignment;
  340. bool integer_dot_product;
  341. // 0: default, 1: force mmvq, -1: disable mmvq
  342. int32_t mmvq_mode;
  343. bool subgroup_size_control;
  344. uint32_t subgroup_min_size;
  345. uint32_t subgroup_max_size;
  346. bool subgroup_require_full_support;
  347. bool coopmat_support;
  348. bool coopmat_acc_f32_support {};
  349. bool coopmat_acc_f16_support {};
  350. bool coopmat_bf16_support {};
  351. bool coopmat_support_16x16x16_f16acc {};
  352. bool coopmat_support_16x16x16_f32acc {};
  353. bool coopmat1_fa_support {};
  354. uint32_t coopmat_m;
  355. uint32_t coopmat_n;
  356. uint32_t coopmat_k;
  357. bool coopmat_int_support;
  358. uint32_t coopmat_int_m;
  359. uint32_t coopmat_int_n;
  360. uint32_t coopmat_int_k;
  361. bool coopmat2;
  362. bool pipeline_executable_properties_support {};
  363. size_t idx;
  364. bool mul_mat_l[GGML_TYPE_COUNT];
  365. bool mul_mat_m[GGML_TYPE_COUNT];
  366. bool mul_mat_s[GGML_TYPE_COUNT];
  367. bool mul_mat_id_l[GGML_TYPE_COUNT];
  368. bool mul_mat_id_m[GGML_TYPE_COUNT];
  369. bool mul_mat_id_s[GGML_TYPE_COUNT];
  370. // set to true to indicate that some shaders need to be compiled after the dryrun
  371. bool need_compiles {};
  372. vk::DescriptorSetLayout dsl;
  373. vk_matmul_pipeline pipeline_matmul_f32 {};
  374. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  375. vk_matmul_pipeline pipeline_matmul_bf16 {};
  376. vk_matmul_pipeline2 pipeline_matmul_f16;
  377. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  378. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  379. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  380. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_COUNT];
  381. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  382. vk_matmul_pipeline pipeline_matmul_id_bf16 {};
  383. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  384. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  385. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  386. vk_pipeline pipeline_matmul_split_k_reduce;
  387. vk_pipeline pipeline_quantize_q8_1;
  388. vk_pipeline pipeline_quantize_q8_1_x4;
  389. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  390. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  391. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  392. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_COUNT];
  393. vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  394. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio];
  395. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  396. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  397. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  398. vk_pipeline pipeline_acc_f32;
  399. // [src0 0=fp32,1=fp16][src1 0=fp32,1=fp16][dst 0=fp32,1=fp16]
  400. vk_pipeline pipeline_add[2][2][2];
  401. vk_pipeline pipeline_add_norepeat[2][2][2];
  402. vk_pipeline pipeline_sub[2][2][2];
  403. vk_pipeline pipeline_sub_norepeat[2][2][2];
  404. vk_pipeline pipeline_mul[2][2][2];
  405. vk_pipeline pipeline_mul_norepeat[2][2][2];
  406. vk_pipeline pipeline_div[2][2][2];
  407. vk_pipeline pipeline_div_norepeat[2][2][2];
  408. vk_pipeline pipeline_add_rms[2][2][2];
  409. vk_pipeline pipeline_add_rms_norepeat[2][2][2];
  410. // indexed by num_additional_fused_ops == num_adds - 1
  411. vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS];
  412. vk_pipeline pipeline_multi_add_rms[MAX_FUSED_ADDS];
  413. vk_pipeline pipeline_add_id_f32;
  414. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  415. vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32, pipeline_upscale_bilinear_ac_f32;
  416. vk_pipeline pipeline_scale_f32;
  417. vk_pipeline pipeline_sqr_f32;
  418. vk_pipeline pipeline_sqrt_f32;
  419. vk_pipeline pipeline_sin_f32;
  420. vk_pipeline pipeline_cos_f32;
  421. vk_pipeline pipeline_clamp_f32;
  422. vk_pipeline pipeline_pad_f32;
  423. vk_pipeline pipeline_roll_f32;
  424. vk_pipeline pipeline_repeat_f32, pipeline_repeat_back_f32;
  425. vk_pipeline pipeline_cpy_f32_f32, pipeline_cpy_f32_f16, pipeline_cpy_f16_f16, pipeline_cpy_f16_f32, pipeline_cpy_f32_bf16, pipeline_cpy_f32_i32, pipeline_cpy_i32_f32;
  426. vk_pipeline pipeline_contig_cpy_f32_f32, pipeline_contig_cpy_f32_f16, pipeline_contig_cpy_f16_f16, pipeline_contig_cpy_f16_f32, pipeline_contig_cpy_f32_bf16, pipeline_contig_cpy_f32_i32, pipeline_contig_cpy_i32_f32;
  427. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  428. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  429. vk_pipeline pipeline_set_rows_i32[GGML_TYPE_COUNT];
  430. vk_pipeline pipeline_set_rows_i64[GGML_TYPE_COUNT];
  431. vk_pipeline pipeline_norm_f32;
  432. vk_pipeline pipeline_group_norm_f32;
  433. vk_pipeline pipeline_rms_norm_f32;
  434. vk_pipeline pipeline_rms_norm_mul_f32;
  435. vk_pipeline pipeline_rms_norm_partials_f32;
  436. vk_pipeline pipeline_rms_norm_mul_partials_f32;
  437. vk_pipeline pipeline_rms_norm_back_f32;
  438. vk_pipeline pipeline_l2_norm_f32;
  439. // [src/dst 0=fp32,1=fp16]
  440. vk_pipeline pipeline_exp[2];
  441. vk_pipeline pipeline_gelu[2];
  442. vk_pipeline pipeline_gelu_erf[2];
  443. vk_pipeline pipeline_gelu_quick[2];
  444. vk_pipeline pipeline_silu[2];
  445. vk_pipeline pipeline_relu[2];
  446. vk_pipeline pipeline_tanh[2];
  447. vk_pipeline pipeline_sigmoid[2];
  448. vk_pipeline pipeline_hardsigmoid[2];
  449. vk_pipeline pipeline_hardswish[2];
  450. vk_pipeline pipeline_geglu[2];
  451. vk_pipeline pipeline_reglu[2];
  452. vk_pipeline pipeline_swiglu[2];
  453. vk_pipeline pipeline_swiglu_oai[2];
  454. vk_pipeline pipeline_geglu_erf[2];
  455. vk_pipeline pipeline_geglu_quick[2];
  456. vk_pipeline pipeline_leaky_relu_f32;
  457. vk_pipeline pipeline_silu_back_f32;
  458. vk_pipeline pipeline_diag_mask_inf_f32;
  459. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  460. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  461. vk_pipeline pipeline_soft_max_back_f32;
  462. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16;
  463. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16;
  464. vk_pipeline pipeline_rope_multi_f32, pipeline_rope_multi_f16;
  465. vk_pipeline pipeline_rope_vision_f32, pipeline_rope_vision_f16;
  466. vk_pipeline pipeline_argsort_f32[num_argsort_pipelines];
  467. vk_pipeline pipeline_sum_rows_f32;
  468. vk_pipeline pipeline_argmax_f32;
  469. vk_pipeline pipeline_count_equal_i32;
  470. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  471. vk_pipeline pipeline_im2col_3d_f32, pipeline_im2col_3d_f32_f16;
  472. vk_pipeline pipeline_timestep_embedding_f32;
  473. vk_pipeline pipeline_conv_transpose_1d_f32;
  474. vk_pipeline pipeline_pool2d_f32;
  475. vk_pipeline pipeline_rwkv_wkv6_f32;
  476. vk_pipeline pipeline_rwkv_wkv7_f32;
  477. vk_pipeline pipeline_opt_step_adamw_f32;
  478. vk_pipeline pipeline_opt_step_sgd_f32;
  479. vk_pipeline pipeline_conv2d_f32[CONV_SHAPE_COUNT];
  480. vk_pipeline pipeline_conv2d_f16_f32[CONV_SHAPE_COUNT];
  481. vk_pipeline pipeline_conv_transpose_2d_f32[CONV_SHAPE_COUNT];
  482. vk_pipeline pipeline_conv_transpose_2d_f16_f32[CONV_SHAPE_COUNT];
  483. vk_pipeline pipeline_conv2d_dw_whcn_f32, pipeline_conv2d_dw_whcn_f16_f32;
  484. vk_pipeline pipeline_conv2d_dw_cwhn_f32, pipeline_conv2d_dw_cwhn_f16_f32;
  485. std::map<vk_fa_pipeline_state, vk_pipeline> pipeline_flash_attn_f32_f16[GGML_TYPE_COUNT];
  486. vk_pipeline pipeline_flash_attn_split_k_reduce;
  487. std::vector<vk_pipeline_ref> all_pipelines;
  488. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  489. vk::Fence fence;
  490. vk_buffer sync_staging;
  491. ggml_backend_buffer_type buffer_type;
  492. bool disable_fusion;
  493. bool disable_host_visible_vidmem;
  494. bool allow_sysmem_fallback;
  495. bool disable_graph_optimize;
  496. #ifdef GGML_VULKAN_MEMORY_DEBUG
  497. std::unique_ptr<vk_memory_logger> memory_logger;
  498. #endif
  499. // for GGML_VK_PERF_LOGGER
  500. std::unique_ptr<vk_perf_logger> perf_logger;
  501. vk::QueryPool query_pool;
  502. int32_t num_queries;
  503. ~vk_device_struct() {
  504. VK_LOG_DEBUG("destroy device " << name);
  505. device.destroyFence(fence);
  506. ggml_vk_destroy_buffer(sync_staging);
  507. compute_queue.cmd_pool.destroy(device);
  508. transfer_queue.cmd_pool.destroy(device);
  509. for (auto& pipeline : all_pipelines) {
  510. if (pipeline.expired()) {
  511. continue;
  512. }
  513. vk_pipeline pl = pipeline.lock();
  514. ggml_vk_destroy_pipeline(device, pl);
  515. }
  516. all_pipelines.clear();
  517. device.destroyDescriptorSetLayout(dsl);
  518. device.destroy();
  519. }
  520. };
  521. void vk_command_pool::init(vk_device& device, vk_queue *q_) {
  522. cmd_buffer_idx = 0;
  523. q = q_;
  524. vk::CommandPoolCreateInfo command_pool_create_info(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), q->queue_family_index);
  525. pool = device->device.createCommandPool(command_pool_create_info);
  526. }
  527. void vk_command_pool::destroy(vk::Device& device) {
  528. device.destroyCommandPool(pool);
  529. pool = nullptr;
  530. cmd_buffers.clear();
  531. }
  532. struct vk_buffer_struct {
  533. vk::Buffer buffer = VK_NULL_HANDLE;
  534. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  535. vk::MemoryPropertyFlags memory_property_flags;
  536. void * ptr;
  537. size_t size = 0;
  538. vk_device device;
  539. ~vk_buffer_struct() {
  540. if (size == 0) {
  541. return;
  542. }
  543. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  544. device->device.freeMemory(device_memory);
  545. device->device.destroyBuffer(buffer);
  546. }
  547. };
  548. struct vk_subbuffer {
  549. vk_buffer buffer;
  550. uint64_t offset;
  551. uint64_t size;
  552. operator vk::DescriptorBufferInfo() const {
  553. return { buffer->buffer, offset, size };
  554. }
  555. };
  556. struct vk_semaphore {
  557. vk::Semaphore s;
  558. uint64_t value;
  559. };
  560. struct vk_submission {
  561. vk::CommandBuffer buffer;
  562. std::vector<vk_semaphore> wait_semaphores;
  563. std::vector<vk_semaphore> signal_semaphores;
  564. };
  565. typedef std::vector<vk_submission> vk_sequence;
  566. struct vk_mat_mat_push_constants {
  567. uint32_t M; uint32_t N; uint32_t K;
  568. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  569. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  570. uint32_t k_split;
  571. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  572. uint32_t padded_N;
  573. };
  574. struct vk_mat_vec_push_constants {
  575. uint32_t ncols; uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  576. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  577. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  578. };
  579. struct vk_mat_mat_id_push_constants {
  580. uint32_t M; uint32_t N; uint32_t K;
  581. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  582. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  583. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  584. uint32_t padded_N;
  585. };
  586. struct vk_mat_vec_id_push_constants {
  587. uint32_t ncols; uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  588. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  589. uint32_t nei0; uint32_t ne11;
  590. };
  591. struct vk_flash_attn_push_constants {
  592. uint32_t N;
  593. uint32_t KV;
  594. uint32_t ne1;
  595. uint32_t ne2;
  596. uint32_t ne3;
  597. uint32_t neq2;
  598. uint32_t neq3;
  599. uint32_t nek2;
  600. uint32_t nek3;
  601. uint32_t nev2;
  602. uint32_t nev3;
  603. uint32_t nem1;
  604. uint32_t nem2;
  605. uint32_t nem3;
  606. uint32_t nb01;
  607. uint32_t nb02;
  608. uint32_t nb03;
  609. uint32_t nb11;
  610. uint32_t nb12;
  611. uint32_t nb13;
  612. uint32_t nb21;
  613. uint32_t nb22;
  614. uint32_t nb23;
  615. float scale;
  616. float max_bias;
  617. float logit_softcap;
  618. uint32_t mask_n_head_log2;
  619. float m0;
  620. float m1;
  621. uint32_t gqa_ratio;
  622. uint32_t split_kv;
  623. uint32_t k_num;
  624. };
  625. static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128");
  626. struct vk_op_push_constants {
  627. uint32_t KX;
  628. uint32_t KY;
  629. float param1;
  630. float param2;
  631. };
  632. struct vk_op_glu_push_constants {
  633. uint32_t N;
  634. uint32_t ne00;
  635. uint32_t ne20;
  636. uint32_t mode; // 0: default, 1: swapped, 2: split
  637. float alpha; // for swiglu_oai
  638. float limit;
  639. };
  640. struct vk_op_unary_push_constants {
  641. uint32_t ne;
  642. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  643. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  644. uint32_t misalign_offsets;
  645. float param1; float param2;
  646. uint32_t ne0_012mp; uint32_t ne0_012L;
  647. uint32_t ne0_01mp; uint32_t ne0_01L;
  648. uint32_t ne0_0mp; uint32_t ne0_0L;
  649. uint32_t ne1_012mp; uint32_t ne1_012L;
  650. uint32_t ne1_01mp; uint32_t ne1_01L;
  651. uint32_t ne1_0mp; uint32_t ne1_0L;
  652. };
  653. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  654. static vk_op_unary_push_constants vk_op_unary_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst, int64_t ne = 0) {
  655. GGML_ASSERT(ne != 0 || (ggml_nelements(src0) == ggml_nelements(dst)));
  656. ne = ne != 0 ? ne : ggml_nelements(dst);
  657. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  658. vk_op_unary_push_constants p{};
  659. p.ne = (uint32_t)ne;
  660. size_t src0_tsize = ggml_type_size(src0->type);
  661. p.ne00 = (uint32_t)src0->ne[0];
  662. p.ne01 = (uint32_t)src0->ne[1];
  663. p.ne02 = (uint32_t)src0->ne[2];
  664. p.ne03 = (uint32_t)src0->ne[3];
  665. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  666. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  667. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  668. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  669. size_t dst_tsize = ggml_type_size(dst->type);
  670. p.ne10 = (uint32_t)dst->ne[0];
  671. p.ne11 = (uint32_t)dst->ne[1];
  672. p.ne12 = (uint32_t)dst->ne[2];
  673. p.ne13 = (uint32_t)dst->ne[3];
  674. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  675. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  676. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  677. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  678. return p; // offsets are initialized later in ggml_vk_op
  679. }
  680. struct vk_op_pad_push_constants {
  681. uint32_t ne;
  682. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  683. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  684. uint32_t misalign_offsets;
  685. uint32_t lp0; uint32_t rp0;
  686. uint32_t lp1; uint32_t rp1;
  687. uint32_t lp2; uint32_t rp2;
  688. uint32_t lp3; uint32_t rp3;
  689. };
  690. static vk_op_pad_push_constants vk_op_pad_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst) {
  691. int64_t ne = ggml_nelements(dst);
  692. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  693. vk_op_pad_push_constants p{};
  694. p.ne = (uint32_t)ne;
  695. size_t src0_tsize = ggml_type_size(src0->type);
  696. p.ne00 = (uint32_t)src0->ne[0];
  697. p.ne01 = (uint32_t)src0->ne[1];
  698. p.ne02 = (uint32_t)src0->ne[2];
  699. p.ne03 = (uint32_t)src0->ne[3];
  700. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  701. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  702. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  703. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  704. size_t dst_tsize = ggml_type_size(dst->type);
  705. p.ne10 = (uint32_t)dst->ne[0];
  706. p.ne11 = (uint32_t)dst->ne[1];
  707. p.ne12 = (uint32_t)dst->ne[2];
  708. p.ne13 = (uint32_t)dst->ne[3];
  709. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  710. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  711. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  712. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  713. p.lp0 = dst->op_params[0];
  714. p.rp0 = dst->op_params[1];
  715. p.lp1 = dst->op_params[2];
  716. p.rp1 = dst->op_params[3];
  717. p.lp2 = dst->op_params[4];
  718. p.rp2 = dst->op_params[5];
  719. p.lp3 = dst->op_params[6];
  720. p.rp3 = dst->op_params[7];
  721. return p; // fastdiv values and offsets are initialized later in ggml_vk_op
  722. }
  723. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  724. // Precompute mp (m' in the paper) and L such that division
  725. // can be computed using a multiply (high 32b of 64b result)
  726. // and a shift:
  727. //
  728. // n/d = (mulhi(n, mp) + n) >> L;
  729. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  730. {
  731. // compute L = ceil(log2(d));
  732. L = 0;
  733. while (L < 32 && (uint32_t{1} << L) < d) {
  734. L++;
  735. }
  736. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  737. }
  738. template <typename T> void init_pushconst_fastdiv(T &p) {
  739. GGML_UNUSED(p);
  740. static_assert(!std::is_const<T>::value, "unexpected type");
  741. }
  742. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  743. // Compute magic values to divide by these six numbers.
  744. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  745. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  746. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  747. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  748. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  749. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  750. }
  751. struct vk_op_binary_push_constants {
  752. uint32_t ne;
  753. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  754. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  755. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  756. uint32_t misalign_offsets;
  757. float param1; float param2; int32_t param3;
  758. };
  759. struct vk_op_multi_add_push_constants {
  760. // shape for dst
  761. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23;
  762. // strides for srcs+dst
  763. uint32_t nb[MAX_PARAMETER_COUNT][4];
  764. uint32_t rms_partials;
  765. };
  766. // update multi_add.comp if this changes
  767. static_assert(MAX_PARAMETER_COUNT == 12);
  768. static_assert(sizeof(vk_op_multi_add_push_constants) <= 256);
  769. struct vk_op_add_id_push_constants {
  770. uint32_t ne0;
  771. uint32_t ne1;
  772. uint32_t s01;
  773. uint32_t s02;
  774. uint32_t s11;
  775. uint32_t s21;
  776. };
  777. struct vk_op_diag_mask_push_constants {
  778. uint32_t ncols;
  779. uint32_t rows_per_channel;
  780. int32_t n_past;
  781. };
  782. struct vk_op_rope_push_constants {
  783. uint32_t ncols;
  784. uint32_t n_dims;
  785. float freq_scale;
  786. uint32_t p_delta_rows;
  787. float freq_base;
  788. float ext_factor;
  789. float attn_factor;
  790. float corr_dims[2];
  791. float theta_scale;
  792. uint32_t has_ff;
  793. uint32_t ne02;
  794. uint32_t s1;
  795. uint32_t s2;
  796. int32_t sections[4];
  797. uint32_t is_back;
  798. };
  799. struct vk_op_soft_max_push_constants {
  800. uint32_t KX;
  801. uint32_t KY;
  802. uint32_t ne00;
  803. uint32_t ne01;
  804. uint32_t ne02;
  805. uint32_t ne12;
  806. uint32_t ne13;
  807. uint32_t nb11;
  808. uint32_t nb12;
  809. uint32_t nb13;
  810. float scale;
  811. float max_bias;
  812. float m0;
  813. float m1;
  814. uint32_t n_head_log2;
  815. uint32_t nrows_x;
  816. uint32_t has_sinks;
  817. };
  818. struct vk_op_argsort_push_constants {
  819. uint32_t ncols;
  820. int32_t order;
  821. };
  822. struct vk_op_im2col_push_constants {
  823. uint32_t batch_offset; uint32_t offset_delta;
  824. uint32_t IC;
  825. uint32_t IW; uint32_t IH;
  826. uint32_t OW; uint32_t OH;
  827. uint32_t KW; uint32_t KH;
  828. uint32_t pelements;
  829. uint32_t CHW;
  830. int32_t s0; int32_t s1;
  831. int32_t p0; int32_t p1;
  832. int32_t d0; int32_t d1;
  833. };
  834. struct vk_op_im2col_3d_push_constants {
  835. uint32_t nb10;
  836. uint32_t nb11;
  837. uint32_t nb12;
  838. uint32_t nb13;
  839. uint32_t s0;
  840. uint32_t s1;
  841. uint32_t s2;
  842. uint32_t p0;
  843. uint32_t p1;
  844. uint32_t p2;
  845. uint32_t d0;
  846. uint32_t d1;
  847. uint32_t d2;
  848. uint32_t IW;
  849. uint32_t IH;
  850. uint32_t ID;
  851. uint32_t IC;
  852. uint32_t KW;
  853. uint32_t OH;
  854. uint32_t KD_KH_KW;
  855. uint32_t KH_KW;
  856. uint32_t IC_KD_KH_KW;
  857. uint32_t N_OD_OH;
  858. uint32_t OD_OH;
  859. uint32_t OD_OH_OW_IC_KD_KH_KW;
  860. uint32_t OH_OW_IC_KD_KH_KW;
  861. uint32_t OW_IC_KD_KH_KW;
  862. uint32_t misalign_offsets;
  863. };
  864. struct vk_op_timestep_embedding_push_constants {
  865. uint32_t nb1;
  866. uint32_t dim;
  867. uint32_t max_period;
  868. };
  869. struct vk_op_conv_transpose_1d_push_constants {
  870. uint32_t Cout;
  871. uint32_t Cin;
  872. uint32_t K;
  873. uint32_t L;
  874. uint32_t KL;
  875. uint32_t nb01;
  876. uint32_t nb02;
  877. uint32_t nb11;
  878. uint32_t nb1;
  879. int32_t s0;
  880. };
  881. struct vk_op_pool2d_push_constants {
  882. uint32_t IW; uint32_t IH;
  883. uint32_t OW; uint32_t OH;
  884. uint32_t OC;
  885. uint32_t pelements;
  886. uint32_t op;
  887. int32_t k0; int32_t k1;
  888. int32_t s0; int32_t s1;
  889. int32_t p0; int32_t p1;
  890. };
  891. struct vk_op_rwkv_wkv6_push_constants {
  892. uint32_t B;
  893. uint32_t T;
  894. uint32_t C;
  895. uint32_t H;
  896. };
  897. struct vk_op_rwkv_wkv7_push_constants {
  898. uint32_t B;
  899. uint32_t T;
  900. uint32_t C;
  901. uint32_t H;
  902. };
  903. struct vk_op_conv2d_push_constants {
  904. uint32_t Cout;
  905. uint32_t Cin;
  906. uint32_t N;
  907. uint32_t KW;
  908. uint32_t KH;
  909. uint32_t W;
  910. uint32_t H;
  911. uint32_t OW;
  912. uint32_t OH;
  913. uint32_t s0;
  914. uint32_t s1;
  915. uint32_t p0;
  916. uint32_t p1;
  917. uint32_t d0;
  918. uint32_t d1;
  919. uint32_t nb01;
  920. uint32_t nb02;
  921. uint32_t nb03;
  922. uint32_t nb11;
  923. uint32_t nb12;
  924. uint32_t nb13;
  925. uint32_t nb1;
  926. uint32_t nb2;
  927. uint32_t nb3;
  928. // init_fastdiv_values constants for dividing by KW, KW*KH, OW, OW*OH
  929. uint32_t KWmp; uint32_t KWL;
  930. uint32_t KWKHmp; uint32_t KWKHL;
  931. uint32_t OWmp; uint32_t OWL;
  932. uint32_t OWOHmp; uint32_t OWOHL;
  933. };
  934. template <> void init_pushconst_fastdiv(vk_op_conv2d_push_constants &p) {
  935. // Compute magic values to divide by KW, KW*KH, OW, OW*OH
  936. init_fastdiv_values(p.KW, p.KWmp, p.KWL);
  937. init_fastdiv_values(p.KW*p.KH, p.KWKHmp, p.KWKHL);
  938. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  939. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  940. }
  941. struct vk_op_conv_transpose_2d_push_constants {
  942. uint32_t Cout;
  943. uint32_t Cin;
  944. uint32_t N;
  945. uint32_t KW;
  946. uint32_t KH;
  947. uint32_t W;
  948. uint32_t H;
  949. uint32_t OW;
  950. uint32_t OH;
  951. uint32_t s0;
  952. uint32_t s1;
  953. uint32_t p0;
  954. uint32_t p1;
  955. uint32_t d0;
  956. uint32_t d1;
  957. uint32_t nb01;
  958. uint32_t nb02;
  959. uint32_t nb03;
  960. uint32_t nb11;
  961. uint32_t nb12;
  962. uint32_t nb13;
  963. uint32_t nb1;
  964. uint32_t nb2;
  965. uint32_t nb3;
  966. // init_fastdiv_values constants for dividing by KW, KW*KH, OW, OW*OH, s0, s1
  967. uint32_t KWmp; uint32_t KWL;
  968. uint32_t KWKHmp; uint32_t KWKHL;
  969. uint32_t OWmp; uint32_t OWL;
  970. uint32_t OWOHmp; uint32_t OWOHL;
  971. uint32_t s0mp; uint32_t s0L;
  972. uint32_t s1mp; uint32_t s1L;
  973. };
  974. template <> void init_pushconst_fastdiv(vk_op_conv_transpose_2d_push_constants &p) {
  975. // Compute magic values to divide by KW, KW*KH, OW, OW*OH, s0, s1
  976. init_fastdiv_values(p.KW, p.KWmp, p.KWL);
  977. init_fastdiv_values(p.KW*p.KH, p.KWKHmp, p.KWKHL);
  978. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  979. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  980. init_fastdiv_values(p.s0, p.s0mp, p.s0L);
  981. init_fastdiv_values(p.s1, p.s1mp, p.s1L);
  982. }
  983. struct vk_op_conv2d_dw_push_constants {
  984. uint32_t ne;
  985. uint32_t batches;
  986. uint32_t channels;
  987. uint32_t dst_w;
  988. uint32_t dst_h;
  989. uint32_t src_w;
  990. uint32_t src_h;
  991. uint32_t knl_w;
  992. uint32_t knl_h;
  993. int32_t stride_x;
  994. int32_t stride_y;
  995. int32_t pad_x;
  996. int32_t pad_y;
  997. int32_t dilation_x;
  998. int32_t dilation_y;
  999. };
  1000. struct vk_op_upscale_push_constants {
  1001. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  1002. uint32_t ne00; uint32_t ne01;
  1003. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1004. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  1005. float sf0; float sf1; float sf2; float sf3;
  1006. };
  1007. struct vk_op_sum_rows_push_constants
  1008. {
  1009. uint32_t n_cols;
  1010. uint32_t ne01, ne02;
  1011. uint32_t nb01, nb02, nb03;
  1012. uint32_t nb11, nb12, nb13;
  1013. float weight;
  1014. uint32_t misalign_offsets;
  1015. uint32_t ne0_12mp, ne0_12L;
  1016. uint32_t ne0_1mp, ne0_1L;
  1017. };
  1018. static vk_op_sum_rows_push_constants vk_op_sum_rows_push_constants_init(const ggml_tensor * src, const ggml_tensor * dst, int64_t n_cols) {
  1019. uint32_t type_size = (uint32_t)ggml_type_size(src->type);
  1020. vk_op_sum_rows_push_constants p = {};
  1021. p.n_cols = (uint32_t)n_cols;
  1022. p.ne01 = (uint32_t)src->ne[1];
  1023. p.ne02 = (uint32_t)src->ne[2];
  1024. p.nb01 = (uint32_t)src->nb[1] / type_size;
  1025. p.nb02 = (uint32_t)src->nb[2] / type_size;
  1026. p.nb03 = (uint32_t)src->nb[3] / type_size;
  1027. p.nb11 = (uint32_t)dst->nb[1] / type_size;
  1028. p.nb12 = (uint32_t)dst->nb[2] / type_size;
  1029. p.nb13 = (uint32_t)dst->nb[3] / type_size;
  1030. p.weight = 1.0f;
  1031. return p;
  1032. }
  1033. template <> void init_pushconst_fastdiv(vk_op_sum_rows_push_constants &p) {
  1034. init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L);
  1035. init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L);
  1036. }
  1037. // Allow pre-recording command buffers
  1038. struct vk_staging_memcpy {
  1039. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  1040. void * dst;
  1041. const void * src;
  1042. size_t n;
  1043. };
  1044. struct vk_staging_memset {
  1045. vk_staging_memset(void * _dst, uint32_t _val, size_t _n) : dst(_dst), val(_val), n(_n) {}
  1046. void * dst;
  1047. uint32_t val;
  1048. size_t n;
  1049. };
  1050. struct vk_context_struct {
  1051. vk_submission * s;
  1052. std::vector<vk_sequence> seqs;
  1053. int exit_tensor_idx;
  1054. std::vector<vk_staging_memcpy> in_memcpys;
  1055. std::vector<vk_staging_memcpy> out_memcpys;
  1056. std::vector<vk_staging_memset> memsets;
  1057. vk_command_pool * p {};
  1058. };
  1059. typedef std::shared_ptr<vk_context_struct> vk_context;
  1060. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  1061. struct ggml_vk_garbage_collector {
  1062. std::vector<vk_semaphore> tl_semaphores;
  1063. std::vector<vk_semaphore> semaphores;
  1064. std::vector<vk::Event> events;
  1065. std::vector<vk_buffer> temp_buffers;
  1066. std::vector<vk_context> contexts;
  1067. };
  1068. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  1069. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  1070. static std::string format_size(size_t size) {
  1071. const size_t kib = 1024;
  1072. const size_t mib = kib * 1024;
  1073. const size_t gib = mib * 1024;
  1074. std::ostringstream oss;
  1075. oss << std::fixed << std::setprecision(2);
  1076. if (size >= gib) {
  1077. oss << static_cast<double>(size) / gib << " GiB";
  1078. } else if (size >= mib) {
  1079. oss << static_cast<double>(size) / mib << " MiB";
  1080. } else if (size >= kib) {
  1081. oss << static_cast<double>(size) / kib << " KiB";
  1082. } else {
  1083. oss << size << " B";
  1084. }
  1085. return oss.str();
  1086. }
  1087. class vk_memory_logger {
  1088. public:
  1089. vk_memory_logger(): total_device(0), total_host(0) {}
  1090. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  1091. void log_deallocation(vk_buffer_ref buf_ref);
  1092. private:
  1093. std::map<vk::Buffer, size_t> allocations; // Track allocations
  1094. size_t total_device;
  1095. size_t total_host;
  1096. };
  1097. #else
  1098. #define VK_LOG_MEMORY(msg) ((void) 0)
  1099. #endif // GGML_VULKAN_MEMORY_DEBUG
  1100. class vk_perf_logger {
  1101. public:
  1102. void print_timings() {
  1103. if (timings.empty()) {
  1104. return;
  1105. }
  1106. uint64_t total_all_op_times = 0;
  1107. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  1108. for (const auto & t : timings) {
  1109. uint64_t total_op_times = 0;
  1110. for (const auto & time : t.second) {
  1111. total_op_times += time;
  1112. }
  1113. std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0)
  1114. << " us";
  1115. // If we have as many flops entries as timing entries for the op, then compute and log the flops/S.
  1116. auto it = flops.find(t.first);
  1117. if (it != flops.end() && (it->second).size() == t.second.size()) {
  1118. uint64_t total_op_flops = 0;
  1119. for (const auto & elem : it->second) {
  1120. total_op_flops += elem;
  1121. }
  1122. std::cerr << " ("
  1123. << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) /
  1124. (double(total_op_times) / (1000.0 * 1000.0 * 1000.0))
  1125. << " GFLOPS/s)";
  1126. }
  1127. total_all_op_times += total_op_times;
  1128. std::cerr << std::endl;
  1129. }
  1130. if (timings.size() > 0) {
  1131. std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl;
  1132. }
  1133. timings.clear();
  1134. flops.clear();
  1135. }
  1136. void log_timing(const ggml_tensor * node, uint64_t time) {
  1137. if (node->op == GGML_OP_UNARY) {
  1138. timings[ggml_unary_op_name(ggml_get_unary_op(node))].push_back(time);
  1139. return;
  1140. }
  1141. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  1142. const uint64_t m = node->src[0]->ne[1];
  1143. const uint64_t n = node->ne[1];
  1144. const uint64_t k = node->src[1]->ne[0];
  1145. const uint64_t batch = node->src[1]->ne[2] * node->src[1]->ne[3];
  1146. std::string name = ggml_op_name(node->op);
  1147. if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) ||
  1148. (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) {
  1149. name += "_VEC";
  1150. }
  1151. name += " ";
  1152. name += ggml_type_name(node->src[0]->type);
  1153. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  1154. if (batch > 1) {
  1155. name += " batch=" + std::to_string(batch);
  1156. }
  1157. timings[name].push_back(time);
  1158. flops[name].push_back(m * n * (k + (k - 1)) * batch);
  1159. return;
  1160. }
  1161. if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) {
  1162. std::string name = ggml_op_name(node->op);
  1163. ggml_tensor * knl = node->src[0];
  1164. uint64_t OW = node->ne[0];
  1165. uint64_t OH = node->ne[1];
  1166. uint64_t N = node->ne[3];
  1167. uint64_t Cout = node->ne[2];
  1168. uint64_t KW = knl->ne[0];
  1169. uint64_t KH = knl->ne[1];
  1170. uint64_t Cin = node->src[1]->ne[2];
  1171. // KxCRS @ CRSxNPQ = KxNPQ -> M=K, K=CRS, N=NPQ
  1172. uint64_t size_M = Cout;
  1173. uint64_t size_K = Cin * KW * KH;
  1174. uint64_t size_N = N * OW * OH;
  1175. uint64_t n_flops = size_M * size_N * (size_K + (size_K - 1));
  1176. name += " M=Cout=" + std::to_string(size_M) + ", K=Cin*KW*KH=" + std::to_string(size_K) +
  1177. ", N=N*OW*OH=" + std::to_string(size_N);
  1178. flops[name].push_back(n_flops);
  1179. timings[name].push_back(time);
  1180. return;
  1181. }
  1182. if (node->op == GGML_OP_RMS_NORM) {
  1183. std::string name = ggml_op_name(node->op);
  1184. name += "(" + std::to_string(node->ne[0]) + "," + std::to_string(node->ne[1]) + "," + std::to_string(node->ne[2]) + "," + std::to_string(node->ne[3]) + ")";
  1185. timings[name].push_back(time);
  1186. return;
  1187. }
  1188. timings[ggml_op_name(node->op)].push_back(time);
  1189. }
  1190. private:
  1191. std::map<std::string, std::vector<uint64_t>> timings;
  1192. std::map<std::string, std::vector<uint64_t>> flops;
  1193. };
  1194. struct ggml_backend_vk_context {
  1195. std::string name;
  1196. vk_device device;
  1197. size_t semaphore_idx, event_idx;
  1198. ggml_vk_garbage_collector gc;
  1199. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset;
  1200. vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials;
  1201. vk::Fence fence, almost_ready_fence;
  1202. bool almost_ready_fence_pending {};
  1203. // Set before op_add and unset after op_rms_norm to indicate that the add should
  1204. // write partial sums to accumulate the square of the vector components
  1205. bool do_add_rms_partials;
  1206. // Cache most recent tensor that was converted into prealloc_y, and what pipeline it used to convert.
  1207. vk_pipeline_struct * prealloc_y_last_pipeline_used {};
  1208. const ggml_tensor * prealloc_y_last_tensor_used {};
  1209. // Track which nodes have been used since the last sync, and whether they were written to
  1210. std::vector<const ggml_tensor *> unsynced_nodes_written;
  1211. std::vector<const ggml_tensor *> unsynced_nodes_read;
  1212. // Track which prealloc buffers have pending reads that need to be synchronized.
  1213. // These are checked before writing to the buffer (and call ggml_vk_sync_buffers if set),
  1214. // and set to true after the buffer contents are consumed.
  1215. bool prealloc_x_need_sync, prealloc_y_need_sync, prealloc_split_k_need_sync;
  1216. vk_buffer buffer_pool[MAX_VK_BUFFERS];
  1217. vk_context_ref compute_ctx;
  1218. vk_context_ref transfer_ctx;
  1219. std::vector<vk_context_ref> tensor_ctxs;
  1220. std::vector<vk::DescriptorPool> descriptor_pools;
  1221. std::vector<vk::DescriptorSet> descriptor_sets;
  1222. uint32_t descriptor_set_idx {};
  1223. uint32_t pipeline_descriptor_set_requirements {};
  1224. vk_command_pool compute_cmd_pool;
  1225. vk_command_pool transfer_cmd_pool;
  1226. // number of additional consecutive nodes that are being fused with the
  1227. // node currently being processed
  1228. int num_additional_fused_ops {};
  1229. };
  1230. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  1231. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  1232. if (tensor->view_src) {
  1233. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  1234. }
  1235. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  1236. }
  1237. struct ggml_backend_vk_buffer_context {
  1238. vk_device_ref device;
  1239. vk_buffer dev_buffer;
  1240. std::string name;
  1241. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  1242. device(device),
  1243. dev_buffer(dev_buffer),
  1244. name(name) {
  1245. }
  1246. ~ggml_backend_vk_buffer_context() {
  1247. ggml_vk_destroy_buffer(dev_buffer);
  1248. }
  1249. };
  1250. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1251. static std::mutex log_mutex;
  1252. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  1253. std::lock_guard<std::mutex> guard(log_mutex);
  1254. vk_buffer buf = buf_ref.lock();
  1255. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1256. const std::string type = device ? "device" : "host";
  1257. allocations[buf->buffer] = size;
  1258. total_device += device ? size : 0;
  1259. total_host += device ? 0 : size;
  1260. 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));
  1261. }
  1262. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  1263. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  1264. return;
  1265. }
  1266. std::lock_guard<std::mutex> guard(log_mutex);
  1267. vk_buffer buf = buf_ref.lock();
  1268. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1269. std::string type = device ? "device" : "host";
  1270. auto it = allocations.find(buf->buffer);
  1271. total_device -= device ? it->second : 0;
  1272. total_host -= device ? 0 : it->second;
  1273. if (it != allocations.end()) {
  1274. 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));
  1275. allocations.erase(it);
  1276. } else {
  1277. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  1278. }
  1279. }
  1280. #endif // GGML_VULKAN_MEMORY_DEBUG
  1281. struct vk_instance_t {
  1282. vk::Instance instance;
  1283. bool debug_utils_support = false; // VK_EXT_debug_utils enabled
  1284. PFN_vkSetDebugUtilsObjectNameEXT pfn_vkSetDebugUtilsObjectNameEXT = {};
  1285. PFN_vkQueueBeginDebugUtilsLabelEXT pfn_vkQueueBeginDebugUtilsLabelEXT = {};
  1286. PFN_vkQueueEndDebugUtilsLabelEXT pfn_vkQueueEndDebugUtilsLabelEXT = {};
  1287. PFN_vkCmdBeginDebugUtilsLabelEXT pfn_vkCmdBeginDebugUtilsLabelEXT = {};
  1288. PFN_vkCmdEndDebugUtilsLabelEXT pfn_vkCmdEndDebugUtilsLabelEXT = {};
  1289. PFN_vkCmdInsertDebugUtilsLabelEXT pfn_vkCmdInsertDebugUtilsLabelEXT = {};
  1290. std::vector<size_t> device_indices;
  1291. std::vector<bool> device_supports_membudget;
  1292. vk_device devices[GGML_VK_MAX_DEVICES];
  1293. };
  1294. static bool vk_instance_initialized = false;
  1295. static vk_instance_t vk_instance;
  1296. static bool vk_perf_logger_enabled = false;
  1297. #ifdef GGML_VULKAN_CHECK_RESULTS
  1298. static size_t vk_skip_checks;
  1299. static size_t vk_output_tensor;
  1300. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  1301. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1302. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1303. #endif
  1304. 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);
  1305. static void ggml_backend_vk_free(ggml_backend_t backend);
  1306. // Wait for ctx->fence to be signaled.
  1307. static void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) {
  1308. // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep
  1309. // during this wait.
  1310. if (ctx->almost_ready_fence_pending) {
  1311. VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence");
  1312. ctx->device->device.resetFences({ ctx->almost_ready_fence });
  1313. ctx->almost_ready_fence_pending = false;
  1314. }
  1315. // Spin (w/pause) waiting for the graph to finish executing.
  1316. vk::Result result;
  1317. while ((result = ctx->device->device.getFenceStatus(ctx->fence)) != vk::Result::eSuccess) {
  1318. if (result != vk::Result::eNotReady) {
  1319. fprintf(stderr, "ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__);
  1320. exit(1);
  1321. }
  1322. for (uint32_t i = 0; i < 100; ++i) {
  1323. YIELD();
  1324. YIELD();
  1325. YIELD();
  1326. YIELD();
  1327. YIELD();
  1328. YIELD();
  1329. YIELD();
  1330. YIELD();
  1331. YIELD();
  1332. YIELD();
  1333. }
  1334. }
  1335. ctx->device->device.resetFences({ ctx->fence });
  1336. }
  1337. // variables to track number of compiles in progress
  1338. static uint32_t compile_count = 0;
  1339. static std::mutex compile_count_mutex;
  1340. static std::condition_variable compile_count_cond;
  1341. 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,
  1342. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  1343. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  1344. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  1345. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  1346. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  1347. GGML_ASSERT(parameter_count > 0);
  1348. GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT);
  1349. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  1350. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  1351. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  1352. vk::PushConstantRange pcr(
  1353. vk::ShaderStageFlagBits::eCompute,
  1354. 0,
  1355. pipeline->push_constant_size
  1356. );
  1357. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr);
  1358. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  1359. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  1360. for (size_t i = 0; i < specialization_constants.size(); i++) {
  1361. specialization_entries[i].constantID = i;
  1362. specialization_entries[i].offset = i * sizeof(uint32_t);
  1363. specialization_entries[i].size = sizeof(uint32_t);
  1364. }
  1365. vk::SpecializationInfo specialization_info(
  1366. specialization_entries.size(),
  1367. specialization_entries.data(),
  1368. specialization_constants.size() * sizeof(uint32_t),
  1369. specialization_constants.data()
  1370. );
  1371. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  1372. if (device->subgroup_require_full_support && require_full_subgroups) {
  1373. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  1374. }
  1375. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  1376. pipeline_shader_stage_create_flags,
  1377. vk::ShaderStageFlagBits::eCompute,
  1378. pipeline->shader_module,
  1379. entrypoint.c_str(),
  1380. &specialization_info);
  1381. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  1382. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  1383. if (device->subgroup_size_control && required_subgroup_size > 0) {
  1384. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  1385. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  1386. }
  1387. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  1388. device->pipeline_executable_properties_support ?
  1389. vk::PipelineCreateFlagBits::eCaptureStatisticsKHR :
  1390. vk::PipelineCreateFlags{},
  1391. pipeline_shader_create_info,
  1392. pipeline->layout);
  1393. vk::PipelineRobustnessCreateInfoEXT rci;
  1394. if (device->pipeline_robustness && disable_robustness) {
  1395. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1396. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1397. compute_pipeline_create_info.setPNext(&rci);
  1398. }
  1399. try {
  1400. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  1401. } catch (const vk::SystemError& e) {
  1402. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  1403. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1404. throw e;
  1405. }
  1406. pipeline->compiled = true;
  1407. if (vk_instance.debug_utils_support) {
  1408. vk::DebugUtilsObjectNameInfoEXT duoni;
  1409. duoni.objectType = vk::ObjectType::ePipeline;
  1410. duoni.pObjectName = pipeline->name.c_str();
  1411. duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast<VkPipeline>(pipeline->pipeline));
  1412. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast<VkDebugUtilsObjectNameInfoEXT &>(duoni));
  1413. }
  1414. if (device->pipeline_executable_properties_support) {
  1415. vk::PipelineExecutableInfoKHR executableInfo;
  1416. executableInfo.pipeline = pipeline->pipeline;
  1417. auto statistics = device->device.getPipelineExecutableStatisticsKHR(executableInfo);
  1418. for (auto & s : statistics) {
  1419. // "Register Count" is reported by NVIDIA drivers.
  1420. if (strcmp(s.name, "Register Count") == 0) {
  1421. VK_LOG_DEBUG(pipeline->name << " " << s.name << ": " << s.value.u64 << " registers");
  1422. pipeline->register_count = (uint32_t)s.value.u64;
  1423. }
  1424. }
  1425. }
  1426. {
  1427. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1428. device->all_pipelines.push_back(pipeline);
  1429. }
  1430. {
  1431. std::lock_guard<std::mutex> guard(compile_count_mutex);
  1432. assert(compile_count > 0);
  1433. compile_count--;
  1434. }
  1435. compile_count_cond.notify_all();
  1436. }
  1437. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  1438. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  1439. device.destroyPipelineLayout(pipeline->layout);
  1440. device.destroyShaderModule(pipeline->shader_module);
  1441. device.destroyPipeline(pipeline->pipeline);
  1442. }
  1443. static void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) {
  1444. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  1445. ctx->pipeline_descriptor_set_requirements += n;
  1446. if (!pipeline->compiled) {
  1447. pipeline->needed = true;
  1448. ctx->device->need_compiles = true;
  1449. }
  1450. }
  1451. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
  1452. if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) {
  1453. // Enough descriptors are available
  1454. return;
  1455. }
  1456. vk_device& device = ctx->device;
  1457. uint32_t to_alloc = ctx->pipeline_descriptor_set_requirements - ctx->descriptor_sets.size();
  1458. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1459. uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1460. while (to_alloc > 0) {
  1461. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  1462. to_alloc -= alloc_count;
  1463. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1464. if (pool_idx >= ctx->descriptor_pools.size()) {
  1465. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  1466. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  1467. ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  1468. }
  1469. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  1470. for (uint32_t i = 0; i < alloc_count; i++) {
  1471. layouts[i] = device->dsl;
  1472. }
  1473. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
  1474. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  1475. ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
  1476. pool_idx++;
  1477. }
  1478. }
  1479. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) {
  1480. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  1481. if (p.cmd_buffers.size() > p.cmd_buffer_idx) {
  1482. // Reuse command buffer
  1483. return p.cmd_buffers[p.cmd_buffer_idx++];
  1484. }
  1485. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  1486. p.pool,
  1487. vk::CommandBufferLevel::ePrimary,
  1488. 1);
  1489. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  1490. auto buf = cmd_buffers.front();
  1491. p.cmd_buffers.push_back(buf);
  1492. p.cmd_buffer_idx++;
  1493. return buf;
  1494. }
  1495. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  1496. if (ctx->seqs.empty()) {
  1497. if (fence) {
  1498. std::lock_guard<std::mutex> guard(queue_mutex);
  1499. ctx->p->q->queue.submit({}, fence);
  1500. }
  1501. return;
  1502. }
  1503. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  1504. std::vector<std::vector<uint64_t>> tl_wait_vals;
  1505. std::vector<std::vector<uint64_t>> tl_signal_vals;
  1506. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  1507. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  1508. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  1509. std::vector<vk::SubmitInfo> submit_infos;
  1510. int idx = -1;
  1511. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  1512. size_t reserve = 0;
  1513. for (const auto& sequence : ctx->seqs) {
  1514. reserve += sequence.size();
  1515. }
  1516. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  1517. tl_wait_semaphores.reserve(reserve);
  1518. tl_wait_vals.reserve(reserve);
  1519. tl_signal_semaphores.reserve(reserve);
  1520. tl_signal_vals.reserve(reserve);
  1521. tl_submit_infos.reserve(reserve);
  1522. submit_infos.reserve(reserve);
  1523. stage_flags.reserve(reserve);
  1524. for (const auto& sequence : ctx->seqs) {
  1525. for (const auto& submission : sequence) {
  1526. stage_flags.push_back({});
  1527. idx++;
  1528. tl_wait_vals.push_back({});
  1529. tl_wait_semaphores.push_back({});
  1530. tl_signal_vals.push_back({});
  1531. tl_signal_semaphores.push_back({});
  1532. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  1533. stage_flags[idx].push_back(ctx->p->q->stage_flags);
  1534. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  1535. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  1536. }
  1537. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  1538. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  1539. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  1540. }
  1541. tl_submit_infos.push_back({
  1542. (uint32_t) submission.wait_semaphores.size(),
  1543. tl_wait_vals[idx].data(),
  1544. (uint32_t) submission.signal_semaphores.size(),
  1545. tl_signal_vals[idx].data(),
  1546. });
  1547. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  1548. tl_submit_infos[idx].pNext = nullptr;
  1549. vk::SubmitInfo si{
  1550. (uint32_t) submission.wait_semaphores.size(),
  1551. tl_wait_semaphores[idx].data(),
  1552. stage_flags[idx].data(),
  1553. 1,
  1554. &submission.buffer,
  1555. (uint32_t) submission.signal_semaphores.size(),
  1556. tl_signal_semaphores[idx].data(),
  1557. };
  1558. si.setPNext(&tl_submit_infos[idx]);
  1559. submit_infos.push_back(si);
  1560. }
  1561. }
  1562. std::lock_guard<std::mutex> guard(queue_mutex);
  1563. ctx->p->q->queue.submit(submit_infos, fence);
  1564. ctx->seqs.clear();
  1565. }
  1566. 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) {
  1567. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  1568. const uint32_t qfsize = queue_family_props.size();
  1569. // Try with avoid preferences first
  1570. for (uint32_t i = 0; i < qfsize; i++) {
  1571. 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)) {
  1572. return i;
  1573. }
  1574. }
  1575. // Fall back to only required
  1576. for (size_t i = 0; i < qfsize; i++) {
  1577. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  1578. return i;
  1579. }
  1580. }
  1581. // Fall back to reusing compute queue
  1582. for (size_t i = 0; i < qfsize; i++) {
  1583. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  1584. return i;
  1585. }
  1586. }
  1587. // Fall back to ignoring min_num_queries
  1588. for (size_t i = 0; i < qfsize; i++) {
  1589. if (queue_family_props[i].queueFlags & required) {
  1590. return i;
  1591. }
  1592. }
  1593. // 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.
  1594. // 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.
  1595. if (compute_index >= 0) {
  1596. return compute_index;
  1597. }
  1598. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  1599. for(auto &q_family : queue_family_props) {
  1600. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  1601. }
  1602. abort();
  1603. }
  1604. 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) {
  1605. VK_LOG_DEBUG("ggml_vk_create_queue()");
  1606. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1607. q.queue_family_index = queue_family_index;
  1608. q.transfer_only = transfer_only;
  1609. q.cmd_pool.init(device, &q);
  1610. q.queue = device->device.getQueue(queue_family_index, queue_index);
  1611. q.stage_flags = stage_flags;
  1612. }
  1613. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) {
  1614. vk_context result = std::make_shared<vk_context_struct>();
  1615. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  1616. ctx->gc.contexts.emplace_back(result);
  1617. result->p = &p;
  1618. return result;
  1619. }
  1620. static vk_context ggml_vk_create_temporary_context(vk_command_pool& p) {
  1621. vk_context result = std::make_shared<vk_context_struct>();
  1622. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  1623. result->p = &p;
  1624. return result;
  1625. }
  1626. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  1627. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1628. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  1629. vk::SemaphoreCreateInfo ci{};
  1630. ci.setPNext(&tci);
  1631. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1632. ctx->gc.semaphores.push_back({ semaphore, 0 });
  1633. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  1634. }
  1635. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  1636. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1637. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  1638. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  1639. vk::SemaphoreCreateInfo ci{};
  1640. ci.setPNext(&tci);
  1641. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1642. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  1643. }
  1644. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  1645. }
  1646. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  1647. if (ctx->event_idx >= ctx->gc.events.size()) {
  1648. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  1649. }
  1650. return ctx->gc.events[ctx->event_idx++];
  1651. }
  1652. static void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) {
  1653. VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()");
  1654. // Requires command buffers to be done
  1655. device->device.resetCommandPool(p.pool);
  1656. p.cmd_buffer_idx = 0;
  1657. }
  1658. static void ggml_vk_queue_command_pools_cleanup(vk_device& device) {
  1659. VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()");
  1660. // Arbitrary frequency to cleanup/reuse command buffers
  1661. static constexpr uint32_t cleanup_frequency = 10;
  1662. if (device->compute_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1663. ggml_vk_command_pool_cleanup(device, device->compute_queue.cmd_pool);
  1664. }
  1665. if (device->transfer_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1666. ggml_vk_command_pool_cleanup(device, device->transfer_queue.cmd_pool);
  1667. }
  1668. }
  1669. static uint32_t find_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  1670. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  1671. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  1672. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  1673. (flags & memory_type.propertyFlags) == flags &&
  1674. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  1675. return static_cast<int32_t>(i);
  1676. }
  1677. }
  1678. return UINT32_MAX;
  1679. }
  1680. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, const std::initializer_list<vk::MemoryPropertyFlags> & req_flags_list) {
  1681. VK_LOG_DEBUG("ggml_vk_create_buffer(" << device->name << ", " << size << ", " << to_string(req_flags_list.begin()[0]) << ", " << to_string(req_flags_list.begin()[req_flags_list.size()-1]) << ")");
  1682. if (size > device->max_memory_allocation_size) {
  1683. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device memory allocation limit");
  1684. }
  1685. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  1686. if (size == 0) {
  1687. buf->size = 0;
  1688. return buf;
  1689. }
  1690. vk::BufferCreateInfo buffer_create_info{
  1691. vk::BufferCreateFlags(),
  1692. size,
  1693. vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst,
  1694. vk::SharingMode::eExclusive,
  1695. 0,
  1696. nullptr,
  1697. };
  1698. buf->buffer = device->device.createBuffer(buffer_create_info);
  1699. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  1700. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  1701. for (auto it = req_flags_list.begin(); it != req_flags_list.end(); it++) {
  1702. const auto & req_flags = *it;
  1703. uint32_t memory_type_index = find_properties(&mem_props, &mem_req, req_flags);
  1704. if (memory_type_index == UINT32_MAX) {
  1705. continue;
  1706. }
  1707. buf->memory_property_flags = req_flags;
  1708. try {
  1709. buf->device_memory = device->device.allocateMemory({ mem_req.size, memory_type_index });
  1710. break;
  1711. } catch (const vk::SystemError& e) {
  1712. // loop and retry
  1713. // during last attempt throw the exception
  1714. if (it + 1 == req_flags_list.end()) {
  1715. device->device.destroyBuffer(buf->buffer);
  1716. throw e;
  1717. }
  1718. }
  1719. }
  1720. if (!buf->device_memory) {
  1721. device->device.destroyBuffer(buf->buffer);
  1722. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  1723. }
  1724. buf->ptr = nullptr;
  1725. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1726. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  1727. }
  1728. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  1729. buf->device = device;
  1730. buf->size = size;
  1731. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1732. device->memory_logger->log_allocation(buf, size);
  1733. #endif
  1734. return buf;
  1735. }
  1736. 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)) {
  1737. try {
  1738. return ggml_vk_create_buffer(device, size, {req_flags, fallback_flags});
  1739. } catch (const vk::SystemError& e) {
  1740. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  1741. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1742. throw e;
  1743. }
  1744. }
  1745. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  1746. vk_buffer buf;
  1747. try {
  1748. if (device->prefer_host_memory) {
  1749. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1750. vk::MemoryPropertyFlagBits::eDeviceLocal});
  1751. } else if (device->uma) {
  1752. // Fall back to host memory type
  1753. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  1754. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1755. } else if (device->disable_host_visible_vidmem) {
  1756. if (device->allow_sysmem_fallback) {
  1757. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  1758. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1759. } else {
  1760. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  1761. }
  1762. } else {
  1763. // use rebar if available, otherwise fallback to device only visible memory
  1764. if (device->allow_sysmem_fallback) {
  1765. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1766. vk::MemoryPropertyFlagBits::eDeviceLocal,
  1767. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1768. } else {
  1769. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1770. vk::MemoryPropertyFlagBits::eDeviceLocal});
  1771. }
  1772. }
  1773. } catch (const vk::SystemError& e) {
  1774. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  1775. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1776. throw e;
  1777. }
  1778. return buf;
  1779. }
  1780. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  1781. if (buf == nullptr) {
  1782. return;
  1783. }
  1784. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1785. if (buf->device != nullptr) {
  1786. buf->device->memory_logger->log_deallocation(buf);
  1787. }
  1788. #endif
  1789. buf.reset();
  1790. }
  1791. static vk_subbuffer ggml_vk_subbuffer(vk_buffer& buf) {
  1792. return { buf, 0, VK_WHOLE_SIZE };
  1793. }
  1794. static void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) {
  1795. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  1796. const bool transfer_queue = subctx->p->q->transfer_only;
  1797. if (ctx) {
  1798. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  1799. }
  1800. subctx->s->buffer.pipelineBarrier(
  1801. subctx->p->q->stage_flags,
  1802. subctx->p->q->stage_flags,
  1803. {},
  1804. { {
  1805. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  1806. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  1807. } },
  1808. {},
  1809. {}
  1810. );
  1811. }
  1812. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  1813. VK_LOG_DEBUG("ggml_vk_wait_events()");
  1814. if (events.empty()) {
  1815. return;
  1816. }
  1817. ctx->s->buffer.waitEvents(
  1818. events,
  1819. ctx->p->q->stage_flags,
  1820. ctx->p->q->stage_flags,
  1821. {},
  1822. {},
  1823. {}
  1824. );
  1825. }
  1826. // number of rows/cols for flash attention shader
  1827. static constexpr uint32_t flash_attention_num_small_rows = 32;
  1828. static constexpr uint32_t scalar_flash_attention_num_small_rows = 1;
  1829. static uint32_t get_fa_scalar_num_large_rows(uint32_t hsv) {
  1830. if (hsv >= 192) {
  1831. return 2;
  1832. } else {
  1833. return 8;
  1834. }
  1835. }
  1836. // The FA coopmat1 shader assumes 16x16x16 matrix multiply support.
  1837. // 128 threads split into four subgroups, each subgroup does 1/4
  1838. // of the Bc dimension.
  1839. static constexpr uint32_t coopmat1_flash_attention_num_large_rows = 16;
  1840. static constexpr uint32_t scalar_flash_attention_Bc = 64;
  1841. static constexpr uint32_t scalar_flash_attention_workgroup_size = 128;
  1842. static uint32_t get_fa_num_small_rows(FaCodePath path) {
  1843. if (path == FA_COOPMAT2) {
  1844. return flash_attention_num_small_rows;
  1845. } else {
  1846. return scalar_flash_attention_num_small_rows;
  1847. }
  1848. }
  1849. static std::array<uint32_t, 2> fa_rows_cols(FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows) {
  1850. GGML_UNUSED(clamp);
  1851. GGML_UNUSED(hsv);
  1852. if (path == FA_SCALAR) {
  1853. if (small_rows) {
  1854. return {scalar_flash_attention_num_small_rows, 64};
  1855. } else {
  1856. if ((hsv | hsk) & 8) {
  1857. // HSV/HSK not being a multiple of 16 makes D_split smaller, which makes cols_per_iter
  1858. // larger, and Bc needs to be >= cols_per_thread. 64 is large enough, 32 is not.
  1859. return {get_fa_scalar_num_large_rows(hsv), 64};
  1860. } else {
  1861. return {get_fa_scalar_num_large_rows(hsv), 32};
  1862. }
  1863. }
  1864. }
  1865. if (path == FA_COOPMAT1) {
  1866. if (small_rows) {
  1867. return {scalar_flash_attention_num_small_rows, scalar_flash_attention_Bc};
  1868. } else {
  1869. return {coopmat1_flash_attention_num_large_rows, scalar_flash_attention_Bc};
  1870. }
  1871. }
  1872. // small rows, large cols
  1873. if (small_rows) {
  1874. return {get_fa_num_small_rows(FA_COOPMAT2), 32};
  1875. }
  1876. // small cols to reduce register count
  1877. if (ggml_is_quantized(type) || hsk >= 256 || hsv >= 256) {
  1878. if (hsk >= 512 || hsv >= 512) {
  1879. return {32, 32};
  1880. } else {
  1881. return {64, 32};
  1882. }
  1883. }
  1884. return {64, 64};
  1885. }
  1886. static uint32_t fa_align(FaCodePath path, uint32_t hsk, uint32_t hsv, ggml_type type, bool small_rows) {
  1887. return fa_rows_cols(path, hsk, hsv, 0, type, small_rows)[1];
  1888. }
  1889. static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector<uint32_t>& warptile, bool mul_mat_id, ggml_type src0_type) {
  1890. uint32_t lut_size = 0;
  1891. switch (src0_type) {
  1892. case GGML_TYPE_IQ1_S:
  1893. case GGML_TYPE_IQ1_M:
  1894. lut_size = 2*2048;
  1895. break;
  1896. case GGML_TYPE_IQ2_XXS:
  1897. lut_size = 8*256;
  1898. break;
  1899. case GGML_TYPE_IQ2_XS:
  1900. lut_size = 8*512;
  1901. break;
  1902. case GGML_TYPE_IQ2_S:
  1903. lut_size = 8*1024;
  1904. break;
  1905. case GGML_TYPE_IQ3_XXS:
  1906. lut_size = 4*256;
  1907. break;
  1908. case GGML_TYPE_IQ3_S:
  1909. lut_size = 4*512;
  1910. break;
  1911. case GGML_TYPE_IQ4_NL:
  1912. case GGML_TYPE_IQ4_XS:
  1913. case GGML_TYPE_MXFP4:
  1914. lut_size = 4*16;
  1915. break;
  1916. default:
  1917. break;
  1918. }
  1919. // Needs to be kept up to date on shader changes
  1920. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  1921. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  1922. const uint32_t warps = warptile[0] / warptile[10];
  1923. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  1924. const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0;
  1925. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  1926. const uint32_t ballots_sh = mul_mat_id ? (warps * 4 * sizeof(uint32_t)) : 0;
  1927. const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size + ballots_sh;
  1928. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  1929. VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), "
  1930. "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported);
  1931. return supported;
  1932. }
  1933. struct GpuPipelineConfig {
  1934. // GPU architecture identifier.
  1935. // Example: vk_device_architecture::AMD_GCN
  1936. vk_device_architecture arch;
  1937. // Mapping of pipeline names to their specific subgroup sizes.
  1938. // Example: {"soft_max_f32", 64}
  1939. std::unordered_map<std::string, uint32_t> pipelines;
  1940. // Default subgroup size for this GPU.
  1941. // Defaults to 0 if not explicitly provided.
  1942. uint32_t default_subgroup_size = 0;
  1943. };
  1944. // Pipeline configuration for RDNA1 GPUs.
  1945. static const std::unordered_map<std::string, uint32_t> rdna1_pipelines = {
  1946. {"soft_max", 64}, {"im2col", 64},
  1947. {"argmax", 64}, {"mul_mat_vec", 64},
  1948. {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32}
  1949. };
  1950. // Pipeline configuration for RDNA2 GPUs.
  1951. static const std::unordered_map<std::string, uint32_t> rdna2_pipelines = {
  1952. {"soft_max", 64}, {"im2col", 64},
  1953. };
  1954. static constexpr uint32_t RDNA_DEFAULT_SUBGROUP_SIZE = 32;
  1955. // Define configurations for different GPUs.
  1956. static std::vector<GpuPipelineConfig> gpu_pipeline_configs = {
  1957. {
  1958. vk_device_architecture::AMD_RDNA1,
  1959. {
  1960. rdna1_pipelines,
  1961. },
  1962. RDNA_DEFAULT_SUBGROUP_SIZE
  1963. },
  1964. {
  1965. vk_device_architecture::AMD_RDNA2,
  1966. {
  1967. rdna2_pipelines,
  1968. },
  1969. RDNA_DEFAULT_SUBGROUP_SIZE
  1970. },
  1971. };
  1972. static uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) {
  1973. for (const auto &config : gpu_pipeline_configs) {
  1974. if (config.arch == arch) {
  1975. auto pipIt = config.pipelines.find(pipeline_name);
  1976. if (pipIt != config.pipelines.end()) {
  1977. return pipIt->second;
  1978. }
  1979. std::vector<std::pair<std::string, uint32_t>> sorted_pipelines(config.pipelines.begin(), config.pipelines.end());
  1980. std::sort(sorted_pipelines.begin(), sorted_pipelines.end(),
  1981. [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
  1982. for (const auto &entry : sorted_pipelines) {
  1983. if (pipeline_name.find(entry.first) != std::string::npos) {
  1984. return entry.second;
  1985. }
  1986. }
  1987. return config.default_subgroup_size;
  1988. }
  1989. }
  1990. return 0; // If no matching configuration is found
  1991. }
  1992. static void ggml_vk_load_shaders(vk_device& device) {
  1993. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  1994. // some shaders have a minimum subgroup size
  1995. const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u);
  1996. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  1997. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  1998. const uint32_t mul_mat_subgroup_size = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  1999. const uint32_t mul_mat_subgroup_size_8 = std::max(mul_mat_subgroup_size, 8u);
  2000. const uint32_t mul_mat_subgroup_size_16 = std::max(mul_mat_subgroup_size, 16u);
  2001. const uint32_t mul_mat_subgroup_size_32 = std::max(mul_mat_subgroup_size, 32u);
  2002. const bool subgroup_min_size_16 = (!device->subgroup_size_control && device->subgroup_size >= 16) ||
  2003. (device->subgroup_size_control && device->subgroup_max_size >= 16);
  2004. // mulmat
  2005. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  2006. l_warptile_id, m_warptile_id, s_warptile_id,
  2007. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  2008. l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int,
  2009. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  2010. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid;
  2011. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  2012. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  2013. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  2014. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  2015. uint32_t l_align, m_align, s_align;
  2016. if (device->coopmat2) {
  2017. // spec constants and tile sizes for non-quant matmul/matmul_id
  2018. l_warptile = { 256, 128, 256, 64, 1 };
  2019. m_warptile = { 256, 128, 128, 64, 0 };
  2020. s_warptile = { 128, 64, 64, 64, 0 };
  2021. l_wg_denoms = {128, 256, 1 };
  2022. m_wg_denoms = {128, 128, 1 };
  2023. s_wg_denoms = { 64, 64, 1 };
  2024. // spec constants and tile sizes for quant matmul (non-Qi_K)
  2025. l_warptile_mmq = { 256, 128, 256, 64, 1 };
  2026. m_warptile_mmq = { 256, 128, 128, 64, 1 };
  2027. s_warptile_mmq = { 256, 32, 64, 128, 0 };
  2028. l_mmq_wg_denoms = { 128, 256, 1 };
  2029. m_mmq_wg_denoms = { 128, 128, 1 };
  2030. s_mmq_wg_denoms = { 32, 64, 1 };
  2031. // spec constants and tile sizes for quant matmul (Qi_K)
  2032. l_warptile_mmq_k = { 256, 128, 256, 64, 1 };
  2033. m_warptile_mmq_k = { 256, 128, 128, 64, 1 };
  2034. s_warptile_mmq_k = { 256, 32, 64, 128, 0 };
  2035. l_mmq_wg_denoms_k = { 128, 256, 1 };
  2036. m_mmq_wg_denoms_k = { 128, 128, 1 };
  2037. s_mmq_wg_denoms_k = { 32, 64, 1 };
  2038. // spec constants and tile sizes for quant matmul_id
  2039. l_warptile_mmqid = { 256, 128, 128, 16, 1, device->subgroup_size };
  2040. m_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2041. s_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2042. l_mmqid_wg_denoms = { 128, 128, 1 };
  2043. m_mmqid_wg_denoms = { 128, 64, 1 };
  2044. s_mmqid_wg_denoms = { 128, 64, 1 };
  2045. l_align = 128;
  2046. m_align = 64;
  2047. s_align = 32;
  2048. } else {
  2049. // Matrix cores require different warp group sizes
  2050. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  2051. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  2052. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  2053. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  2054. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  2055. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  2056. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  2057. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  2058. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  2059. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2060. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2061. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2062. l_warptile_mmq = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2063. m_warptile_mmq = { 128, 64, 64, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2064. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2065. l_warptile_mmq_int = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2066. m_warptile_mmq_int = { 128, 64, 64, 32, subgroup_size_8, 32, 2, 2, 2, 1, subgroup_size_8 };
  2067. s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, subgroup_size_8 };
  2068. l_warptile_id = { 128, 128, 128, 16, mul_mat_subgroup_size_16 * 2, 64, 2, tm_l, tn_l, tk_l, mul_mat_subgroup_size_16 };
  2069. m_warptile_id = { 128, 64, 64, 16, mul_mat_subgroup_size_16, 32, 2, tm_m, tn_m, tk_m, mul_mat_subgroup_size_16 };
  2070. s_warptile_id = { mul_mat_subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_16 };
  2071. l_warptile_mmqid = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, mul_mat_subgroup_size_8 };
  2072. m_warptile_mmqid = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, mul_mat_subgroup_size_8 };
  2073. s_warptile_mmqid = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_8 };
  2074. // chip specific tuning
  2075. if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) {
  2076. m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2077. m_warptile_mmqid = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2078. }
  2079. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  2080. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  2081. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  2082. l_align = 128;
  2083. m_align = 64;
  2084. s_align = 32;
  2085. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  2086. ggml_type t = (ggml_type)i;
  2087. // Disable medium and large matrix multiplication if not enough shared memory is available
  2088. // Check mmq warptiles as the largest configuration
  2089. // Throw an error if not enough for any matrix multiplication is available
  2090. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) {
  2091. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  2092. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  2093. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) {
  2094. device->mul_mat_m[i] = false;
  2095. device->mul_mat_l[i] = false;
  2096. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) {
  2097. device->mul_mat_l[i] = false;
  2098. }
  2099. // Disable mul_mat_id if not enough shared memory is available
  2100. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmqid, true, t)) {
  2101. device->mul_mat_id_s[i] = false;
  2102. device->mul_mat_id_m[i] = false;
  2103. device->mul_mat_id_l[i] = false;
  2104. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmqid, true, t)) {
  2105. device->mul_mat_id_m[i] = false;
  2106. device->mul_mat_id_l[i] = false;
  2107. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmqid, true, t)) {
  2108. device->mul_mat_id_l[i] = false;
  2109. }
  2110. }
  2111. }
  2112. if (!device->pipeline_matmul_f32) {
  2113. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2114. }
  2115. if (!device->pipeline_matmul_f32_f16) {
  2116. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  2117. }
  2118. if (!device->pipeline_matmul_id_f32) {
  2119. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2120. }
  2121. if (!device->pipeline_matmul_bf16) {
  2122. device->pipeline_matmul_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2123. }
  2124. if (!device->pipeline_matmul_id_bf16) {
  2125. device->pipeline_matmul_id_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2126. }
  2127. std::vector<std::future<void>> compiles;
  2128. auto const &ggml_vk_create_pipeline = [&](vk_device& device, vk_pipeline& pipeline, const char *name, size_t spv_size, const void* spv_data, const char *entrypoint,
  2129. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2130. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2131. if (!require_full_subgroups && required_subgroup_size == 0) {
  2132. required_subgroup_size = get_subgroup_size(name, device->architecture);
  2133. }
  2134. if (!pipeline) {
  2135. pipeline = std::make_shared<vk_pipeline_struct>();
  2136. }
  2137. if (!pipeline->initialized) {
  2138. pipeline->name = name;
  2139. pipeline->parameter_count = parameter_count;
  2140. pipeline->push_constant_size = push_constant_size;
  2141. pipeline->wg_denoms = wg_denoms;
  2142. pipeline->align = align;
  2143. pipeline->initialized = true;
  2144. }
  2145. if (!pipeline->needed || pipeline->compiled) {
  2146. return;
  2147. }
  2148. {
  2149. // wait until fewer than N compiles are in progress
  2150. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  2151. std::unique_lock<std::mutex> guard(compile_count_mutex);
  2152. while (compile_count >= N) {
  2153. compile_count_cond.wait(guard);
  2154. }
  2155. compile_count++;
  2156. }
  2157. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  2158. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  2159. };
  2160. auto const &ggml_vk_create_pipeline2 = [&](vk_device& device, vk_pipeline& pipeline, const std::string &name, size_t spv_size, const void* spv_data, const char *entrypoint,
  2161. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2162. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2163. return ggml_vk_create_pipeline(device, pipeline, name.c_str(), spv_size, spv_data, entrypoint,
  2164. parameter_count, push_constant_size, wg_denoms, specialization_constants,
  2165. align, disable_robustness, require_full_subgroups, required_subgroup_size);
  2166. };
  2167. auto const &fa_wg_denoms = [&](FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows) -> std::array<uint32_t, 3> {
  2168. return {fa_rows_cols(path, hsk, hsv, clamp, type, small_rows)[0], 1, 1};
  2169. };
  2170. auto const &fa_spec_constants = [&](FaCodePath path, uint32_t hsk, uint32_t hsv, uint32_t clamp, ggml_type type, bool small_rows) -> std::vector<uint32_t> {
  2171. // For large number of rows, 128 invocations seems to work best.
  2172. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  2173. // can't use 256 for D==80.
  2174. // For scalar, use 128 (arbitrary)
  2175. // The same D_split value is used for both HSK and HSV, so just base it on the union of the LSBs.
  2176. const uint32_t D = (hsk|hsv);
  2177. uint32_t wg_size = (path == FA_SCALAR || path == FA_COOPMAT1)
  2178. ? scalar_flash_attention_workgroup_size
  2179. : ((small_rows && (D % 32) == 0) ? 256 : 128);
  2180. auto rows_cols = fa_rows_cols(path, hsk, hsv, clamp, type, small_rows);
  2181. // D_split can't be larger than a subgroup because we use subgroupShuffle to reduce it.
  2182. // D_split can't be larger than the LSB of D divided by 4 due to vectorization in the shader.
  2183. const uint32_t D_lsb = D ^ (D & (D-1));
  2184. uint32_t D_split = std::min(std::min(device->subgroup_size, 8u), D_lsb / 4);
  2185. // mask dim1 is padded to 64, we rely on this to avoid clamping mask loads
  2186. GGML_ASSERT((GGML_KQ_MASK_PAD % rows_cols[0]) == 0);
  2187. return {wg_size, rows_cols[0], rows_cols[1], hsk, hsv, clamp, D_split};
  2188. };
  2189. #define CREATE_FA(TYPE, NAMELC, FAPATH, SUFFIX) \
  2190. for (auto &fa : device->pipeline_flash_attn_f32_f16[TYPE]) { \
  2191. uint32_t HSK = fa.first.HSK; \
  2192. uint32_t HSV = fa.first.HSV; \
  2193. bool small_rows = fa.first.small_rows; \
  2194. FaCodePath path = fa.first.path; \
  2195. bool aligned = fa.first.aligned; \
  2196. bool f32acc = fa.first.f32acc; \
  2197. if (path == FAPATH) { \
  2198. if (aligned) { \
  2199. if (f32acc) { \
  2200. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_aligned_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_align(FAPATH,HSK,HSV,TYPE,small_rows), true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2201. } else { \
  2202. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_aligned_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_align(FAPATH,HSK,HSV,TYPE,small_rows), true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2203. } \
  2204. } else { \
  2205. if (f32acc) { \
  2206. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,1,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows), 1, true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2207. } else { \
  2208. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,1,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows), 1, true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2209. } \
  2210. } \
  2211. } \
  2212. }
  2213. CREATE_FA(GGML_TYPE_F16, f16, FA_SCALAR, )
  2214. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_SCALAR, )
  2215. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_SCALAR, )
  2216. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2217. if (device->coopmat1_fa_support) {
  2218. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT1, _cm1)
  2219. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT1, _cm1)
  2220. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT1, _cm1)
  2221. }
  2222. #endif
  2223. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2224. if (device->coopmat2) {
  2225. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT2, _cm2)
  2226. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT2, _cm2)
  2227. CREATE_FA(GGML_TYPE_Q4_1, q4_1, FA_COOPMAT2, _cm2)
  2228. CREATE_FA(GGML_TYPE_Q5_0, q5_0, FA_COOPMAT2, _cm2)
  2229. CREATE_FA(GGML_TYPE_Q5_1, q5_1, FA_COOPMAT2, _cm2)
  2230. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT2, _cm2)
  2231. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl, FA_COOPMAT2, _cm2)
  2232. }
  2233. #endif
  2234. #undef CREATE_FA
  2235. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2236. if (device->coopmat2) {
  2237. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2238. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2239. 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); \
  2240. 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); \
  2241. 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); \
  2242. 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); \
  2243. 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); \
  2244. 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); \
  2245. // Create 2 variants, {f16,f32} accumulator
  2246. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2247. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2248. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2249. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2250. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2251. if (device->coopmat_bf16_support) {
  2252. CREATE_MM(pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2253. }
  2254. #endif
  2255. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_0], matmul_q4_0_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2256. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_1], matmul_q4_1_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2257. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_0], matmul_q5_0_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2258. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_1], matmul_q5_1_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2259. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q8_0], matmul_q8_0_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2260. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q2_K], matmul_q2_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2261. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q3_K], matmul_q3_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2262. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q4_K], matmul_q4_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2263. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q5_K], matmul_q5_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2264. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_Q6_K], matmul_q6_k_f16, mmq_wg_denoms_k, warptile_mmq_k, vk_mat_mat_push_constants, 3)
  2265. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ1_S], matmul_iq1_s_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2266. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ1_M], matmul_iq1_m_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2267. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2268. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2269. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ2_S], matmul_iq2_s_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2270. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2271. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ3_S], matmul_iq3_s_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2272. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2273. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2274. CREATE_MM2(pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_MXFP4], matmul_mxfp4_f16, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3)
  2275. GGML_ASSERT(device->subgroup_ballot);
  2276. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2277. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2278. if (device->coopmat_bf16_support) {
  2279. CREATE_MM(pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2280. }
  2281. #endif
  2282. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2283. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2284. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2285. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2286. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2287. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2288. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2289. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2290. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2291. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2292. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2293. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2294. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2295. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2296. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2297. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2298. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2299. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2300. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2301. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2302. #undef CREATE_MM
  2303. #undef CREATE_MM2
  2304. } else
  2305. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2306. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2307. if (device->coopmat_support) {
  2308. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2309. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2310. if (device->mul_mat ## ID ## _l[TYPE]) \
  2311. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _cm1_len, NAMELC ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, true); \
  2312. if (device->mul_mat ## ID ## _m[TYPE]) \
  2313. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _cm1_len, NAMELC ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, true); \
  2314. if (device->mul_mat ## ID ## _s[TYPE]) \
  2315. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _cm1_len, NAMELC ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, true); \
  2316. if (device->mul_mat ## ID ## _l[TYPE]) \
  2317. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _cm1_len, NAMELC ## _aligned ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, true); \
  2318. if (device->mul_mat ## ID ## _m[TYPE]) \
  2319. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _cm1_len, NAMELC ## _aligned ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, true); \
  2320. if (device->mul_mat ## ID ## _s[TYPE]) \
  2321. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _cm1_len, NAMELC ## _aligned ## F16ACC ## _cm1_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, true); \
  2322. // Create 2 variants, {f16,f32} accumulator
  2323. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2324. if (device->coopmat_acc_f16_support) { \
  2325. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2326. } \
  2327. if (device->coopmat_acc_f32_support) { \
  2328. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2329. } \
  2330. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2331. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2332. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2333. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2334. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2335. if (device->coopmat_bf16_support) {
  2336. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, )
  2337. }
  2338. #endif
  2339. if (device->coopmat_acc_f16_support) {
  2340. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0], matmul_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2341. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1], matmul_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2342. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0], matmul_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2343. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1], matmul_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2344. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0], matmul_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2345. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K], matmul_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2346. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K], matmul_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2347. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K], matmul_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2348. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K], matmul_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2349. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K], matmul_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2350. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S], matmul_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2351. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M], matmul_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2352. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2353. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2354. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S], matmul_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2355. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2356. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S], matmul_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2357. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2358. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2359. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4], matmul_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2360. } else {
  2361. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2362. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2363. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2364. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2365. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2366. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2367. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2368. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2369. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2370. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2371. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S].f32acc, matmul_iq1_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2372. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M].f32acc, matmul_iq1_m_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2373. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS].f32acc, matmul_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2374. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS].f32acc, matmul_iq2_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2375. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S].f32acc, matmul_iq2_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2376. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS].f32acc, matmul_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2377. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S].f32acc, matmul_iq3_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2378. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS].f32acc, matmul_iq4_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2379. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f32acc, matmul_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2380. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4].f32acc, matmul_mxfp4_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, );
  2381. }
  2382. GGML_ASSERT(device->subgroup_ballot);
  2383. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2384. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2385. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2386. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2387. if (device->coopmat_bf16_support) {
  2388. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2389. }
  2390. #endif
  2391. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2392. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2393. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2394. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2395. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2396. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2397. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2398. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2399. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2400. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2401. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2402. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2403. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2404. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2405. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2406. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2407. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2408. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2409. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2410. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2411. #undef CREATE_MM2
  2412. #undef CREATE_MM
  2413. } else
  2414. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2415. if (device->fp16) {
  2416. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2417. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2418. if (device->mul_mat ## ID ## _l[TYPE]) \
  2419. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2420. if (device->mul_mat ## ID ## _m[TYPE]) \
  2421. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2422. if (device->mul_mat ## ID ## _s[TYPE]) \
  2423. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2424. if (device->mul_mat ## ID ## _l[TYPE]) \
  2425. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2426. if (device->mul_mat ## ID ## _m[TYPE]) \
  2427. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2428. if (device->mul_mat ## ID ## _s[TYPE]) \
  2429. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2430. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2431. if (device->mul_mat ## ID ## _l[TYPE]) { \
  2432. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f16acc->l, #NAMELC "_f16acc_l", NAMELC ## _f16acc_len, NAMELC ## _f16acc_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  2433. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->l, #NAMELC "_l", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  2434. } \
  2435. if (device->mul_mat ## ID ## _m[TYPE]) { \
  2436. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f16acc->m, #NAMELC "_f16acc_m", NAMELC ## _f16acc_len, NAMELC ## _f16acc_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  2437. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->m, #NAMELC "_m", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  2438. } \
  2439. if (device->mul_mat ## ID ## _s[TYPE]) { \
  2440. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f16acc->s, #NAMELC "_f16acc_s", NAMELC ## _f16acc_len, NAMELC ## _f16acc_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  2441. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->s, #NAMELC "_s", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  2442. } \
  2443. // Create 2 variants, {f16,f32} accumulator
  2444. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2445. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2446. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2447. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2448. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2449. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2450. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2451. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2452. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0], matmul_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2453. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1], matmul_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2454. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0], matmul_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2455. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1], matmul_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2456. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0], matmul_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2457. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K], matmul_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2458. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K], matmul_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2459. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K], matmul_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2460. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K], matmul_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2461. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K], matmul_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2462. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S], matmul_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2463. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M], matmul_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2464. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2465. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2466. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S], matmul_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2467. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2468. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S], matmul_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2469. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2470. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2471. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4], matmul_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2472. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2473. if (device->integer_dot_product) {
  2474. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_0], matmul_q4_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2475. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_1], matmul_q4_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2476. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_0], matmul_q5_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2477. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_1], matmul_q5_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2478. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q8_0], matmul_q8_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2479. }
  2480. #endif
  2481. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2482. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2483. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2484. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2485. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2486. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2487. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2488. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2489. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2490. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2491. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2492. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2493. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2494. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2495. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2496. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2497. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2498. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2499. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2500. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2501. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2502. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2503. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2504. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2505. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2506. } else {
  2507. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2508. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2509. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2510. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2511. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2512. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2513. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2514. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2515. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2516. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2517. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2518. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2519. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2520. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2521. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2522. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2523. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2524. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2525. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2526. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2527. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2528. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2529. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2530. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2531. }
  2532. #undef CREATE_MM2
  2533. #undef CREATE_MMQ
  2534. #undef CREATE_MM
  2535. } else {
  2536. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2537. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2538. if (device->mul_mat ## ID ## _l[TYPE]) \
  2539. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2540. if (device->mul_mat ## ID ## _m[TYPE]) \
  2541. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2542. if (device->mul_mat ## ID ## _s[TYPE]) \
  2543. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2544. if (device->mul_mat ## ID ## _l[TYPE]) \
  2545. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2546. if (device->mul_mat ## ID ## _m[TYPE]) \
  2547. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2548. if (device->mul_mat ## ID ## _s[TYPE]) \
  2549. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2550. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2551. if (device->mul_mat ## ID ## _l[TYPE]) \
  2552. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC "_l", NAMELC ## _fp32_len, NAMELC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1); \
  2553. if (device->mul_mat ## ID ## _m[TYPE]) \
  2554. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC "_m", NAMELC ## _fp32_len, NAMELC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1); \
  2555. if (device->mul_mat ## ID ## _s[TYPE]) \
  2556. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC "_s", NAMELC ## _fp32_len, NAMELC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1); \
  2557. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2558. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2559. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2560. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2561. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2562. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2563. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2564. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2565. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2566. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2567. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2568. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2569. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2570. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2571. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2572. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S].f32acc, matmul_iq1_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2573. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M].f32acc, matmul_iq1_m_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2574. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS].f32acc, matmul_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2575. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS].f32acc, matmul_iq2_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2576. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S].f32acc, matmul_iq2_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2577. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS].f32acc, matmul_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2578. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S].f32acc, matmul_iq3_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2579. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS].f32acc, matmul_iq4_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2580. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f32acc, matmul_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2581. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4].f32acc, matmul_mxfp4_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2582. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2583. if (device->integer_dot_product) {
  2584. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2585. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2586. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2587. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2588. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, );
  2589. }
  2590. #endif
  2591. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2592. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2593. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_subgroup_f16, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2594. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_subgroup_f16_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2595. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2596. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_subgroup_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2597. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_subgroup_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2598. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_subgroup_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2599. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_subgroup_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2600. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_subgroup_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2601. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_subgroup_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2602. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_subgroup_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2603. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_subgroup_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2604. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_subgroup_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2605. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_subgroup_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2606. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_subgroup_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2607. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_subgroup_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2608. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_subgroup_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2609. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_subgroup_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2610. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_subgroup_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2611. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_subgroup_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2612. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_subgroup_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2613. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_subgroup_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2614. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_subgroup_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2615. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_subgroup_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2616. } else {
  2617. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2618. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2619. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2620. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2621. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2622. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2623. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2624. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2625. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2626. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2627. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2628. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2629. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2630. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2631. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2632. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2633. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2634. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2635. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2636. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2637. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2638. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2639. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2640. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2641. }
  2642. }
  2643. // reusing CREATE_MM from the fp32 path
  2644. if ((device->coopmat2 || device->coopmat_support)
  2645. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2646. && !device->coopmat_bf16_support
  2647. #endif
  2648. ) {
  2649. // use scalar tile sizes
  2650. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2651. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, 4, 2, 1, subgroup_size_8 };
  2652. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, 2, 2, 1, subgroup_size_8 };
  2653. l_wg_denoms = {128, 128, 1 };
  2654. m_wg_denoms = { 64, 64, 1 };
  2655. s_wg_denoms = { 32, 32, 1 };
  2656. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2657. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2658. }
  2659. #undef CREATE_MM
  2660. // mul mat vec
  2661. // the number of rows computed per shader depends on GPU model and quant
  2662. uint32_t rm_stdq = 1;
  2663. uint32_t rm_kq = 2;
  2664. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  2665. if (device->architecture == AMD_GCN) {
  2666. rm_stdq = 2;
  2667. rm_kq = 4;
  2668. }
  2669. } else if (device->vendor_id == VK_VENDOR_ID_INTEL)
  2670. rm_stdq = 2;
  2671. uint32_t rm_iq = 2 * rm_kq;
  2672. const bool use_subgroups = device->subgroup_arithmetic && device->architecture != vk_device_architecture::AMD_GCN;
  2673. // Ensure a subgroup size >= 16 is available
  2674. const bool use_subgroups16 = use_subgroups && subgroup_min_size_16;
  2675. const uint32_t subgroup_size = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control && device->subgroup_min_size <= 16 && device->subgroup_max_size >= 16) ? 16 : device->subgroup_size;
  2676. const uint32_t subgroup_size16 = std::max(subgroup_size, 16u);
  2677. const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0;
  2678. const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0;
  2679. for (uint32_t w = 0; w < DMMV_WG_SIZE_COUNT; ++w) {
  2680. const uint32_t wg_size_subgroup = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size : (subgroup_size * 4);
  2681. const uint32_t wg_size_subgroup16 = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size16 : (subgroup_size16 * 4);
  2682. const shader_reduction_mode reduc = (use_subgroups && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  2683. (use_subgroups && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  2684. SHADER_REDUCTION_MODE_SHMEM;
  2685. const shader_reduction_mode reduc16 = (use_subgroups16 && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  2686. (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  2687. SHADER_REDUCTION_MODE_SHMEM;
  2688. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  2689. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f32_f32", arr_dmmv_f32_f32_f32_len[reduc], arr_dmmv_f32_f32_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2690. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f32_f32", arr_dmmv_f16_f32_f32_len[reduc], arr_dmmv_f16_f32_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2691. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f32_f32", arr_dmmv_bf16_f32_f32_len[reduc], arr_dmmv_bf16_f32_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2692. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f32_f32", arr_dmmv_q4_0_f32_f32_len[reduc], arr_dmmv_q4_0_f32_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2693. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f32_f32", arr_dmmv_q4_1_f32_f32_len[reduc], arr_dmmv_q4_1_f32_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2694. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f32_f32", arr_dmmv_q5_0_f32_f32_len[reduc], arr_dmmv_q5_0_f32_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2695. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f32_f32", arr_dmmv_q5_1_f32_f32_len[reduc], arr_dmmv_q5_1_f32_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2696. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f32_f32", arr_dmmv_q8_0_f32_f32_len[reduc], arr_dmmv_q8_0_f32_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2697. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f32_f32", arr_dmmv_q2_k_f32_f32_len[reduc16], arr_dmmv_q2_k_f32_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2698. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f32_f32", arr_dmmv_q3_k_f32_f32_len[reduc16], arr_dmmv_q3_k_f32_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2699. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f32_f32", arr_dmmv_q4_k_f32_f32_len[reduc16], arr_dmmv_q4_k_f32_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2700. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f32_f32", arr_dmmv_q5_k_f32_f32_len[reduc16], arr_dmmv_q5_k_f32_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2701. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f32_f32", arr_dmmv_q6_k_f32_f32_len[reduc16], arr_dmmv_q6_k_f32_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2702. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f32_f32", arr_dmmv_iq1_s_f32_f32_len[reduc16], arr_dmmv_iq1_s_f32_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2703. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f32_f32", arr_dmmv_iq1_m_f32_f32_len[reduc16], arr_dmmv_iq1_m_f32_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2704. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f32_f32", arr_dmmv_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_iq2_xxs_f32_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2705. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f32_f32", arr_dmmv_iq2_xs_f32_f32_len[reduc16], arr_dmmv_iq2_xs_f32_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2706. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f32_f32", arr_dmmv_iq2_s_f32_f32_len[reduc16], arr_dmmv_iq2_s_f32_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2707. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f32_f32", arr_dmmv_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_iq3_xxs_f32_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2708. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f32_f32", arr_dmmv_iq3_s_f32_f32_len[reduc16], arr_dmmv_iq3_s_f32_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2709. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f32_f32", arr_dmmv_iq4_xs_f32_f32_len[reduc16], arr_dmmv_iq4_xs_f32_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2710. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f32_f32", arr_dmmv_iq4_nl_f32_f32_len[reduc16], arr_dmmv_iq4_nl_f32_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2711. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f32_f32", arr_dmmv_mxfp4_f32_f32_len[reduc16], arr_dmmv_mxfp4_f32_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2712. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f16_f32", arr_dmmv_f32_f16_f32_len[reduc], arr_dmmv_f32_f16_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2713. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f16_f32", arr_dmmv_f16_f16_f32_len[reduc], arr_dmmv_f16_f16_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2714. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f16_f32", arr_dmmv_bf16_f16_f32_len[reduc], arr_dmmv_bf16_f16_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  2715. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f16_f32", arr_dmmv_q4_0_f16_f32_len[reduc], arr_dmmv_q4_0_f16_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2716. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f16_f32", arr_dmmv_q4_1_f16_f32_len[reduc], arr_dmmv_q4_1_f16_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2717. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f16_f32", arr_dmmv_q5_0_f16_f32_len[reduc], arr_dmmv_q5_0_f16_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2718. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f16_f32", arr_dmmv_q5_1_f16_f32_len[reduc], arr_dmmv_q5_1_f16_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2719. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f16_f32", arr_dmmv_q8_0_f16_f32_len[reduc], arr_dmmv_q8_0_f16_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  2720. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f16_f32", arr_dmmv_q2_k_f16_f32_len[reduc16], arr_dmmv_q2_k_f16_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2721. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f16_f32", arr_dmmv_q3_k_f16_f32_len[reduc16], arr_dmmv_q3_k_f16_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2722. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f16_f32", arr_dmmv_q4_k_f16_f32_len[reduc16], arr_dmmv_q4_k_f16_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2723. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f16_f32", arr_dmmv_q5_k_f16_f32_len[reduc16], arr_dmmv_q5_k_f16_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2724. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f16_f32", arr_dmmv_q6_k_f16_f32_len[reduc16], arr_dmmv_q6_k_f16_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2725. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f16_f32", arr_dmmv_iq1_s_f16_f32_len[reduc16], arr_dmmv_iq1_s_f16_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2726. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f16_f32", arr_dmmv_iq1_m_f16_f32_len[reduc16], arr_dmmv_iq1_m_f16_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2727. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f16_f32", arr_dmmv_iq2_xxs_f16_f32_len[reduc16], arr_dmmv_iq2_xxs_f16_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2728. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f16_f32", arr_dmmv_iq2_xs_f16_f32_len[reduc16], arr_dmmv_iq2_xs_f16_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2729. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f16_f32", arr_dmmv_iq2_s_f16_f32_len[reduc16], arr_dmmv_iq2_s_f16_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2730. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f16_f32", arr_dmmv_iq3_xxs_f16_f32_len[reduc16], arr_dmmv_iq3_xxs_f16_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2731. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f16_f32", arr_dmmv_iq3_s_f16_f32_len[reduc16], arr_dmmv_iq3_s_f16_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2732. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f16_f32", arr_dmmv_iq4_xs_f16_f32_len[reduc16], arr_dmmv_iq4_xs_f16_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2733. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f16_f32", arr_dmmv_iq4_nl_f16_f32_len[reduc16], arr_dmmv_iq4_nl_f16_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2734. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f16_f32", arr_dmmv_mxfp4_f16_f32_len[reduc16], arr_dmmv_mxfp4_f16_f32_data[reduc16], "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  2735. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2736. if (device->integer_dot_product) {
  2737. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  2738. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  2739. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_q8_1_f32", arr_dmmv_q4_0_q8_1_f32_len[reduc], arr_dmmv_q4_0_q8_1_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2740. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_q8_1_f32", arr_dmmv_q4_1_q8_1_f32_len[reduc], arr_dmmv_q4_1_q8_1_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2741. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_q8_1_f32", arr_dmmv_q5_0_q8_1_f32_len[reduc], arr_dmmv_q5_0_q8_1_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2742. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_q8_1_f32", arr_dmmv_q5_1_q8_1_f32_len[reduc], arr_dmmv_q5_1_q8_1_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2743. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_q8_1_f32", arr_dmmv_q8_0_q8_1_f32_len[reduc], arr_dmmv_q8_0_q8_1_f32_data[reduc], "main", 3, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  2744. }
  2745. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  2746. }
  2747. }
  2748. 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);
  2749. 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);
  2750. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_BF16], "mul_mat_vec_id_bf16_f32", mul_mat_vec_id_bf16_f32_len, mul_mat_vec_id_bf16_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  2751. 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);
  2752. 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);
  2753. 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);
  2754. 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);
  2755. 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);
  2756. 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);
  2757. 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);
  2758. 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);
  2759. 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);
  2760. 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);
  2761. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ1_S], "mul_mat_vec_id_iq1_s_f32", mul_mat_vec_id_iq1_s_f32_len, mul_mat_vec_id_iq1_s_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2762. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ1_M], "mul_mat_vec_id_iq1_m_f32", mul_mat_vec_id_iq1_m_f32_len, mul_mat_vec_id_iq1_m_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2763. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ2_XXS], "mul_mat_vec_id_iq2_xxs_f32", mul_mat_vec_id_iq2_xxs_f32_len, mul_mat_vec_id_iq2_xxs_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2764. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ2_XS], "mul_mat_vec_id_iq2_xs_f32", mul_mat_vec_id_iq2_xs_f32_len, mul_mat_vec_id_iq2_xs_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2765. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ2_S], "mul_mat_vec_id_iq2_s_f32", mul_mat_vec_id_iq2_s_f32_len, mul_mat_vec_id_iq2_s_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2766. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ3_XXS], "mul_mat_vec_id_iq3_xxs_f32", mul_mat_vec_id_iq3_xxs_f32_len, mul_mat_vec_id_iq3_xxs_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2767. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ3_S], "mul_mat_vec_id_iq3_s_f32", mul_mat_vec_id_iq3_s_f32_len, mul_mat_vec_id_iq3_s_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2768. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ4_XS], "mul_mat_vec_id_iq4_xs_f32", mul_mat_vec_id_iq4_xs_f32_len, mul_mat_vec_id_iq4_xs_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2769. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_IQ4_NL], "mul_mat_vec_id_iq4_nl_f32", mul_mat_vec_id_iq4_nl_f32_len, mul_mat_vec_id_iq4_nl_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2770. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_f32", mul_mat_vec_id_mxfp4_f32_len, mul_mat_vec_id_mxfp4_f32_data, "main", 4, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  2771. // dequant shaders
  2772. 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);
  2773. 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);
  2774. 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);
  2775. 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);
  2776. 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);
  2777. 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);
  2778. 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);
  2779. 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);
  2780. 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);
  2781. 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);
  2782. 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);
  2783. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ1_S], "dequant_iq1_s", dequant_iq1_s_len, dequant_iq1_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  2784. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ1_M], "dequant_iq1_m", dequant_iq1_m_len, dequant_iq1_m_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  2785. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_XXS], "dequant_iq2_xxs", dequant_iq2_xxs_len, dequant_iq2_xxs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  2786. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_XS], "dequant_iq2_xs", dequant_iq2_xs_len, dequant_iq2_xs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  2787. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ2_S], "dequant_iq2_s", dequant_iq2_s_len, dequant_iq2_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  2788. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ3_XXS], "dequant_iq3_xxs", dequant_iq3_xxs_len, dequant_iq3_xxs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  2789. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ3_S], "dequant_iq3_s", dequant_iq3_s_len, dequant_iq3_s_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  2790. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ4_XS], "dequant_iq4_xs", dequant_iq4_xs_len, dequant_iq4_xs_data, "main", 2, 5 * sizeof(uint32_t), {256 * 32, 1, 1}, {}, 1);
  2791. 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);
  2792. ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_MXFP4], "dequant_mxfp4", dequant_mxfp4_len, dequant_mxfp4_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
  2793. // get_rows
  2794. 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);
  2795. 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);
  2796. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_BF16], "get_rows_bf16", get_rows_bf16_len, get_rows_bf16_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  2797. 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);
  2798. 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);
  2799. 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);
  2800. 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);
  2801. 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);
  2802. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ1_S], "get_rows_iq1_s", get_rows_iq1_s_len, get_rows_iq1_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2803. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ1_M], "get_rows_iq1_m", get_rows_iq1_m_len, get_rows_iq1_m_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2804. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_XXS], "get_rows_iq2_xxs", get_rows_iq2_xxs_len, get_rows_iq2_xxs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2805. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_XS], "get_rows_iq2_xs", get_rows_iq2_xs_len, get_rows_iq2_xs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2806. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ2_S], "get_rows_iq2_s", get_rows_iq2_s_len, get_rows_iq2_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2807. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ3_XXS], "get_rows_iq3_xxs", get_rows_iq3_xxs_len, get_rows_iq3_xxs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2808. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ3_S], "get_rows_iq3_s", get_rows_iq3_s_len, get_rows_iq3_s_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2809. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ4_XS], "get_rows_iq4_xs", get_rows_iq4_xs_len, get_rows_iq4_xs_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2810. 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);
  2811. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_MXFP4], "get_rows_mxfp4", get_rows_mxfp4_len, get_rows_mxfp4_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2812. 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);
  2813. 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);
  2814. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_BF16], "get_rows_bf16_f32", get_rows_bf16_f32_len, get_rows_bf16_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
  2815. 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);
  2816. 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);
  2817. 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);
  2818. 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);
  2819. 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);
  2820. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ1_S], "get_rows_iq1_s_f32", get_rows_iq1_s_f32_len, get_rows_iq1_s_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2821. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ1_M], "get_rows_iq1_m_f32", get_rows_iq1_m_f32_len, get_rows_iq1_m_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2822. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ2_XXS], "get_rows_iq2_xxs_f32", get_rows_iq2_xxs_f32_len, get_rows_iq2_xxs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2823. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ2_XS], "get_rows_iq2_xs_f32", get_rows_iq2_xs_f32_len, get_rows_iq2_xs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2824. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ2_S], "get_rows_iq2_s_f32", get_rows_iq2_s_f32_len, get_rows_iq2_s_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2825. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ3_XXS], "get_rows_iq3_xxs_f32", get_rows_iq3_xxs_f32_len, get_rows_iq3_xxs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2826. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ3_S], "get_rows_iq3_s_f32", get_rows_iq3_s_f32_len, get_rows_iq3_s_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2827. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ4_XS], "get_rows_iq4_xs_f32", get_rows_iq4_xs_f32_len, get_rows_iq4_xs_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2828. 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);
  2829. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_MXFP4], "get_rows_mxfp4_f32", get_rows_mxfp4_f32_len, get_rows_mxfp4_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2830. 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);
  2831. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_split_k_reduce, "fa_split_k_reduce", fa_split_k_reduce_len, fa_split_k_reduce_data, "main", 3, 5 * sizeof(uint32_t), {1, device->subgroup_size, 1}, {device->subgroup_size}, 1, true);
  2832. if (device->subgroup_clustered && device->subgroup_require_full_support) {
  2833. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1, "quantize_q8_1", quantize_q8_1_subgroup_len, quantize_q8_1_subgroup_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1, true, true);
  2834. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1_x4, "quantize_q8_1_x4", quantize_q8_1_x4_subgroup_len, quantize_q8_1_x4_subgroup_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1, true, true);
  2835. } else {
  2836. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1, "quantize_q8_1", quantize_q8_1_len, quantize_q8_1_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1);
  2837. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1_x4, "quantize_q8_1_x4", quantize_q8_1_x4_len, quantize_q8_1_x4_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1);
  2838. }
  2839. for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) {
  2840. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  2841. ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_subgroup_add_len, mul_mat_vec_p021_f16_f32_subgroup_add_data, "main", 3, 6 * sizeof(uint32_t), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true, true);
  2842. } else {
  2843. ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_len, mul_mat_vec_p021_f16_f32_data, "main", 3, 6 * sizeof(uint32_t), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true);
  2844. }
  2845. }
  2846. ggml_vk_create_pipeline(device, device->pipeline_mul_mat_vec_nc_f16_f32, "mul_mat_vec_nc_f16_f32", mul_mat_vec_nc_f16_f32_len, mul_mat_vec_nc_f16_f32_data, "main", 3, 12 * sizeof(uint32_t), {1, 1, 1}, {}, 1);
  2847. 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);
  2848. 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);
  2849. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_f32, "rms_norm_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0}, 1, true);
  2850. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_f32, "rms_norm_mul_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  2851. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_partials_f32, "rms_norm_partials_f32", rms_norm_partials_f32_len, rms_norm_partials_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0}, 1, true);
  2852. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_partials_f32, "rms_norm_mul_partials_f32", rms_norm_partials_f32_len, rms_norm_partials_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  2853. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_back_f32, "rms_norm_back_f32", rms_norm_back_f32_len, rms_norm_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  2854. ggml_vk_create_pipeline(device, device->pipeline_l2_norm_f32, "l2_norm_f32", l2_norm_f32_len, l2_norm_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, {}, 1);
  2855. 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);
  2856. 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);
  2857. 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);
  2858. ggml_vk_create_pipeline(device, device->pipeline_cpy_f16_f32, "cpy_f16_f32", cpy_f16_f32_len, cpy_f16_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  2859. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_bf16,"cpy_f32_bf16",cpy_f32_bf16_len,cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  2860. ggml_vk_create_pipeline(device, device->pipeline_cpy_i32_f32, "cpy_i32_f32", cpy_i32_f32_len, cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  2861. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_i32, "cpy_f32_i32", cpy_f32_i32_len, cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  2862. 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);
  2863. 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);
  2864. 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);
  2865. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f16_f32, "contig_cpy_f16_f32", contig_cpy_f16_f32_len, contig_cpy_f16_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  2866. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_bf16,"contig_cpy_f32_bf16",contig_cpy_f32_bf16_len,contig_cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  2867. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_i32_f32, "contig_cpy_i32_f32", contig_cpy_i32_f32_len, contig_cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  2868. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_i32, "contig_cpy_f32_i32", contig_cpy_f32_i32_len, contig_cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  2869. if (device->float_controls_rte_fp16) {
  2870. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_0], "cpy_f32_q4_0", cpy_f32_q4_0_rte_len, cpy_f32_q4_0_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  2871. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_1], "cpy_f32_q4_1", cpy_f32_q4_1_rte_len, cpy_f32_q4_1_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  2872. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_0], "cpy_f32_q5_0", cpy_f32_q5_0_rte_len, cpy_f32_q5_0_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  2873. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_1], "cpy_f32_q5_1", cpy_f32_q5_1_rte_len, cpy_f32_q5_1_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  2874. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q8_0], "cpy_f32_q8_0", cpy_f32_q8_0_rte_len, cpy_f32_q8_0_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  2875. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_IQ4_NL], "cpy_f32_iq4_nl", cpy_f32_iq4_nl_rte_len, cpy_f32_iq4_nl_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  2876. } else {
  2877. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_0], "cpy_f32_q4_0", cpy_f32_q4_0_len, cpy_f32_q4_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  2878. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q4_1], "cpy_f32_q4_1", cpy_f32_q4_1_len, cpy_f32_q4_1_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  2879. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_0], "cpy_f32_q5_0", cpy_f32_q5_0_len, cpy_f32_q5_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  2880. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q5_1], "cpy_f32_q5_1", cpy_f32_q5_1_len, cpy_f32_q5_1_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  2881. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_Q8_0], "cpy_f32_q8_0", cpy_f32_q8_0_len, cpy_f32_q8_0_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  2882. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_quant[GGML_TYPE_IQ4_NL], "cpy_f32_iq4_nl", cpy_f32_iq4_nl_len, cpy_f32_iq4_nl_data, "main", 2, sizeof(vk_op_unary_push_constants), {32, 1, 1}, {}, 1);
  2883. }
  2884. #define SET_ROWS(itype, rte) \
  2885. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_F32], "set_rows_f32" #itype, set_rows_f32 ## itype ## rte ## _len, set_rows_f32 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  2886. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_F16], "set_rows_f16" #itype, set_rows_f16 ## itype ## rte ## _len, set_rows_f16 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  2887. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_BF16], "set_rows_bf16" #itype, set_rows_bf16 ## itype ## rte ## _len, set_rows_bf16 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  2888. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q4_0], "set_rows_q4_0" #itype, set_rows_q4_0 ## itype ## rte ## _len, set_rows_q4_0 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  2889. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q4_1], "set_rows_q4_1" #itype, set_rows_q4_1 ## itype ## rte ## _len, set_rows_q4_1 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  2890. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q5_0], "set_rows_q5_0" #itype, set_rows_q5_0 ## itype ## rte ## _len, set_rows_q5_0 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  2891. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q5_1], "set_rows_q5_1" #itype, set_rows_q5_1 ## itype ## rte ## _len, set_rows_q5_1 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  2892. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q8_0], "set_rows_q8_0" #itype, set_rows_q8_0 ## itype ## rte ## _len, set_rows_q8_0 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  2893. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_IQ4_NL], "set_rows_iq4_nl" #itype, set_rows_iq4_nl ## itype ## rte ## _len, set_rows_iq4_nl ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2894. if (device->float_controls_rte_fp16) {
  2895. SET_ROWS(_i32, _rte)
  2896. SET_ROWS(_i64, _rte)
  2897. } else {
  2898. SET_ROWS(_i32, )
  2899. SET_ROWS(_i64, )
  2900. }
  2901. #undef SET_ROWS
  2902. 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);
  2903. 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);
  2904. 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);
  2905. 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);
  2906. 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);
  2907. 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);
  2908. auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) {
  2909. std::string s;
  2910. s += std::string(src0_f16 ? "_f16" : "_f32");
  2911. s += std::string(src1_f16 ? "_f16" : "_f32");
  2912. s += std::string(dst_f16 ? "_f16" : "_f32");
  2913. return s;
  2914. };
  2915. bool rte = device->float_controls_rte_fp16;
  2916. #define CREATE_BINARY(name, namemod, spec, bindings) \
  2917. for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \
  2918. ggml_vk_create_pipeline2(device, device->pipeline_ ## name ## namemod[s0][s1][d], \
  2919. #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d][rte], name ## _data[s0][s1][d][rte], \
  2920. "main", (bindings), sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1);
  2921. CREATE_BINARY(add, , {0}, 4)
  2922. CREATE_BINARY(add, _norepeat, {1}, 4)
  2923. CREATE_BINARY(sub, , {0}, 3)
  2924. CREATE_BINARY(sub, _norepeat, {1}, 3)
  2925. CREATE_BINARY(mul, , {0}, 3)
  2926. CREATE_BINARY(mul, _norepeat, {1}, 3)
  2927. CREATE_BINARY(div, , {0}, 3)
  2928. CREATE_BINARY(div, _norepeat, {1}, 3)
  2929. CREATE_BINARY(add_rms, , {0}, 4)
  2930. CREATE_BINARY(add_rms, _norepeat, {1}, 4)
  2931. #undef CREATE_BINARY
  2932. if (device->multi_add) {
  2933. for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) {
  2934. ggml_vk_create_pipeline2(device, device->pipeline_multi_add[i], "multi_add_f32_" + std::to_string(i+1), multi_add_f32_len, multi_add_f32_data, "main", MAX_PARAMETER_COUNT, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1);
  2935. ggml_vk_create_pipeline2(device, device->pipeline_multi_add_rms[i], "multi_add_rms_f32_" + std::to_string(i+1), multi_add_rms_f32_len, multi_add_rms_f32_data, "main", MAX_PARAMETER_COUNT, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1);
  2936. }
  2937. }
  2938. ggml_vk_create_pipeline(device, device->pipeline_add_id_f32, "add_id_f32", add_id_f32_len, add_id_f32_data, "main", 4, sizeof(vk_op_add_id_push_constants), {1, 1, 1}, {}, 1);
  2939. 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);
  2940. 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);
  2941. 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);
  2942. 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);
  2943. ggml_vk_create_pipeline(device, device->pipeline_upscale_nearest_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_NEAREST}, 1);
  2944. ggml_vk_create_pipeline(device, device->pipeline_upscale_bilinear_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BILINEAR}, 1);
  2945. ggml_vk_create_pipeline(device, device->pipeline_upscale_bilinear_ac_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ALIGN_CORNERS}, 1);
  2946. 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);
  2947. 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);
  2948. ggml_vk_create_pipeline(device, device->pipeline_sqrt_f32, "sqrt_f32", sqrt_f32_len, sqrt_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  2949. 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);
  2950. 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);
  2951. 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);
  2952. ggml_vk_create_pipeline(device, device->pipeline_pad_f32, "pad_f32", pad_f32_len, pad_f32_data, "main", 2, sizeof(vk_op_pad_push_constants), {512, 1, 1}, {}, 1);
  2953. ggml_vk_create_pipeline(device, device->pipeline_roll_f32, "roll_f32", roll_f32_len, roll_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  2954. 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);
  2955. ggml_vk_create_pipeline(device, device->pipeline_repeat_back_f32, "repeat_back_f32", repeat_back_f32_len, repeat_back_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  2956. #define CREATE_UNARY(name) \
  2957. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  2958. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  2959. CREATE_UNARY(gelu)
  2960. CREATE_UNARY(gelu_erf)
  2961. CREATE_UNARY(gelu_quick)
  2962. CREATE_UNARY(silu)
  2963. CREATE_UNARY(relu)
  2964. CREATE_UNARY(tanh)
  2965. CREATE_UNARY(sigmoid)
  2966. CREATE_UNARY(hardsigmoid)
  2967. CREATE_UNARY(hardswish)
  2968. #undef CREATE_UNARY
  2969. #define CREATE_UNARY_RTE(name) \
  2970. if (device->float_controls_rte_fp16) { \
  2971. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32_rte", name ## _f32_rte_len, name ## _f32_rte_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  2972. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16_rte", name ## _f16_rte_len, name ## _f16_rte_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  2973. } else { \
  2974. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  2975. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  2976. }
  2977. CREATE_UNARY_RTE(exp)
  2978. #undef CREATE_UNARY_RTE
  2979. #define CREATE_GLU(name) \
  2980. if (device->float_controls_rte_fp16) { \
  2981. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32_rte", name ## _f32_rte_len, name ## _f32_rte_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  2982. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16_rte", name ## _f16_rte_len, name ## _f16_rte_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  2983. } else { \
  2984. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  2985. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \
  2986. }
  2987. CREATE_GLU(geglu)
  2988. CREATE_GLU(reglu)
  2989. CREATE_GLU(swiglu)
  2990. CREATE_GLU(swiglu_oai)
  2991. CREATE_GLU(geglu_erf)
  2992. CREATE_GLU(geglu_quick)
  2993. #undef CREATE_GLU
  2994. 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);
  2995. ggml_vk_create_pipeline(device, device->pipeline_silu_back_f32, "silu_back_f32", silu_back_f32_len, silu_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  2996. 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);
  2997. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32, "soft_max_f32", soft_max_f32_len, soft_max_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  2998. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_wg512, "soft_max_f32_wg512", soft_max_f32_len, soft_max_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  2999. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16, "soft_max_f32_f16", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3000. ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16_wg512, "soft_max_f32_f16_wg512", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1);
  3001. ggml_vk_create_pipeline(device, device->pipeline_soft_max_back_f32, "soft_max_back_f32", soft_max_back_f32_len, soft_max_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1, true);
  3002. 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);
  3003. 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);
  3004. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f32, "rope_multi_f32", rope_multi_f32_len, rope_multi_f32_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3005. ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f32, "rope_vision_f32", rope_vision_f32_len, rope_vision_f32_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3006. if (device->float_controls_rte_fp16) {
  3007. 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);
  3008. 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);
  3009. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f16, "rope_multi_f16", rope_multi_f16_rte_len, rope_multi_f16_rte_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3010. ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f16, "rope_vision_f16", rope_vision_f16_rte_len, rope_vision_f16_rte_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3011. } else {
  3012. 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);
  3013. 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);
  3014. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f16, "rope_multi_f16", rope_multi_f16_len, rope_multi_f16_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3015. ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f16, "rope_vision_f16", rope_vision_f16_len, rope_vision_f16_data, "main", 4, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3016. }
  3017. for (uint32_t i = 0; i < num_argsort_pipelines; ++i) {
  3018. ggml_vk_create_pipeline2(device, device->pipeline_argsort_f32[i], "argsort_f32_"+std::to_string(i), argsort_f32_len, argsort_f32_data, "main", 2, sizeof(vk_op_argsort_push_constants), {1u<<i, 1, 1}, {1u<<i, i}, 1, true);
  3019. }
  3020. ggml_vk_create_pipeline(device, device->pipeline_argmax_f32, "argmax_f32", argmax_f32_len, argmax_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3021. ggml_vk_create_pipeline(device, device->pipeline_sum_rows_f32, "sum_rows_f32", sum_rows_f32_len, sum_rows_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3022. ggml_vk_create_pipeline(device, device->pipeline_count_equal_i32, "count_equal_i32", count_equal_i32_len, count_equal_i32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, { device->subgroup_size }, 1);
  3023. 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);
  3024. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32, "im2col_3d_f32", im2col_3d_f32_len, im2col_3d_f32_data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true);
  3025. if (device->float_controls_rte_fp16) {
  3026. 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);
  3027. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32_f16, "im2col_3d_f32_f16", im2col_3d_f32_f16_rte_len, im2col_3d_f32_f16_rte_data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true);
  3028. } else {
  3029. 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);
  3030. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32_f16, "im2col_3d_f32_f16", im2col_3d_f32_f16_len, im2col_3d_f32_f16_data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true);
  3031. }
  3032. 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);
  3033. ggml_vk_create_pipeline(device, device->pipeline_conv_transpose_1d_f32, "conv_transpose_1d_f32", conv_transpose_1d_f32_len, conv_transpose_1d_f32_data, "main", 3, sizeof(vk_op_conv_transpose_1d_push_constants), {1, 1, 1}, {}, 1);
  3034. 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);
  3035. 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);
  3036. ggml_vk_create_pipeline(device, device->pipeline_rwkv_wkv7_f32, "rwkv_wkv7_f32", rwkv_wkv7_f32_len, rwkv_wkv7_f32_data, "main", 8, sizeof(vk_op_rwkv_wkv7_push_constants), {1, 1, 1}, {device->subgroup_size}, 1);
  3037. ggml_vk_create_pipeline(device, device->pipeline_opt_step_adamw_f32, "opt_step_adamw_f32", opt_step_adamw_f32_len, opt_step_adamw_f32_data, "main", 5, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3038. ggml_vk_create_pipeline(device, device->pipeline_opt_step_sgd_f32, "opt_step_sgd_f32", opt_step_sgd_f32_len, opt_step_sgd_f32_data, "main", 3, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1);
  3039. // conv2d, conv_transpose_2d
  3040. for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) {
  3041. uint32_t conv2d_WG_SIZE = 256;
  3042. uint32_t conv2d_BS_K = 128;
  3043. uint32_t conv2d_BS_CRS = 16;
  3044. uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices.
  3045. uint32_t conv2d_BS_NPQ = 128;
  3046. uint32_t conv2d_TS_K = 8;
  3047. uint32_t conv2d_SHMEM_PAD = 4;
  3048. bool conv2d_UNROLL = true;
  3049. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3050. if (device->coopmat2) {
  3051. conv2d_SHMEM_PAD = 8; // 8 float16_t
  3052. }
  3053. #endif
  3054. if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3055. conv2d_SHMEM_PAD = 0;
  3056. conv2d_UNROLL = false;
  3057. } else if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3058. conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4;
  3059. }
  3060. switch (s) {
  3061. default:
  3062. case CONV_SHAPE_128x128:
  3063. conv2d_BS_K = 128;
  3064. conv2d_BS_NPQ = 128;
  3065. conv2d_BS_CRS = 16;
  3066. if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != vk_device_architecture::AMD_GCN) {
  3067. conv2d_UNROLL = false;
  3068. }
  3069. break;
  3070. case CONV_SHAPE_64x32:
  3071. conv2d_BS_K = 64;
  3072. conv2d_BS_NPQ = 32;
  3073. conv2d_BS_CRS = 32;
  3074. conv2d_TS_K = 4;
  3075. break;
  3076. case CONV_SHAPE_32x256:
  3077. conv2d_BS_K = 32;
  3078. conv2d_BS_NPQ = 256;
  3079. conv2d_BS_CRS = 16;
  3080. break;
  3081. }
  3082. // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math.
  3083. bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA ||
  3084. device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  3085. bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD ||
  3086. device->architecture == vk_device_architecture::AMD_GCN;
  3087. if (device->subgroup_shuffle &&
  3088. device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316.
  3089. allow_collectives_nv &&
  3090. allow_collectives_amd) {
  3091. use_collectives = 1;
  3092. conv2d_BS_CRS = std::min(
  3093. device->subgroup_size,
  3094. conv2d_BS_CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used.
  3095. }
  3096. uint32_t conv2d_shmem_req =
  3097. (conv2d_BS_K * (conv2d_BS_CRS + conv2d_SHMEM_PAD) + conv2d_BS_CRS * (conv2d_BS_NPQ + conv2d_SHMEM_PAD)) * sizeof(float);
  3098. if (device->properties.limits.maxComputeSharedMemorySize < conv2d_shmem_req) {
  3099. conv2d_BS_CRS = 8;
  3100. if (use_collectives) {
  3101. conv2d_BS_CRS = std::min(device->subgroup_size, conv2d_BS_CRS);
  3102. }
  3103. }
  3104. std::array<uint32_t, 3> wg_denoms = { conv2d_BS_K, conv2d_BS_NPQ, 1 };
  3105. std::vector<uint32_t> spec_constants = { conv2d_WG_SIZE, conv2d_BS_K, conv2d_BS_CRS, conv2d_BS_NPQ, conv2d_TS_K, use_collectives, conv2d_SHMEM_PAD };
  3106. #define CREATE_CONV(name, type_suffix, spv_suffix) \
  3107. ggml_vk_create_pipeline( \
  3108. device, device->pipeline_##name##type_suffix[s], #name #type_suffix, \
  3109. name##type_suffix##spv_suffix##_len, name##type_suffix##spv_suffix##_data, "main", 3, \
  3110. sizeof(vk_op_##name##_push_constants), wg_denoms, spec_constants, 1, true, use_collectives);
  3111. #define CREATE_CONVS(spv_suffix) \
  3112. CREATE_CONV(conv2d, _f32, spv_suffix) \
  3113. CREATE_CONV(conv2d, _f16_f32, spv_suffix) \
  3114. if (device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_conv_transpose_2d_push_constants)) { \
  3115. CREATE_CONV(conv_transpose_2d, _f32, spv_suffix) \
  3116. CREATE_CONV(conv_transpose_2d, _f16_f32, spv_suffix) \
  3117. }
  3118. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3119. if (device->coopmat2) {
  3120. CREATE_CONVS(_cm2)
  3121. } else
  3122. #endif
  3123. if (conv2d_UNROLL) {
  3124. CREATE_CONVS(_unroll)
  3125. } else {
  3126. CREATE_CONVS( )
  3127. }
  3128. #undef CREATE_CONV
  3129. #undef CREATE_CONVS
  3130. }
  3131. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_whcn_f32, "conv2d_dw_whcn_f32", conv2d_dw_whcn_f32_len, conv2d_dw_whcn_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3132. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_cwhn_f32, "conv2d_dw_cwhn_f32", conv2d_dw_cwhn_f32_len, conv2d_dw_cwhn_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3133. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_whcn_f16_f32, "conv2d_dw_whcn_f16_f32", conv2d_dw_whcn_f16_f32_len, conv2d_dw_whcn_f16_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3134. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_cwhn_f16_f32, "conv2d_dw_cwhn_f16_f32", conv2d_dw_cwhn_f16_f32_len, conv2d_dw_cwhn_f16_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3135. for (auto &c : compiles) {
  3136. c.wait();
  3137. }
  3138. device->need_compiles = false;
  3139. }
  3140. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch);
  3141. static vk_device ggml_vk_get_device(size_t idx) {
  3142. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  3143. if (vk_instance.devices[idx] == nullptr) {
  3144. VK_LOG_DEBUG("Initializing new vk_device");
  3145. vk_device device = std::make_shared<vk_device_struct>();
  3146. vk_instance.devices[idx] = device;
  3147. #ifdef GGML_VULKAN_MEMORY_DEBUG
  3148. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  3149. #endif
  3150. if (vk_perf_logger_enabled) {
  3151. device->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  3152. }
  3153. size_t dev_num = vk_instance.device_indices[idx];
  3154. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  3155. if (dev_num >= physical_devices.size()) {
  3156. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3157. throw std::runtime_error("Device not found");
  3158. }
  3159. device->physical_device = physical_devices[dev_num];
  3160. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  3161. device->architecture = get_device_architecture(device->physical_device);
  3162. const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY");
  3163. device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr;
  3164. const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM");
  3165. device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr;
  3166. const char* GGML_VK_ALLOW_SYSMEM_FALLBACK = getenv("GGML_VK_ALLOW_SYSMEM_FALLBACK");
  3167. device->allow_sysmem_fallback = GGML_VK_ALLOW_SYSMEM_FALLBACK != nullptr;
  3168. const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE");
  3169. device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr;
  3170. bool fp16_storage = false;
  3171. bool fp16_compute = false;
  3172. bool maintenance4_support = false;
  3173. bool sm_builtins = false;
  3174. bool amd_shader_core_properties2 = false;
  3175. bool pipeline_robustness = false;
  3176. bool coopmat2_support = false;
  3177. bool pipeline_executable_properties_support = false;
  3178. device->coopmat_support = false;
  3179. device->integer_dot_product = false;
  3180. bool bfloat16_support = false;
  3181. for (const auto& properties : ext_props) {
  3182. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  3183. maintenance4_support = true;
  3184. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3185. fp16_storage = true;
  3186. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3187. fp16_compute = true;
  3188. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  3189. sm_builtins = true;
  3190. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  3191. amd_shader_core_properties2 = true;
  3192. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  3193. pipeline_robustness = true;
  3194. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  3195. device->subgroup_size_control = true;
  3196. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3197. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3198. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3199. device->coopmat_support = true;
  3200. device->coopmat_m = 0;
  3201. device->coopmat_n = 0;
  3202. device->coopmat_k = 0;
  3203. #endif
  3204. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3205. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3206. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3207. coopmat2_support = true;
  3208. #endif
  3209. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3210. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3211. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3212. device->integer_dot_product = true;
  3213. #endif
  3214. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3215. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3216. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3217. bfloat16_support = true;
  3218. #endif
  3219. } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) {
  3220. pipeline_executable_properties_support = true;
  3221. }
  3222. }
  3223. vk::PhysicalDeviceProperties2 props2;
  3224. vk::PhysicalDeviceMaintenance3Properties props3;
  3225. vk::PhysicalDeviceMaintenance4Properties props4;
  3226. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3227. vk::PhysicalDeviceDriverProperties driver_props;
  3228. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  3229. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  3230. vk::PhysicalDeviceVulkan11Properties vk11_props;
  3231. vk::PhysicalDeviceVulkan12Properties vk12_props;
  3232. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  3233. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3234. props2.pNext = &props3;
  3235. props3.pNext = &subgroup_props;
  3236. subgroup_props.pNext = &driver_props;
  3237. driver_props.pNext = &vk11_props;
  3238. vk11_props.pNext = &vk12_props;
  3239. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  3240. if (maintenance4_support) {
  3241. last_struct->pNext = (VkBaseOutStructure *)&props4;
  3242. last_struct = (VkBaseOutStructure *)&props4;
  3243. }
  3244. if (sm_builtins) {
  3245. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  3246. last_struct = (VkBaseOutStructure *)&sm_props;
  3247. }
  3248. if (amd_shader_core_properties2) {
  3249. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3250. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3251. }
  3252. if (device->subgroup_size_control) {
  3253. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  3254. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  3255. }
  3256. #if defined(VK_NV_cooperative_matrix2)
  3257. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  3258. if (coopmat2_support) {
  3259. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  3260. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  3261. }
  3262. #endif
  3263. if (device->integer_dot_product) {
  3264. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3265. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3266. }
  3267. device->physical_device.getProperties2(&props2);
  3268. device->properties = props2.properties;
  3269. device->vendor_id = device->properties.vendorID;
  3270. device->driver_id = driver_props.driverID;
  3271. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  3272. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  3273. device->max_memory_allocation_size = std::stoul(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  3274. } else if (maintenance4_support) {
  3275. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  3276. } else {
  3277. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  3278. }
  3279. const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE");
  3280. if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) {
  3281. device->suballocation_block_size = std::stoul(GGML_VK_SUBALLOCATION_BLOCK_SIZE);
  3282. } else {
  3283. // Limit batching of allocations to 1GB by default to avoid fragmentation issues
  3284. device->suballocation_block_size = 1024*1024*1024;
  3285. }
  3286. device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size);
  3287. device->subgroup_size = subgroup_props.subgroupSize;
  3288. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3289. if (sm_builtins) {
  3290. device->shader_core_count = sm_props.shaderSMCount;
  3291. } else if (amd_shader_core_properties2) {
  3292. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  3293. } else {
  3294. device->shader_core_count = 0;
  3295. }
  3296. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  3297. device->subgroup_arithmetic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3298. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic);
  3299. #ifdef __APPLE__
  3300. // Workaround for subgroup arithmetic failing on MoltenVK with AMD GPUs (issue 15846)
  3301. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3302. device->subgroup_arithmetic = false;
  3303. }
  3304. #endif
  3305. device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3306. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle);
  3307. device->subgroup_clustered = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3308. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eClustered);
  3309. device->subgroup_ballot = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3310. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBallot);
  3311. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  3312. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  3313. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) {
  3314. device->coopmat_support = false;
  3315. }
  3316. device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated;
  3317. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  3318. // Try to find a non-graphics compute queue and transfer-focused queues
  3319. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  3320. 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);
  3321. const float priorities[] = { 1.0f, 1.0f };
  3322. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  3323. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  3324. if (compute_queue_family_index != transfer_queue_family_index) {
  3325. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3326. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  3327. } else if(!device->single_queue) {
  3328. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  3329. } else {
  3330. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3331. }
  3332. vk::DeviceCreateInfo device_create_info;
  3333. std::vector<const char *> device_extensions;
  3334. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  3335. VkPhysicalDeviceFeatures2 device_features2;
  3336. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  3337. device_features2.pNext = nullptr;
  3338. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  3339. VkPhysicalDeviceVulkan11Features vk11_features;
  3340. vk11_features.pNext = nullptr;
  3341. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  3342. device_features2.pNext = &vk11_features;
  3343. VkPhysicalDeviceVulkan12Features vk12_features;
  3344. vk12_features.pNext = nullptr;
  3345. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  3346. vk11_features.pNext = &vk12_features;
  3347. last_struct = (VkBaseOutStructure *)&vk12_features;
  3348. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  3349. pl_robustness_features.pNext = nullptr;
  3350. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  3351. pl_robustness_features.pipelineRobustness = VK_FALSE;
  3352. if (pipeline_robustness) {
  3353. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  3354. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  3355. device_extensions.push_back("VK_EXT_pipeline_robustness");
  3356. }
  3357. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  3358. subgroup_size_control_features.pNext = nullptr;
  3359. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  3360. subgroup_size_control_features.computeFullSubgroups = false;
  3361. subgroup_size_control_features.subgroupSizeControl = false;
  3362. if (device->subgroup_size_control) {
  3363. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  3364. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  3365. }
  3366. #if defined(VK_KHR_cooperative_matrix)
  3367. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  3368. coopmat_features.pNext = nullptr;
  3369. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  3370. coopmat_features.cooperativeMatrix = VK_FALSE;
  3371. if (device->coopmat_support) {
  3372. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  3373. last_struct = (VkBaseOutStructure *)&coopmat_features;
  3374. }
  3375. #endif
  3376. #if defined(VK_NV_cooperative_matrix2)
  3377. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  3378. coopmat2_features.pNext = nullptr;
  3379. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  3380. if (coopmat2_support) {
  3381. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  3382. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  3383. device_extensions.push_back("VK_NV_cooperative_matrix2");
  3384. }
  3385. #endif
  3386. #if defined(VK_KHR_shader_bfloat16)
  3387. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  3388. bfloat16_features.pNext = nullptr;
  3389. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  3390. if (bfloat16_support) {
  3391. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  3392. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  3393. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3394. }
  3395. #endif
  3396. VkPhysicalDeviceMaintenance4Features maint4_features {};
  3397. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  3398. if (maintenance4_support) {
  3399. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  3400. last_struct = (VkBaseOutStructure *)&maint4_features;
  3401. device_extensions.push_back("VK_KHR_maintenance4");
  3402. }
  3403. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  3404. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  3405. if (device->integer_dot_product) {
  3406. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3407. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3408. device_extensions.push_back("VK_KHR_shader_integer_dot_product");
  3409. }
  3410. VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pep_features {};
  3411. pep_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR;
  3412. if (pipeline_executable_properties_support) {
  3413. last_struct->pNext = (VkBaseOutStructure *)&pep_features;
  3414. last_struct = (VkBaseOutStructure *)&pep_features;
  3415. device_extensions.push_back("VK_KHR_pipeline_executable_properties");
  3416. }
  3417. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  3418. device->pipeline_executable_properties_support = pipeline_executable_properties_support;
  3419. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  3420. #if defined(VK_KHR_shader_bfloat16)
  3421. device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  3422. #else
  3423. device->bf16 = false;
  3424. #endif
  3425. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  3426. device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 &&
  3427. device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) &&
  3428. vk12_features.runtimeDescriptorArray &&
  3429. device->vendor_id != VK_VENDOR_ID_INTEL &&
  3430. getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr;
  3431. if (device->subgroup_size_control) {
  3432. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  3433. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  3434. device_extensions.push_back("VK_EXT_subgroup_size_control");
  3435. }
  3436. device->subgroup_size_control = device->subgroup_size_control &&
  3437. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  3438. subgroup_size_control_features.subgroupSizeControl;
  3439. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  3440. #if defined(VK_KHR_cooperative_matrix)
  3441. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  3442. // coopmat1 fa shader currently assumes 32 invocations per subgroup
  3443. device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support &&
  3444. device->subgroup_size_control && device->subgroup_min_size <= 32 &&
  3445. device->subgroup_max_size >= 32;
  3446. #endif
  3447. if (coopmat2_support) {
  3448. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3449. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  3450. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  3451. coopmat2_features.cooperativeMatrixReductions &&
  3452. coopmat2_features.cooperativeMatrixConversions &&
  3453. coopmat2_features.cooperativeMatrixPerElementOperations &&
  3454. coopmat2_features.cooperativeMatrixTensorAddressing &&
  3455. coopmat2_features.cooperativeMatrixBlockLoads &&
  3456. vk12_features.bufferDeviceAddress) {
  3457. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  3458. uint32_t count = 0;
  3459. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  3460. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  3461. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  3462. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  3463. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  3464. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  3465. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  3466. flexible_dimensions.resize(count, empty_prop);
  3467. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  3468. bool found_fp16_128 = false,
  3469. found_fp16_256 = false,
  3470. found_fp32_128 = false,
  3471. found_fp32_256 = false;
  3472. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  3473. // with 32x16x16 and 256 with 32x32x16.
  3474. for (auto &prop : flexible_dimensions) {
  3475. if (prop.saturatingAccumulation == VK_FALSE &&
  3476. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  3477. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3478. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3479. if (prop.workgroupInvocations == 128 &&
  3480. prop.MGranularity <= 32 &&
  3481. prop.NGranularity <= 16 &&
  3482. prop.KGranularity <= 16) {
  3483. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3484. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3485. found_fp16_128 = true;
  3486. }
  3487. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3488. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3489. found_fp32_128 = true;
  3490. }
  3491. }
  3492. if (prop.workgroupInvocations == 256 &&
  3493. prop.MGranularity <= 32 &&
  3494. prop.NGranularity <= 32 &&
  3495. prop.KGranularity <= 16) {
  3496. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3497. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3498. found_fp16_256 = true;
  3499. }
  3500. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3501. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3502. found_fp32_256 = true;
  3503. }
  3504. }
  3505. }
  3506. }
  3507. if (found_fp16_128 && found_fp16_256 &&
  3508. found_fp32_128 && found_fp32_256 &&
  3509. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  3510. device->coopmat2 = true;
  3511. }
  3512. }
  3513. #endif
  3514. }
  3515. if (!vk11_features.storageBuffer16BitAccess) {
  3516. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  3517. throw std::runtime_error("Unsupported device");
  3518. }
  3519. device_extensions.push_back("VK_KHR_16bit_storage");
  3520. #ifdef GGML_VULKAN_VALIDATE
  3521. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  3522. #endif
  3523. if (device->fp16) {
  3524. device_extensions.push_back("VK_KHR_shader_float16_int8");
  3525. }
  3526. #if defined(VK_KHR_cooperative_matrix)
  3527. if (device->coopmat_support) {
  3528. // Query supported shapes
  3529. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  3530. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  3531. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  3532. uint32_t cm_props_num;
  3533. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  3534. cm_props.resize(cm_props_num);
  3535. for (auto& prop : cm_props) {
  3536. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  3537. }
  3538. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  3539. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  3540. for (auto& prop : cm_props) {
  3541. 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));
  3542. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  3543. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  3544. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3545. ) {
  3546. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  3547. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  3548. // coopmat sizes not set yet
  3549. if (device->coopmat_m == 0) {
  3550. device->coopmat_acc_f32_support = true;
  3551. device->coopmat_m = prop.MSize;
  3552. device->coopmat_n = prop.NSize;
  3553. device->coopmat_k = prop.KSize;
  3554. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3555. // Only enable if shape is identical
  3556. device->coopmat_acc_f32_support = true;
  3557. }
  3558. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3559. device->coopmat_support_16x16x16_f32acc = true;
  3560. }
  3561. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  3562. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  3563. // coopmat sizes not set yet
  3564. if (device->coopmat_m == 0) {
  3565. device->coopmat_acc_f16_support = true;
  3566. device->coopmat_m = prop.MSize;
  3567. device->coopmat_n = prop.NSize;
  3568. device->coopmat_k = prop.KSize;
  3569. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3570. // Only enable if shape is identical
  3571. device->coopmat_acc_f16_support = true;
  3572. }
  3573. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3574. device->coopmat_support_16x16x16_f16acc = true;
  3575. }
  3576. }
  3577. } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 &&
  3578. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 &&
  3579. (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 &&
  3580. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 &&
  3581. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup &&
  3582. device->coopmat_int_m == 0
  3583. ) {
  3584. device->coopmat_int_support = true;
  3585. device->coopmat_int_m = prop.MSize;
  3586. device->coopmat_int_n = prop.NSize;
  3587. device->coopmat_int_k = prop.KSize;
  3588. }
  3589. #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3590. if (prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3591. prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3592. prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3593. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3594. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3595. ) {
  3596. // coopmat sizes not set yet
  3597. if (device->coopmat_m == 0) {
  3598. device->coopmat_bf16_support = true;
  3599. device->coopmat_m = prop.MSize;
  3600. device->coopmat_n = prop.NSize;
  3601. device->coopmat_k = prop.KSize;
  3602. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3603. // Only enable if shape is identical
  3604. device->coopmat_bf16_support = true;
  3605. }
  3606. }
  3607. #endif
  3608. }
  3609. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  3610. // No suitable matmul mode found
  3611. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  3612. device->coopmat_support = false;
  3613. }
  3614. if (getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3615. device->coopmat_bf16_support = false;
  3616. }
  3617. }
  3618. if (device->coopmat_support) {
  3619. device_extensions.push_back("VK_KHR_cooperative_matrix");
  3620. }
  3621. #if defined(VK_KHR_shader_bfloat16)
  3622. if (device->coopmat_bf16_support) {
  3623. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3624. }
  3625. #endif
  3626. #endif
  3627. device->name = GGML_VK_NAME + std::to_string(idx);
  3628. device_create_info = {
  3629. vk::DeviceCreateFlags(),
  3630. device_queue_create_infos,
  3631. {},
  3632. device_extensions
  3633. };
  3634. device_create_info.setPNext(&device_features2);
  3635. device->device = device->physical_device.createDevice(device_create_info);
  3636. // Queues
  3637. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  3638. // Shaders
  3639. // Disable matmul tile sizes early if performance low or not supported
  3640. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  3641. switch (device->vendor_id) {
  3642. #ifndef GGML_VULKAN_RUN_TESTS
  3643. case VK_VENDOR_ID_AMD:
  3644. case VK_VENDOR_ID_INTEL:
  3645. device->mul_mat_l[i] = false;
  3646. device->mul_mat_m[i] = true;
  3647. device->mul_mat_s[i] = true;
  3648. device->mul_mat_id_l[i] = false;
  3649. device->mul_mat_id_m[i] = true;
  3650. device->mul_mat_id_s[i] = true;
  3651. break;
  3652. case VK_VENDOR_ID_APPLE:
  3653. device->mul_mat_l[i] = false;
  3654. device->mul_mat_m[i] = true;
  3655. device->mul_mat_s[i] = false;
  3656. device->mul_mat_id_l[i] = false;
  3657. device->mul_mat_id_m[i] = true;
  3658. device->mul_mat_id_s[i] = false;
  3659. break;
  3660. #endif
  3661. default:
  3662. device->mul_mat_l[i] = true;
  3663. device->mul_mat_m[i] = true;
  3664. device->mul_mat_s[i] = true;
  3665. device->mul_mat_id_l[i] = true;
  3666. device->mul_mat_id_m[i] = true;
  3667. device->mul_mat_id_s[i] = true;
  3668. break;
  3669. }
  3670. }
  3671. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  3672. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  3673. for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
  3674. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  3675. dsl_binding_flags.push_back({});
  3676. }
  3677. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  3678. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  3679. {},
  3680. dsl_binding);
  3681. descriptor_set_layout_create_info.setPNext(&dslbfci);
  3682. device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  3683. ggml_vk_load_shaders(device);
  3684. if (!device->single_queue) {
  3685. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  3686. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  3687. } else {
  3688. // TODO: Use pointer or reference to avoid copy
  3689. device->transfer_queue.copyFrom(device->compute_queue);
  3690. device->transfer_queue.cmd_pool.init(device, &device->transfer_queue);
  3691. }
  3692. device->buffer_type = {
  3693. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  3694. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  3695. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  3696. };
  3697. device->fence = device->device.createFence({});
  3698. device->idx = idx;
  3699. device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr;
  3700. device->add_rms_fusion = !device->disable_fusion &&
  3701. device->subgroup_arithmetic &&
  3702. device->vendor_id != VK_VENDOR_ID_INTEL;
  3703. device->partials_binding_alignment =
  3704. std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment);
  3705. device->mmvq_mode = 0;
  3706. if (getenv("GGML_VK_DISABLE_MMVQ")) {
  3707. device->mmvq_mode = -1;
  3708. } else if (getenv("GGML_VK_FORCE_MMVQ")) {
  3709. device->mmvq_mode = 1;
  3710. }
  3711. return device;
  3712. }
  3713. return vk_instance.devices[idx];
  3714. }
  3715. static void ggml_vk_print_gpu_info(size_t idx) {
  3716. GGML_ASSERT(idx < vk_instance.device_indices.size());
  3717. size_t dev_num = vk_instance.device_indices[idx];
  3718. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  3719. GGML_ASSERT(vk_instance_initialized);
  3720. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  3721. if (dev_num >= devices.size()) {
  3722. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3723. throw std::runtime_error("Device not found");
  3724. }
  3725. vk::PhysicalDevice physical_device = devices[dev_num];
  3726. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  3727. bool fp16_storage = false;
  3728. bool fp16_compute = false;
  3729. bool coopmat_support = false;
  3730. bool coopmat2_support = false;
  3731. bool integer_dot_product = false;
  3732. bool bfloat16_support = false;
  3733. for (auto properties : ext_props) {
  3734. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3735. fp16_storage = true;
  3736. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3737. fp16_compute = true;
  3738. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3739. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3740. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3741. coopmat_support = true;
  3742. #endif
  3743. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3744. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3745. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3746. coopmat2_support = true;
  3747. #endif
  3748. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3749. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3750. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3751. integer_dot_product = true;
  3752. #endif
  3753. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3754. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3755. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3756. bfloat16_support = true;
  3757. #endif
  3758. }
  3759. }
  3760. const vk_device_architecture device_architecture = get_device_architecture(physical_device);
  3761. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  3762. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  3763. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  3764. vk::PhysicalDeviceProperties2 props2;
  3765. vk::PhysicalDeviceMaintenance3Properties props3;
  3766. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3767. vk::PhysicalDeviceDriverProperties driver_props;
  3768. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3769. props2.pNext = &props3;
  3770. props3.pNext = &subgroup_props;
  3771. subgroup_props.pNext = &driver_props;
  3772. // Pointer to the last chain element
  3773. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  3774. if (integer_dot_product) {
  3775. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3776. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3777. }
  3778. physical_device.getProperties2(&props2);
  3779. VkPhysicalDeviceFeatures2 device_features2;
  3780. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  3781. device_features2.pNext = nullptr;
  3782. VkPhysicalDeviceVulkan11Features vk11_features;
  3783. vk11_features.pNext = nullptr;
  3784. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  3785. device_features2.pNext = &vk11_features;
  3786. VkPhysicalDeviceVulkan12Features vk12_features;
  3787. vk12_features.pNext = nullptr;
  3788. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  3789. vk11_features.pNext = &vk12_features;
  3790. // Pointer to the last chain element
  3791. last_struct = (VkBaseOutStructure *)&vk12_features;
  3792. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3793. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  3794. coopmat_features.pNext = nullptr;
  3795. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  3796. coopmat_features.cooperativeMatrix = VK_FALSE;
  3797. if (coopmat_support) {
  3798. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  3799. last_struct = (VkBaseOutStructure *)&coopmat_features;
  3800. }
  3801. #endif
  3802. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  3803. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  3804. if (integer_dot_product) {
  3805. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3806. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3807. }
  3808. #if defined(VK_KHR_shader_bfloat16)
  3809. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  3810. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  3811. if (bfloat16_support) {
  3812. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  3813. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  3814. }
  3815. #endif
  3816. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  3817. fp16 = fp16 && vk12_features.shaderFloat16;
  3818. #if defined(VK_KHR_shader_bfloat16)
  3819. bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  3820. #else
  3821. bool bf16 = false;
  3822. #endif
  3823. uint32_t default_subgroup_size = get_subgroup_size("", device_architecture);
  3824. const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize;
  3825. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3826. integer_dot_product = integer_dot_product
  3827. && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated
  3828. && shader_integer_dot_product_features.shaderIntegerDotProduct;
  3829. coopmat_support = coopmat_support
  3830. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3831. && coopmat_features.cooperativeMatrix
  3832. #endif
  3833. && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture);
  3834. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  3835. std::string device_name = props2.properties.deviceName.data();
  3836. GGML_LOG_DEBUG("ggml_vulkan: %zu = %s (%s) | uma: %d | fp16: %d | bf16: %d | warp size: %zu | shared memory: %d | int dot: %d | matrix cores: %s\n",
  3837. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, bf16, subgroup_size,
  3838. props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str());
  3839. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  3840. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  3841. }
  3842. }
  3843. static bool ggml_vk_instance_validation_ext_available();
  3844. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  3845. static bool ggml_vk_instance_debug_utils_ext_available(const std::vector<vk::ExtensionProperties> & instance_extensions);
  3846. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev);
  3847. static void ggml_vk_instance_init() {
  3848. if (vk_instance_initialized) {
  3849. return;
  3850. }
  3851. VK_LOG_DEBUG("ggml_vk_instance_init()");
  3852. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  3853. VULKAN_HPP_DEFAULT_DISPATCHER.init(vkGetInstanceProcAddr);
  3854. uint32_t api_version = vk::enumerateInstanceVersion();
  3855. if (api_version < VK_API_VERSION_1_2) {
  3856. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  3857. GGML_ABORT("fatal error");
  3858. }
  3859. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  3860. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  3861. const bool validation_ext = ggml_vk_instance_validation_ext_available();
  3862. #ifdef __APPLE__
  3863. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  3864. #endif
  3865. const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr;
  3866. std::vector<const char*> layers;
  3867. if (validation_ext) {
  3868. layers.push_back("VK_LAYER_KHRONOS_validation");
  3869. }
  3870. std::vector<const char*> extensions;
  3871. if (validation_ext) {
  3872. extensions.push_back("VK_EXT_validation_features");
  3873. }
  3874. #ifdef __APPLE__
  3875. if (portability_enumeration_ext) {
  3876. extensions.push_back("VK_KHR_portability_enumeration");
  3877. }
  3878. #endif
  3879. if (debug_utils_ext) {
  3880. extensions.push_back("VK_EXT_debug_utils");
  3881. }
  3882. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions);
  3883. #ifdef __APPLE__
  3884. if (portability_enumeration_ext) {
  3885. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  3886. }
  3887. #endif
  3888. std::vector<vk::ValidationFeatureEnableEXT> features_enable;
  3889. vk::ValidationFeaturesEXT validation_features;
  3890. if (validation_ext) {
  3891. features_enable = { vk::ValidationFeatureEnableEXT::eBestPractices };
  3892. validation_features = {
  3893. features_enable,
  3894. {},
  3895. };
  3896. validation_features.setPNext(nullptr);
  3897. instance_create_info.setPNext(&validation_features);
  3898. GGML_LOG_DEBUG("ggml_vulkan: Validation layers enabled\n");
  3899. }
  3900. vk_instance.instance = vk::createInstance(instance_create_info);
  3901. vk_instance_initialized = true;
  3902. if (debug_utils_ext) {
  3903. vk_instance.debug_utils_support = true;
  3904. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT");
  3905. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT");
  3906. vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT");
  3907. vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT");
  3908. vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT");
  3909. vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT");
  3910. }
  3911. vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr;
  3912. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  3913. VULKAN_HPP_DEFAULT_DISPATCHER.init(vk_instance.instance);
  3914. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  3915. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  3916. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  3917. if (devices_env != nullptr) {
  3918. size_t num_available_devices = devices.size();
  3919. std::string devices(devices_env);
  3920. std::replace(devices.begin(), devices.end(), ',', ' ');
  3921. std::stringstream ss(devices);
  3922. size_t tmp;
  3923. while (ss >> tmp) {
  3924. if(tmp >= num_available_devices) {
  3925. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  3926. throw std::runtime_error("Invalid Vulkan device index");
  3927. }
  3928. vk_instance.device_indices.push_back(tmp);
  3929. }
  3930. } else {
  3931. // If no vulkan devices are found, return early
  3932. if (devices.empty()) {
  3933. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  3934. return;
  3935. }
  3936. // Default to using all dedicated GPUs
  3937. for (size_t i = 0; i < devices.size(); i++) {
  3938. vk::PhysicalDeviceProperties2 new_props;
  3939. vk::PhysicalDeviceDriverProperties new_driver;
  3940. vk::PhysicalDeviceIDProperties new_id;
  3941. new_props.pNext = &new_driver;
  3942. new_driver.pNext = &new_id;
  3943. devices[i].getProperties2(&new_props);
  3944. if ((new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu || new_props.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) && ggml_vk_device_is_supported(devices[i])) {
  3945. // Check if there are two physical devices corresponding to the same GPU
  3946. auto old_device = std::find_if(
  3947. vk_instance.device_indices.begin(),
  3948. vk_instance.device_indices.end(),
  3949. [&devices, &new_id](const size_t k){
  3950. vk::PhysicalDeviceProperties2 old_props;
  3951. vk::PhysicalDeviceIDProperties old_id;
  3952. old_props.pNext = &old_id;
  3953. devices[k].getProperties2(&old_props);
  3954. return std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  3955. }
  3956. );
  3957. if (old_device == vk_instance.device_indices.end()) {
  3958. vk_instance.device_indices.push_back(i);
  3959. } else {
  3960. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  3961. // This can cause error when splitting layers aross the devices, need to keep only 1
  3962. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  3963. vk::PhysicalDeviceProperties2 old_props;
  3964. vk::PhysicalDeviceDriverProperties old_driver;
  3965. old_props.pNext = &old_driver;
  3966. devices[*old_device].getProperties2(&old_props);
  3967. std::map<vk::DriverId, int> driver_priorities {};
  3968. int old_priority = std::numeric_limits<int>::max();
  3969. int new_priority = std::numeric_limits<int>::max();
  3970. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  3971. // Smaller number -> higher priority
  3972. switch (old_props.properties.vendorID) {
  3973. case VK_VENDOR_ID_AMD:
  3974. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  3975. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  3976. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  3977. break;
  3978. case VK_VENDOR_ID_INTEL:
  3979. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  3980. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  3981. break;
  3982. case VK_VENDOR_ID_NVIDIA:
  3983. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  3984. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  3985. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  3986. #endif
  3987. break;
  3988. }
  3989. if (driver_priorities.count(old_driver.driverID)) {
  3990. old_priority = driver_priorities[old_driver.driverID];
  3991. }
  3992. if (driver_priorities.count(new_driver.driverID)) {
  3993. new_priority = driver_priorities[new_driver.driverID];
  3994. }
  3995. if (new_priority < old_priority) {
  3996. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  3997. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  3998. vk_instance.device_indices.push_back(i);
  3999. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  4000. }
  4001. else {
  4002. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  4003. }
  4004. }
  4005. }
  4006. }
  4007. // If no GPUs found, fall back to the first non-CPU device.
  4008. // If only CPU devices are available, return without devices.
  4009. if (vk_instance.device_indices.empty()) {
  4010. for (size_t i = 0; i < devices.size(); i++) {
  4011. if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) {
  4012. vk_instance.device_indices.push_back(i);
  4013. break;
  4014. }
  4015. }
  4016. }
  4017. if (vk_instance.device_indices.empty()) {
  4018. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4019. return;
  4020. }
  4021. }
  4022. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  4023. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  4024. vk::PhysicalDevice vkdev = devices[vk_instance.device_indices[i]];
  4025. std::vector<vk::ExtensionProperties> extensionprops = vkdev.enumerateDeviceExtensionProperties();
  4026. bool membudget_supported = false;
  4027. for (const auto & ext : extensionprops) {
  4028. if (strcmp(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, ext.extensionName) == 0) {
  4029. membudget_supported = true;
  4030. break;
  4031. }
  4032. }
  4033. vk_instance.device_supports_membudget.push_back(membudget_supported);
  4034. ggml_vk_print_gpu_info(i);
  4035. }
  4036. }
  4037. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  4038. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  4039. ggml_vk_instance_init();
  4040. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4041. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4042. ctx->device = ggml_vk_get_device(idx);
  4043. ctx->semaphore_idx = 0;
  4044. ctx->event_idx = 0;
  4045. ctx->prealloc_size_x = 0;
  4046. ctx->prealloc_size_y = 0;
  4047. ctx->prealloc_size_split_k = 0;
  4048. ctx->fence = ctx->device->device.createFence({});
  4049. ctx->almost_ready_fence = ctx->device->device.createFence({});
  4050. ctx->compute_cmd_pool.init(ctx->device, &ctx->device->compute_queue);
  4051. ctx->transfer_cmd_pool.init(ctx->device, &ctx->device->transfer_queue);
  4052. #ifdef GGML_VULKAN_CHECK_RESULTS
  4053. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  4054. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  4055. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  4056. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  4057. #endif
  4058. }
  4059. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  4060. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  4061. switch (type) {
  4062. case GGML_TYPE_F32:
  4063. case GGML_TYPE_Q4_0:
  4064. case GGML_TYPE_Q4_1:
  4065. case GGML_TYPE_Q5_0:
  4066. case GGML_TYPE_Q5_1:
  4067. case GGML_TYPE_Q8_0:
  4068. case GGML_TYPE_Q2_K:
  4069. case GGML_TYPE_Q3_K:
  4070. case GGML_TYPE_Q4_K:
  4071. case GGML_TYPE_Q5_K:
  4072. case GGML_TYPE_Q6_K:
  4073. case GGML_TYPE_IQ1_S:
  4074. case GGML_TYPE_IQ1_M:
  4075. case GGML_TYPE_IQ2_XXS:
  4076. case GGML_TYPE_IQ2_XS:
  4077. case GGML_TYPE_IQ2_S:
  4078. case GGML_TYPE_IQ3_XXS:
  4079. case GGML_TYPE_IQ3_S:
  4080. case GGML_TYPE_IQ4_XS:
  4081. case GGML_TYPE_IQ4_NL:
  4082. case GGML_TYPE_MXFP4:
  4083. break;
  4084. default:
  4085. return nullptr;
  4086. }
  4087. return ctx->device->pipeline_dequant[type];
  4088. }
  4089. 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) {
  4090. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ", " << prec << ")");
  4091. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4092. return ctx->device->pipeline_matmul_f32;
  4093. }
  4094. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4095. return ctx->device->pipeline_matmul_f32_f16;
  4096. }
  4097. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4098. return ctx->device->pipeline_matmul_bf16;
  4099. }
  4100. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4101. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4102. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  4103. }
  4104. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4105. return ctx->device->pipeline_matmul_f16.f16acc;
  4106. }
  4107. } else {
  4108. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4109. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  4110. }
  4111. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4112. return ctx->device->pipeline_matmul_f16.f32acc;
  4113. }
  4114. }
  4115. // MMQ
  4116. if (src1_type == GGML_TYPE_Q8_1) {
  4117. vk_matmul_pipeline pipelines = (ctx->device->fp16 && prec == GGML_PREC_DEFAULT) ? ctx->device->pipeline_dequant_mul_mat_mat_q8_1[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat_q8_1[src0_type].f32acc;
  4118. if (pipelines->s == nullptr && pipelines->m == nullptr && pipelines->l == nullptr) {
  4119. return nullptr;
  4120. }
  4121. return pipelines;
  4122. }
  4123. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  4124. return nullptr;
  4125. }
  4126. switch (src0_type) {
  4127. case GGML_TYPE_Q4_0:
  4128. case GGML_TYPE_Q4_1:
  4129. case GGML_TYPE_Q5_0:
  4130. case GGML_TYPE_Q5_1:
  4131. case GGML_TYPE_Q8_0:
  4132. case GGML_TYPE_Q2_K:
  4133. case GGML_TYPE_Q3_K:
  4134. case GGML_TYPE_Q4_K:
  4135. case GGML_TYPE_Q5_K:
  4136. case GGML_TYPE_Q6_K:
  4137. case GGML_TYPE_IQ1_S:
  4138. case GGML_TYPE_IQ1_M:
  4139. case GGML_TYPE_IQ2_XXS:
  4140. case GGML_TYPE_IQ2_XS:
  4141. case GGML_TYPE_IQ2_S:
  4142. case GGML_TYPE_IQ3_XXS:
  4143. case GGML_TYPE_IQ3_S:
  4144. case GGML_TYPE_IQ4_XS:
  4145. case GGML_TYPE_IQ4_NL:
  4146. case GGML_TYPE_MXFP4:
  4147. break;
  4148. default:
  4149. return nullptr;
  4150. }
  4151. if (ctx->device->coopmat2) {
  4152. assert(src1_type == GGML_TYPE_F16);
  4153. return prec == GGML_PREC_DEFAULT ? ctx->device->pipeline_dequant_mul_mat_mat_f16[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat_f16[src0_type].f32acc;
  4154. }
  4155. if (ctx->device->coopmat_support) {
  4156. return (ctx->device->fp16 && ctx->device->coopmat_acc_f16_support && prec == GGML_PREC_DEFAULT) ? ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f32acc;
  4157. }
  4158. return (ctx->device->fp16 && prec == GGML_PREC_DEFAULT) ? ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f16acc : ctx->device->pipeline_dequant_mul_mat_mat[src0_type].f32acc;
  4159. }
  4160. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type, uint32_t num_cols, uint32_t m, uint32_t k) {
  4161. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  4162. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1);
  4163. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  4164. if (b_type == GGML_TYPE_Q8_1) {
  4165. switch (a_type) {
  4166. case GGML_TYPE_Q4_0:
  4167. case GGML_TYPE_Q4_1:
  4168. case GGML_TYPE_Q5_0:
  4169. case GGML_TYPE_Q5_1:
  4170. case GGML_TYPE_Q8_0:
  4171. break;
  4172. default:
  4173. return nullptr;
  4174. }
  4175. }
  4176. switch (a_type) {
  4177. case GGML_TYPE_F32:
  4178. case GGML_TYPE_F16:
  4179. case GGML_TYPE_BF16:
  4180. case GGML_TYPE_Q4_0:
  4181. case GGML_TYPE_Q4_1:
  4182. case GGML_TYPE_Q5_0:
  4183. case GGML_TYPE_Q5_1:
  4184. case GGML_TYPE_Q8_0:
  4185. case GGML_TYPE_Q2_K:
  4186. case GGML_TYPE_Q3_K:
  4187. case GGML_TYPE_Q4_K:
  4188. case GGML_TYPE_Q5_K:
  4189. case GGML_TYPE_Q6_K:
  4190. case GGML_TYPE_IQ1_S:
  4191. case GGML_TYPE_IQ1_M:
  4192. case GGML_TYPE_IQ2_XXS:
  4193. case GGML_TYPE_IQ2_XS:
  4194. case GGML_TYPE_IQ2_S:
  4195. case GGML_TYPE_IQ3_XXS:
  4196. case GGML_TYPE_IQ3_S:
  4197. case GGML_TYPE_IQ4_XS:
  4198. case GGML_TYPE_IQ4_NL:
  4199. case GGML_TYPE_MXFP4:
  4200. break;
  4201. default:
  4202. return nullptr;
  4203. }
  4204. // heuristic to choose workgroup size
  4205. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4206. if ((ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA && ctx->device->architecture != vk_device_architecture::NVIDIA_PRE_TURING) || ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4207. // Prefer larger workgroups when M is small, to spread the work out more
  4208. // and keep more SMs busy.
  4209. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4210. if (a_type == GGML_TYPE_Q6_K) {
  4211. if (m < 4096 && k >= 1024) {
  4212. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4213. }
  4214. } else {
  4215. if (m <= 8192 && k >= 1024) {
  4216. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4217. }
  4218. }
  4219. }
  4220. if (b_type == GGML_TYPE_Q8_1) {
  4221. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4222. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4223. }
  4224. return ctx->device->pipeline_dequant_mul_mat_vec_q8_1_f32[dmmv_wg][a_type][num_cols-1];
  4225. }
  4226. return b_type == GGML_TYPE_F32 ? ctx->device->pipeline_dequant_mul_mat_vec_f32_f32[dmmv_wg][a_type][num_cols-1] : ctx->device->pipeline_dequant_mul_mat_vec_f16_f32[dmmv_wg][a_type][num_cols-1];
  4227. }
  4228. 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) {
  4229. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  4230. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4231. return ctx->device->pipeline_matmul_id_f32;
  4232. }
  4233. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4234. return ctx->device->pipeline_matmul_id_bf16;
  4235. }
  4236. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4237. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4238. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  4239. }
  4240. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4241. return ctx->device->pipeline_matmul_id_f16.f16acc;
  4242. }
  4243. } else {
  4244. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4245. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  4246. }
  4247. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4248. return ctx->device->pipeline_matmul_id_f16.f32acc;
  4249. }
  4250. }
  4251. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  4252. switch (src0_type) {
  4253. case GGML_TYPE_Q4_0:
  4254. case GGML_TYPE_Q4_1:
  4255. case GGML_TYPE_Q5_0:
  4256. case GGML_TYPE_Q5_1:
  4257. case GGML_TYPE_Q8_0:
  4258. case GGML_TYPE_Q2_K:
  4259. case GGML_TYPE_Q3_K:
  4260. case GGML_TYPE_Q4_K:
  4261. case GGML_TYPE_Q5_K:
  4262. case GGML_TYPE_Q6_K:
  4263. case GGML_TYPE_IQ1_S:
  4264. case GGML_TYPE_IQ1_M:
  4265. case GGML_TYPE_IQ2_XXS:
  4266. case GGML_TYPE_IQ2_XS:
  4267. case GGML_TYPE_IQ2_S:
  4268. case GGML_TYPE_IQ3_XXS:
  4269. case GGML_TYPE_IQ3_S:
  4270. case GGML_TYPE_IQ4_XS:
  4271. case GGML_TYPE_IQ4_NL:
  4272. case GGML_TYPE_MXFP4:
  4273. break;
  4274. default:
  4275. return nullptr;
  4276. }
  4277. // XXX TODO 'prec' is not actually allowed in mul_mat_id.
  4278. bool prefer_fp16acc = ctx->device->fp16 /*&& prec == GGML_PREC_DEFAULT*/;
  4279. bool support_fp16acc = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f16acc != nullptr;
  4280. bool support_fp32acc = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f32acc != nullptr;
  4281. if (support_fp16acc && (prefer_fp16acc || !support_fp32acc)) {
  4282. return ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f16acc;
  4283. } else {
  4284. GGML_ASSERT(support_fp32acc);
  4285. return ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f32acc;
  4286. }
  4287. }
  4288. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type) {
  4289. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()");
  4290. GGML_ASSERT(b_type == GGML_TYPE_F32);
  4291. switch (a_type) {
  4292. case GGML_TYPE_F32:
  4293. case GGML_TYPE_F16:
  4294. case GGML_TYPE_BF16:
  4295. case GGML_TYPE_Q4_0:
  4296. case GGML_TYPE_Q4_1:
  4297. case GGML_TYPE_Q5_0:
  4298. case GGML_TYPE_Q5_1:
  4299. case GGML_TYPE_Q8_0:
  4300. case GGML_TYPE_Q2_K:
  4301. case GGML_TYPE_Q3_K:
  4302. case GGML_TYPE_Q4_K:
  4303. case GGML_TYPE_Q5_K:
  4304. case GGML_TYPE_Q6_K:
  4305. case GGML_TYPE_IQ1_S:
  4306. case GGML_TYPE_IQ1_M:
  4307. case GGML_TYPE_IQ2_XXS:
  4308. case GGML_TYPE_IQ2_XS:
  4309. case GGML_TYPE_IQ2_S:
  4310. case GGML_TYPE_IQ3_XXS:
  4311. case GGML_TYPE_IQ3_S:
  4312. case GGML_TYPE_IQ4_XS:
  4313. case GGML_TYPE_IQ4_NL:
  4314. case GGML_TYPE_MXFP4:
  4315. break;
  4316. default:
  4317. return nullptr;
  4318. }
  4319. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[a_type];
  4320. }
  4321. static vk_buffer ggml_vk_pool_malloc(ggml_backend_vk_context * ctx, size_t size) {
  4322. VK_LOG_DEBUG("ggml_vk_pool_malloc(" << size << ")");
  4323. VK_LOG_MEMORY("ggml_vk_pool_malloc");
  4324. int best_i = -1;
  4325. size_t best_size = std::numeric_limits<size_t>::max(); //smallest unused buffer that fits our needs
  4326. int worst_i = -1;
  4327. size_t worst_size = 0; //largest unused buffer seen so far
  4328. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  4329. vk_buffer &b = ctx->buffer_pool[i];
  4330. if (b != nullptr && b->size >= size && b->size < best_size) {
  4331. best_i = i;
  4332. best_size = b->size;
  4333. }
  4334. if (b != nullptr && b->size > worst_size) {
  4335. worst_i = i;
  4336. worst_size = b->size;
  4337. }
  4338. }
  4339. if(best_i != -1) {
  4340. //found the smallest buffer that fits our needs
  4341. vk_buffer b = ctx->buffer_pool[best_i];
  4342. ctx->buffer_pool[best_i].reset();
  4343. return b;
  4344. }
  4345. if(worst_i != -1) {
  4346. //no buffer that fits our needs, resize largest one to save memory
  4347. vk_buffer& b = ctx->buffer_pool[worst_i];
  4348. ggml_vk_destroy_buffer(b);
  4349. }
  4350. return ggml_vk_create_buffer_device(ctx->device, size);
  4351. }
  4352. static void ggml_vk_pool_free(ggml_backend_vk_context * ctx, vk_buffer& buffer) {
  4353. VK_LOG_DEBUG("ggml_vk_pool_free(" << buffer->size << ")");
  4354. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  4355. vk_buffer& b = ctx->buffer_pool[i];
  4356. if (b == nullptr) {
  4357. b = buffer;
  4358. return;
  4359. }
  4360. }
  4361. std::cerr << "ggml_vulkan: WARNING: vk buffer pool full, increase MAX_VK_BUFFERS" << std::endl;
  4362. ggml_vk_destroy_buffer(buffer);
  4363. }
  4364. // Returns an available temporary buffer that may only be used temporarily, it will be reused
  4365. static vk_buffer ggml_vk_create_buffer_temp(ggml_backend_vk_context * ctx, size_t size) {
  4366. // Try to find existing temp buffer with enough capacity
  4367. for (auto& buffer : ctx->gc.temp_buffers) {
  4368. if (buffer->size >= size) {
  4369. return buffer;
  4370. }
  4371. }
  4372. VK_LOG_MEMORY("ggml_vk_create_buffer_temp(" << size << ")");
  4373. // Otherwise create new buffer
  4374. vk_buffer buf = ggml_vk_pool_malloc(ctx, size);
  4375. ctx->gc.temp_buffers.push_back(buf);
  4376. return buf;
  4377. }
  4378. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  4379. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  4380. vk_buffer buf = ggml_vk_create_buffer(device, size,
  4381. {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4382. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  4383. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  4384. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  4385. size/1024.0/1024.0);
  4386. device->device.freeMemory(buf->device_memory);
  4387. device->device.destroyBuffer(buf->buffer);
  4388. return nullptr;
  4389. }
  4390. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4391. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  4392. return buf->ptr;
  4393. }
  4394. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  4395. if (ptr == nullptr) {
  4396. return;
  4397. }
  4398. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  4399. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4400. vk_buffer buf;
  4401. size_t index;
  4402. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4403. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4404. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4405. if (ptr >= addr && ptr < endr) {
  4406. buf = std::get<2>(device->pinned_memory[i]);
  4407. index = i;
  4408. break;
  4409. }
  4410. }
  4411. if (buf == nullptr) {
  4412. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  4413. return;
  4414. }
  4415. ggml_vk_destroy_buffer(buf);
  4416. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  4417. }
  4418. static void ggml_vk_host_get(vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  4419. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4420. buf = nullptr;
  4421. buf_offset = 0;
  4422. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4423. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4424. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4425. if (ptr >= addr && ptr < endr) {
  4426. buf = std::get<2>(device->pinned_memory[i]);
  4427. buf_offset = ((const uint8_t *)ptr) - addr;
  4428. break;
  4429. }
  4430. }
  4431. }
  4432. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) {
  4433. vk_submission s;
  4434. s.buffer = ggml_vk_create_cmd_buffer(device, p);
  4435. if (one_time) {
  4436. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  4437. } else {
  4438. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  4439. }
  4440. return s;
  4441. }
  4442. template <typename T> size_t push_constant_size(const T &t) {
  4443. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4444. GGML_UNUSED(t);
  4445. return sizeof(T);
  4446. }
  4447. template <typename T> size_t push_constant_size(const std::vector<T> &t) {
  4448. GGML_UNUSED(t);
  4449. return sizeof(T) * t.size();
  4450. }
  4451. template <typename T, uint32_t N> size_t push_constant_size(const std::array<T, N> &t) {
  4452. GGML_UNUSED(t);
  4453. return sizeof(T) * N;
  4454. }
  4455. template <typename T> const T *push_constant_data(const T &t) {
  4456. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4457. return &t;
  4458. }
  4459. template <typename T> const T *push_constant_data(const std::vector<T> &t) {
  4460. return t.data();
  4461. }
  4462. template <typename T, uint32_t N> const T *push_constant_data(const std::array<T, N> &t) {
  4463. return t.data();
  4464. }
  4465. template <typename T>
  4466. static void ggml_vk_dispatch_pipeline(ggml_backend_vk_context* ctx, vk_context& subctx, vk_pipeline& pipeline, std::initializer_list<vk::DescriptorBufferInfo> const& descriptor_buffer_infos, const T &push_constants, std::array<uint32_t, 3> elements) {
  4467. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  4468. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  4469. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  4470. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  4471. for (auto& buffer : descriptor_buffer_infos) {
  4472. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  4473. }
  4474. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  4475. GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size());
  4476. GGML_ASSERT(descriptor_buffer_infos.size() <= MAX_PARAMETER_COUNT);
  4477. GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size());
  4478. vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[ctx->descriptor_set_idx++];
  4479. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  4480. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  4481. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size(push_constants), push_constant_data(push_constants));
  4482. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  4483. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  4484. pipeline->layout,
  4485. 0,
  4486. { descriptor_set },
  4487. {});
  4488. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  4489. }
  4490. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  4491. s.buffer.end();
  4492. s.wait_semaphores = std::move(wait_semaphores);
  4493. s.signal_semaphores = std::move(signal_semaphores);
  4494. }
  4495. static void ggml_vk_ctx_end(vk_context& ctx) {
  4496. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  4497. if (ctx->s == nullptr) {
  4498. return;
  4499. }
  4500. ctx->s->buffer.end();
  4501. ctx->s = nullptr;
  4502. }
  4503. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  4504. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  4505. if (subctx->s != nullptr) {
  4506. ggml_vk_ctx_end(subctx);
  4507. }
  4508. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) });
  4509. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  4510. }
  4511. static size_t ggml_vk_align_size(size_t width, size_t align) {
  4512. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  4513. return CEIL_DIV(width, align) * align;
  4514. }
  4515. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  4516. if (memcpys == nullptr) {
  4517. memcpy(dst, src, size);
  4518. } else {
  4519. memcpys->emplace_back(dst, src, size);
  4520. }
  4521. }
  4522. static void deferred_memset(void * dst, uint32_t val, size_t size, std::vector<vk_staging_memset>* memsets = nullptr) {
  4523. if (memsets == nullptr) {
  4524. memset(dst, val, size);
  4525. } else {
  4526. memsets->emplace_back(dst, val, size);
  4527. }
  4528. }
  4529. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  4530. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  4531. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  4532. ggml_vk_destroy_buffer(device->sync_staging);
  4533. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  4534. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4535. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  4536. }
  4537. }
  4538. 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) {
  4539. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  4540. GGML_ASSERT(!ggml_is_contiguous(tensor));
  4541. // Buffer is already mapped
  4542. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4543. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4544. GGML_ABORT("fatal error");
  4545. }
  4546. // Check if src is pinned memory
  4547. vk_buffer buf = nullptr;
  4548. size_t buf_offset = 0;
  4549. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  4550. const uint64_t ne0 = tensor->ne[0];
  4551. const uint64_t ne1 = tensor->ne[1];
  4552. const uint64_t ne2 = tensor->ne[2];
  4553. const uint64_t ne3 = tensor->ne[3];
  4554. const uint64_t nb0 = tensor->nb[0];
  4555. const uint64_t nb1 = tensor->nb[1];
  4556. const uint64_t nb2 = tensor->nb[2];
  4557. const uint64_t nb3 = tensor->nb[3];
  4558. const ggml_type type = tensor->type;
  4559. const uint64_t ts = ggml_type_size(type);
  4560. const uint64_t bs = ggml_blck_size(type);
  4561. const uint64_t dstnb0 = ts;
  4562. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  4563. const uint64_t dstnb2 = dstnb1*ne1;
  4564. const uint64_t dstnb3 = dstnb2*ne2;
  4565. const uint64_t ne = ggml_nelements(tensor);
  4566. if (buf != nullptr) {
  4567. // Memory is pinned, use as staging buffer
  4568. std::vector<vk::BufferCopy> slices;
  4569. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4570. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4571. // Find longest contiguous slice
  4572. if (ne1*nb1 == dstnb2) {
  4573. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  4574. } else {
  4575. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4576. if (ne0*nb0/bs == dstnb1) {
  4577. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  4578. } else {
  4579. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4580. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4581. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4582. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  4583. }
  4584. }
  4585. }
  4586. }
  4587. }
  4588. }
  4589. ggml_vk_sync_buffers(ctx, subctx);
  4590. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  4591. return;
  4592. }
  4593. if (!sync_staging) {
  4594. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  4595. }
  4596. // Staging buffer required
  4597. vk_buffer& staging = ctx->device->sync_staging;
  4598. const uint64_t copy_size = ts*ne/bs;
  4599. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  4600. VkBufferCopy buf_copy{ 0, offset, copy_size };
  4601. ggml_vk_sync_buffers(ctx, subctx);
  4602. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  4603. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4604. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4605. // Find longest contiguous slice
  4606. if (ne1*nb1 == dstnb2) {
  4607. 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);
  4608. } else {
  4609. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4610. if (ne0*nb0/bs == dstnb1) {
  4611. 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);
  4612. } else {
  4613. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4614. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4615. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4616. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  4617. }
  4618. }
  4619. }
  4620. }
  4621. }
  4622. }
  4623. }
  4624. 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) {
  4625. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  4626. // Buffer is already mapped
  4627. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4628. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4629. GGML_ABORT("fatal error");
  4630. }
  4631. // Check if src is pinned memory
  4632. vk_buffer buf = nullptr;
  4633. size_t buf_offset = 0;
  4634. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  4635. if (buf != nullptr) {
  4636. // Memory is pinned, use as staging buffer
  4637. std::vector<vk::BufferCopy> slices(1);
  4638. if (width == spitch) {
  4639. // Only do single write if stride is equal
  4640. slices[0].srcOffset = buf_offset;
  4641. slices[0].dstOffset = offset;
  4642. slices[0].size = width * height;
  4643. } else {
  4644. slices.resize(height);
  4645. for (size_t i = 0; i < height; i++) {
  4646. slices[i].srcOffset = buf_offset + i * spitch;
  4647. slices[i].dstOffset = offset + i * width;
  4648. slices[i].size = width;
  4649. }
  4650. }
  4651. ggml_vk_sync_buffers(nullptr, subctx);
  4652. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  4653. return;
  4654. }
  4655. VK_LOG_DEBUG("STAGING");
  4656. if (!sync_staging) {
  4657. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  4658. }
  4659. // Staging buffer required
  4660. const size_t copy_size = width*height;
  4661. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  4662. vk_buffer& staging_buffer = dst->device->sync_staging;
  4663. VkBufferCopy buf_copy = {
  4664. 0,
  4665. offset,
  4666. copy_size};
  4667. ggml_vk_sync_buffers(nullptr, subctx);
  4668. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  4669. if (width == spitch) {
  4670. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  4671. } else {
  4672. for (size_t i = 0; i < height; i++) {
  4673. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  4674. }
  4675. }
  4676. }
  4677. 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) {
  4678. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  4679. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  4680. }
  4681. 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) {
  4682. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  4683. // Buffer is already mapped
  4684. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4685. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  4686. for (size_t i = 0; i < height; i++) {
  4687. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  4688. }
  4689. } else {
  4690. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  4691. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  4692. ggml_vk_ctx_begin(dst->device, subctx);
  4693. ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  4694. ggml_vk_ctx_end(subctx);
  4695. for (auto& cpy : subctx->in_memcpys) {
  4696. memcpy(cpy.dst, cpy.src, cpy.n);
  4697. }
  4698. for (auto& mset : subctx->memsets) {
  4699. memset(mset.dst, mset.val, mset.n);
  4700. }
  4701. ggml_vk_submit(subctx, dst->device->fence);
  4702. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  4703. dst->device->device.resetFences({ dst->device->fence });
  4704. ggml_vk_queue_command_pools_cleanup(dst->device);
  4705. }
  4706. }
  4707. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  4708. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  4709. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  4710. }
  4711. 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) {
  4712. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  4713. GGML_ASSERT(width > 0);
  4714. GGML_ASSERT(height > 0);
  4715. GGML_ASSERT(src != nullptr);
  4716. // TODO: staging_offset is not used
  4717. // Check if dst is pinned memory
  4718. vk_buffer buf = nullptr;
  4719. size_t buf_offset = 0;
  4720. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  4721. std::vector<vk::BufferCopy> slices(1);
  4722. if (width == spitch && width == dpitch) {
  4723. // Only do single write if stride is equal
  4724. slices[0].srcOffset = offset;
  4725. slices[0].dstOffset = buf_offset;
  4726. slices[0].size = width * height;
  4727. } else {
  4728. slices.resize(height);
  4729. for (size_t i = 0; i < height; i++) {
  4730. slices[i].srcOffset = offset + i * spitch;
  4731. slices[i].dstOffset = buf_offset + i * dpitch;
  4732. slices[i].size = width;
  4733. }
  4734. }
  4735. if (buf != nullptr) {
  4736. // Memory is pinned, use as staging buffer
  4737. ggml_vk_sync_buffers(nullptr, subctx);
  4738. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  4739. return;
  4740. }
  4741. VK_LOG_DEBUG("STAGING");
  4742. if (!sync_staging) {
  4743. GGML_ABORT("Asynchronous read from non-pinned memory not supported");
  4744. }
  4745. // Fall back to staging buffer
  4746. const size_t copy_size = dpitch * height;
  4747. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  4748. vk_buffer& staging_buffer = src->device->sync_staging;
  4749. ggml_vk_sync_buffers(nullptr, subctx);
  4750. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  4751. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  4752. }
  4753. 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) {
  4754. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  4755. }
  4756. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  4757. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  4758. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  4759. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  4760. // the HW device to host copy path.
  4761. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  4762. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  4763. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  4764. } else {
  4765. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  4766. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  4767. ggml_vk_ctx_begin(src->device, subctx);
  4768. ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  4769. ggml_vk_ctx_end(subctx);
  4770. ggml_vk_submit(subctx, src->device->fence);
  4771. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  4772. src->device->device.resetFences({ src->device->fence });
  4773. ggml_vk_queue_command_pools_cleanup(src->device);
  4774. for (auto& cpy : subctx->out_memcpys) {
  4775. memcpy(cpy.dst, cpy.src, cpy.n);
  4776. }
  4777. }
  4778. }
  4779. 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) {
  4780. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  4781. // Make sure both buffers are on same device
  4782. GGML_ASSERT(src->device == dst->device);
  4783. VkBufferCopy bc{ src_offset, dst_offset, size };
  4784. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  4785. }
  4786. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  4787. if (src->device == dst->device) {
  4788. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  4789. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  4790. // Copy within the device
  4791. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  4792. ggml_vk_ctx_begin(src->device, subctx);
  4793. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  4794. ggml_vk_ctx_end(subctx);
  4795. ggml_vk_submit(subctx, src->device->fence);
  4796. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  4797. src->device->device.resetFences({ src->device->fence });
  4798. ggml_vk_queue_command_pools_cleanup(src->device);
  4799. } else {
  4800. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  4801. // Copy device to device
  4802. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  4803. ggml_vk_ensure_sync_staging_buffer(dst->device, size);
  4804. // Copy to src staging buffer
  4805. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  4806. // memcpy to dst staging buffer
  4807. memcpy(dst->device->sync_staging->ptr, src->device->sync_staging->ptr, size);
  4808. // Copy to dst buffer
  4809. ggml_vk_buffer_copy(dst, dst_offset, dst->device->sync_staging, 0, size);
  4810. }
  4811. }
  4812. static void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  4813. VK_LOG_DEBUG("ggml_vk_buffer_memset_async(" << offset << ", " << c << ", " << size << ")");
  4814. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  4815. dst->device->uma) {
  4816. deferred_memset((uint8_t*)dst->ptr + offset, c, size, &ctx->memsets);
  4817. return;
  4818. }
  4819. // Fall back to GPU fillBuffer for non-UMA or non-host-visible buffers
  4820. ctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  4821. }
  4822. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  4823. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  4824. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  4825. dst->device->uma) {
  4826. memset((uint8_t*)dst->ptr + offset, c, size);
  4827. return;
  4828. }
  4829. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  4830. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  4831. ggml_vk_ctx_begin(dst->device, subctx);
  4832. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  4833. ggml_vk_ctx_end(subctx);
  4834. ggml_vk_submit(subctx, dst->device->fence);
  4835. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  4836. dst->device->device.resetFences({ dst->device->fence });
  4837. ggml_vk_queue_command_pools_cleanup(dst->device);
  4838. }
  4839. static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, uint32_t m, uint32_t n, uint32_t k, const vk_pipeline& pipeline) {
  4840. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ")");
  4841. uint32_t split_k = 1;
  4842. if (ctx->device->shader_core_count != 0 && m >= pipeline->wg_denoms[0] && n >= pipeline->wg_denoms[1]) {
  4843. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  4844. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  4845. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  4846. if (k >= 2048) {
  4847. if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) {
  4848. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  4849. } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) {
  4850. split_k = 3;
  4851. }
  4852. // Cap the split at 8x. Unless k is huge this is a lot of overhead.
  4853. split_k = std::min(split_k, 8u);
  4854. // ggml_vk_matmul will align the splits to be a multiple of 256.
  4855. // If this rounded up size would cause the last split to be empty,
  4856. // then reduce the split count.
  4857. while (true) {
  4858. if (split_k == 1) {
  4859. break;
  4860. }
  4861. uint32_t k_split = CEIL_DIV(k, split_k);
  4862. k_split = ROUNDUP_POW2(k_split, 256);
  4863. if (k_split * (split_k - 1) < k) {
  4864. break;
  4865. }
  4866. split_k--;
  4867. }
  4868. }
  4869. }
  4870. return split_k;
  4871. }
  4872. static vk_pipeline ggml_vk_guess_matmul_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, uint32_t m, uint32_t n, bool aligned, ggml_type src0_type, ggml_type src1_type) {
  4873. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  4874. if (ctx->device->coopmat2) {
  4875. const uint32_t shader_core_count = ctx->device->shader_core_count;
  4876. const uint32_t tiles_l = CEIL_DIV(m, mmp->a_l->wg_denoms[0]) * CEIL_DIV(n, mmp->a_l->wg_denoms[1]);
  4877. const uint32_t tiles_m = CEIL_DIV(m, mmp->a_m->wg_denoms[0]) * CEIL_DIV(n, mmp->a_m->wg_denoms[1]);
  4878. // Use large shader when the N dimension is greater than the medium shader's tile size
  4879. uint32_t crossover_large = mmp->m->wg_denoms[1];
  4880. // Prefer large over medium if either:
  4881. // - medium or large tiles would overfill the GPU
  4882. // - large tiles with a split_k==3 fits in the GPU and medium tiles with split_k==2 does not
  4883. // (medium with split_k==2 is probably better if it fits - more workgroups running and less split_k overhead)
  4884. bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count ||
  4885. // split_k==3 with large tiles likely better than medium tiles with no split_k.
  4886. (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2);
  4887. if ((ctx->device->mul_mat_l[src0_type] && (n > crossover_large && prefer_large)) || (!ctx->device->mul_mat_m[src0_type] && !ctx->device->mul_mat_s[src0_type])) {
  4888. return aligned ? mmp->a_l : mmp->l;
  4889. }
  4890. // Use medium shader when the N dimension is greater than the small shader's tile size
  4891. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  4892. if ((ctx->device->mul_mat_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_s[src0_type]) {
  4893. return aligned ? mmp->a_m : mmp->m;
  4894. }
  4895. return aligned ? mmp->a_s : mmp->s;
  4896. }
  4897. if ((ctx->device->mul_mat_s[src0_type] && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_m[src0_type] && !ctx->device->mul_mat_l[src0_type])) {
  4898. return aligned ? mmp->a_s : mmp->s;
  4899. }
  4900. if ((ctx->device->mul_mat_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l[src0_type]) {
  4901. return aligned ? mmp->a_m : mmp->m;
  4902. }
  4903. return aligned ? mmp->a_l : mmp->l;
  4904. GGML_UNUSED(src1_type);
  4905. }
  4906. static uint32_t ggml_vk_guess_matmul_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, ggml_type src0_type, ggml_type src1_type) {
  4907. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  4908. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, src0_type, src1_type)->align;
  4909. }
  4910. static void ggml_vk_matmul(
  4911. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  4912. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  4913. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  4914. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  4915. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3,
  4916. uint32_t padded_n) {
  4917. VK_LOG_DEBUG("ggml_vk_matmul(a: (" << a.buffer->buffer << ", " << a.offset << ", " << a.size << "), b: (" << b.buffer->buffer << ", " << b.offset << ", " << b.size << "), d: (" << d.buffer->buffer << ", " << d.offset << ", " << d.size << "), split_k: (" << (split_k_buffer.buffer != nullptr ? split_k_buffer.buffer->buffer : VK_NULL_HANDLE) << ", " << split_k_buffer.offset << ", " << split_k_buffer.size << "), m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", split_k: " << split_k << ", batch: " << batch << ", ne02: " << ne02 << ", ne12: " << ne12 << ", broadcast2: " << broadcast2 << ", broadcast3: " << broadcast3 << ", padded_n: " << padded_n << ")");
  4918. if (split_k == 1) {
  4919. const vk_mat_mat_push_constants pc = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, k, ne02, ne12, broadcast2, broadcast3, padded_n };
  4920. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc, { m, n, batch });
  4921. return;
  4922. }
  4923. if (ctx->prealloc_split_k_need_sync) {
  4924. ggml_vk_sync_buffers(ctx, subctx);
  4925. }
  4926. GGML_ASSERT(batch_stride_d == m * n);
  4927. // Round the split size up to a multiple of 256 (k-quant alignment)
  4928. uint32_t k_split = CEIL_DIV(k, split_k);
  4929. k_split = ROUNDUP_POW2(k_split, 256);
  4930. const vk_mat_mat_push_constants pc1 = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, k_split, ne02, ne12, broadcast2, broadcast3, padded_n };
  4931. // Make sure enough workgroups get assigned for split k to work
  4932. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, split_k_buffer }, pc1, { (CEIL_DIV(m, pipeline->wg_denoms[0]) * pipeline->wg_denoms[0]) * split_k, n, batch });
  4933. ggml_vk_sync_buffers(ctx, subctx);
  4934. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  4935. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 });
  4936. ctx->prealloc_split_k_need_sync = true;
  4937. }
  4938. static vk_pipeline ggml_vk_guess_matmul_id_pipeline(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, uint32_t m, uint32_t n, bool aligned, ggml_type src0_type) {
  4939. VK_LOG_DEBUG("ggml_vk_guess_matmul_id_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ")");
  4940. if (ctx->device->coopmat2) {
  4941. // Use large shader when the N dimension is greater than the medium shader's tile size
  4942. uint32_t crossover_large = mmp->m->wg_denoms[1];
  4943. if ((ctx->device->mul_mat_id_l[src0_type] && (n > crossover_large)) || (!ctx->device->mul_mat_id_m[src0_type] && !ctx->device->mul_mat_id_s[src0_type])) {
  4944. return aligned ? mmp->a_l : mmp->l;
  4945. }
  4946. // Use medium shader when the N dimension is greater than the small shader's tile size
  4947. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  4948. if ((ctx->device->mul_mat_id_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_id_s[src0_type]) {
  4949. return aligned ? mmp->a_m : mmp->m;
  4950. }
  4951. return aligned ? mmp->a_s : mmp->s;
  4952. }
  4953. if ((ctx->device->mul_mat_id_s[src0_type] && (m <= 32 || n <= 32)) || (!ctx->device->mul_mat_id_m[src0_type] && !ctx->device->mul_mat_id_l[src0_type])) {
  4954. return aligned ? mmp->a_s : mmp->s;
  4955. }
  4956. if ((ctx->device->mul_mat_id_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l[src0_type]) {
  4957. return aligned ? mmp->a_m : mmp->m;
  4958. }
  4959. return aligned ? mmp->a_l : mmp->l;
  4960. }
  4961. static uint32_t ggml_vk_guess_matmul_id_pipeline_align(ggml_backend_vk_context * ctx, vk_matmul_pipeline& mmp, int m, int n, ggml_type src0_type) {
  4962. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ")");
  4963. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true, src0_type)->align;
  4964. }
  4965. static void ggml_vk_matmul_id(
  4966. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  4967. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  4968. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  4969. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  4970. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11,
  4971. uint32_t padded_n) {
  4972. 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 << "), " <<
  4973. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  4974. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  4975. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  4976. 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,
  4977. nei0, nei1, nbi1, ne11, padded_n };
  4978. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, pc, { m, nei1, n_as });
  4979. }
  4980. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  4981. return
  4982. tensor->nb[0] == ggml_type_size(tensor->type) &&
  4983. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  4984. (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]);
  4985. }
  4986. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  4987. // Choose "contiguous copy" shader if src/dst are contiguous
  4988. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  4989. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  4990. if (contig) {
  4991. return ctx->device->pipeline_contig_cpy_f32_f32;
  4992. } else {
  4993. return ctx->device->pipeline_cpy_f32_f32;
  4994. }
  4995. }
  4996. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  4997. if (contig) {
  4998. return ctx->device->pipeline_contig_cpy_f32_f16;
  4999. } else {
  5000. return ctx->device->pipeline_cpy_f32_f16;
  5001. }
  5002. }
  5003. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  5004. if (contig) {
  5005. return ctx->device->pipeline_contig_cpy_f16_f16;
  5006. } else {
  5007. return ctx->device->pipeline_cpy_f16_f16;
  5008. }
  5009. }
  5010. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) {
  5011. if (contig) {
  5012. return ctx->device->pipeline_contig_cpy_f16_f32;
  5013. } else {
  5014. return ctx->device->pipeline_cpy_f16_f32;
  5015. }
  5016. }
  5017. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) {
  5018. if (contig) {
  5019. return ctx->device->pipeline_contig_cpy_f32_bf16;
  5020. } else {
  5021. return ctx->device->pipeline_cpy_f32_bf16;
  5022. }
  5023. }
  5024. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
  5025. if (contig) {
  5026. return ctx->device->pipeline_contig_cpy_f32_i32;
  5027. } else {
  5028. return ctx->device->pipeline_cpy_f32_i32;
  5029. }
  5030. }
  5031. if (src->type == GGML_TYPE_I32 && to == GGML_TYPE_F32) {
  5032. if (contig) {
  5033. return ctx->device->pipeline_contig_cpy_i32_f32;
  5034. } else {
  5035. return ctx->device->pipeline_cpy_i32_f32;
  5036. }
  5037. }
  5038. if (src->type == GGML_TYPE_F32) {
  5039. switch (to) {
  5040. case GGML_TYPE_Q4_0:
  5041. case GGML_TYPE_Q4_1:
  5042. case GGML_TYPE_Q5_0:
  5043. case GGML_TYPE_Q5_1:
  5044. case GGML_TYPE_Q8_0:
  5045. case GGML_TYPE_IQ4_NL:
  5046. return ctx->device->pipeline_cpy_f32_quant[to];
  5047. default:
  5048. break;
  5049. }
  5050. }
  5051. if (to == GGML_TYPE_F32) {
  5052. switch (src->type) {
  5053. case GGML_TYPE_Q4_0:
  5054. case GGML_TYPE_Q4_1:
  5055. case GGML_TYPE_Q5_0:
  5056. case GGML_TYPE_Q5_1:
  5057. case GGML_TYPE_Q8_0:
  5058. case GGML_TYPE_IQ4_NL:
  5059. return ctx->device->pipeline_cpy_quant_f32[src->type];
  5060. default:
  5061. break;
  5062. }
  5063. }
  5064. if (src->type == to) {
  5065. // Copy two or four bytes at a time, depending on block size.
  5066. // For quantized types, we scale by block size/type size. But
  5067. // this path is also used for bf16->bf16 for example, where the
  5068. // type size must be exactly 2 or 4.
  5069. GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4);
  5070. if ((ggml_type_size(src->type) % 4) == 0) {
  5071. if (contig) {
  5072. return ctx->device->pipeline_contig_cpy_f32_f32;
  5073. } else {
  5074. return ctx->device->pipeline_cpy_f32_f32;
  5075. }
  5076. } else {
  5077. if (contig) {
  5078. return ctx->device->pipeline_contig_cpy_f16_f16;
  5079. } else {
  5080. return ctx->device->pipeline_cpy_f16_f16;
  5081. }
  5082. }
  5083. }
  5084. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  5085. GGML_ABORT("fatal error");
  5086. }
  5087. 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) {
  5088. 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] << "), ";
  5089. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  5090. const int tensor_type_size = ggml_type_size(tensor->type);
  5091. const uint32_t ne = ggml_nelements(tensor);
  5092. std::array<uint32_t, 3> elements;
  5093. if (ne > 262144) {
  5094. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  5095. } else if (ne > 512) {
  5096. elements = { 512, CEIL_DIV(ne, 512), 1 };
  5097. } else {
  5098. elements = { ne, 1, 1 };
  5099. }
  5100. vk_op_unary_push_constants pc = {
  5101. (uint32_t)ne,
  5102. (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,
  5103. (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]),
  5104. 0,
  5105. 0.0f, 0.0f,
  5106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5107. };
  5108. init_pushconst_fastdiv(pc);
  5109. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements);
  5110. ggml_vk_sync_buffers(ctx, subctx);
  5111. }
  5112. static vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type, bool use_x4_blocks) {
  5113. switch(type) {
  5114. case GGML_TYPE_Q8_1:
  5115. return use_x4_blocks ? ctx->device->pipeline_quantize_q8_1_x4 : ctx->device->pipeline_quantize_q8_1;
  5116. default:
  5117. std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl;
  5118. GGML_ABORT("fatal error");
  5119. }
  5120. }
  5121. static void ggml_vk_quantize_q8_1(ggml_backend_vk_context * ctx, vk_context& subctx, vk_subbuffer&& in, vk_subbuffer&& out, uint32_t ne, bool use_x4_blocks = false) {
  5122. VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")");
  5123. vk_pipeline pipeline = use_x4_blocks ? ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true) : ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, false);
  5124. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, std::array<uint32_t, 1>{ne}, { ne, 1, 1 });
  5125. ggml_vk_sync_buffers(ctx, subctx);
  5126. }
  5127. 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) {
  5128. VK_LOG_DEBUG("ggml_vk_mul_mat_q_f16((" << src0 << ", name=" << src0->name << ", type=" << ggml_type_name(src0->type) << ", ne0=" << src0->ne[0] << ", ne1=" << src0->ne[1] << ", ne2=" << src0->ne[2] << ", ne3=" << src0->ne[3] << ", nb0=" << src0->nb[0] << ", nb1=" << src0->nb[1] << ", nb2=" << src0->nb[2] << ", nb3=" << src0->nb[3];
  5129. std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << ggml_type_name(src1->type) << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
  5130. std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << ggml_type_name(dst->type) << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
  5131. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5132. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5133. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5134. const uint64_t ne00 = src0->ne[0];
  5135. const uint64_t ne01 = src0->ne[1];
  5136. const uint64_t ne02 = src0->ne[2];
  5137. const uint64_t ne03 = src0->ne[3];
  5138. const uint64_t ne10 = src1->ne[0];
  5139. const uint64_t ne11 = src1->ne[1];
  5140. const uint64_t ne12 = src1->ne[2];
  5141. const uint64_t ne13 = src1->ne[3];
  5142. const uint64_t ne20 = dst->ne[0];
  5143. const uint64_t ne21 = dst->ne[1];
  5144. const uint64_t r2 = ne12 / ne02;
  5145. const uint64_t r3 = ne13 / ne03;
  5146. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5147. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5148. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5149. vk_buffer d_Qx = nullptr;
  5150. size_t qx_buf_offset = 0;
  5151. vk_buffer d_Qy = nullptr;
  5152. size_t qy_buf_offset = 0;
  5153. bool src0_uma = false;
  5154. bool src1_uma = false;
  5155. if (ctx->device->uma) {
  5156. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5157. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5158. src0_uma = d_Qx != nullptr;
  5159. src1_uma = d_Qy != nullptr;
  5160. }
  5161. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5162. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5163. !ggml_vk_dim01_contiguous(src0);
  5164. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5165. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5166. !ggml_vk_dim01_contiguous(src1);
  5167. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5168. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5169. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5170. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0;
  5171. // Check for mmq first
  5172. vk_matmul_pipeline mmp = quantize_y ? ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, GGML_TYPE_Q8_1, (ggml_prec)dst->op_params[0]) : nullptr;
  5173. if (mmp == nullptr) {
  5174. // Fall back to f16 dequant mul mat
  5175. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  5176. quantize_y = false;
  5177. }
  5178. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5179. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  5180. if (qx_needs_dequant) {
  5181. // Fall back to dequant + f16 mulmat
  5182. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, f16_type, y_f32_kernel ? GGML_TYPE_F32 : f16_type, (ggml_prec)dst->op_params[0]);
  5183. }
  5184. // Not implemented
  5185. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5186. const uint32_t kpad = quantize_y ? 0 : ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align(ctx, mmp, ne01, ne11, qx_needs_dequant ? f16_type : src0->type, quantize_y ? GGML_TYPE_Q8_1 : (y_f32_kernel ? GGML_TYPE_F32 : src1->type)));
  5187. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8;
  5188. vk_pipeline pipeline = ggml_vk_guess_matmul_pipeline(ctx, mmp, ne01, ne11, aligned, qx_needs_dequant ? f16_type : src0->type, quantize_y ? GGML_TYPE_Q8_1 : (y_f32_kernel ? GGML_TYPE_F32 : src1->type));
  5189. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  5190. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11;
  5191. const int x_ne = ne01 * ne00;
  5192. const int y_ne = padded_n * ne10;
  5193. const int d_ne = ne11 * ne01;
  5194. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, pipeline);
  5195. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  5196. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5197. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  5198. const uint64_t y_sz = quantize_y ? (y_ne * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  5199. const uint64_t d_sz = sizeof(float) * d_ne;
  5200. vk_pipeline to_fp16_vk_0 = nullptr;
  5201. vk_pipeline to_fp16_vk_1 = nullptr;
  5202. vk_pipeline to_q8_1 = nullptr;
  5203. if (x_non_contig) {
  5204. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  5205. } else {
  5206. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  5207. }
  5208. if (y_non_contig) {
  5209. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  5210. } else {
  5211. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5212. }
  5213. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5214. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5215. if (quantize_y) {
  5216. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true);
  5217. }
  5218. if (dryrun) {
  5219. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  5220. uint64_t y_sz_upd = y_sz * ne12 * ne13;
  5221. if (quantize_y) {
  5222. y_sz_upd = CEIL_DIV(y_sz_upd, 144) * 144;
  5223. }
  5224. const uint64_t split_k_size = split_k > 1 ? d_sz * ne12 * ne13 * split_k : 0;
  5225. if (
  5226. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  5227. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size) ||
  5228. (split_k > 1 && split_k_size > ctx->device->max_memory_allocation_size)) {
  5229. GGML_ABORT("Requested preallocation size is too large");
  5230. }
  5231. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  5232. ctx->prealloc_size_x = x_sz_upd;
  5233. }
  5234. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz_upd) {
  5235. ctx->prealloc_size_y = y_sz_upd;
  5236. }
  5237. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  5238. ctx->prealloc_size_split_k = split_k_size;
  5239. }
  5240. // Request descriptor sets
  5241. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  5242. if (qx_needs_dequant) {
  5243. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5244. }
  5245. if (qy_needs_dequant) {
  5246. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5247. }
  5248. if (quantize_y) {
  5249. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5250. }
  5251. if (split_k > 1) {
  5252. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  5253. }
  5254. return;
  5255. }
  5256. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5257. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5258. GGML_ASSERT(d_D != nullptr);
  5259. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz * ne02 * ne03);
  5260. vk_buffer d_X;
  5261. uint64_t x_buf_offset = 0;
  5262. vk_buffer d_Y;
  5263. uint64_t y_buf_offset = 0;
  5264. if (!src0_uma) {
  5265. d_Qx = src0_buf_ctx->dev_buffer;
  5266. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5267. GGML_ASSERT(d_Qx != nullptr);
  5268. }
  5269. if (!src1_uma) {
  5270. d_Qy = src1_buf_ctx->dev_buffer;
  5271. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5272. GGML_ASSERT(d_Qy != nullptr);
  5273. }
  5274. if (qx_needs_dequant) {
  5275. d_X = ctx->prealloc_x;
  5276. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  5277. } else {
  5278. d_X = d_Qx;
  5279. x_buf_offset = qx_buf_offset;
  5280. GGML_ASSERT(qx_sz == x_sz);
  5281. }
  5282. if (qy_needs_dequant) {
  5283. d_Y = ctx->prealloc_y;
  5284. GGML_ASSERT(d_Y->size >= y_sz * ne12 * ne13);
  5285. } else if (quantize_y) {
  5286. d_Y = ctx->prealloc_y;
  5287. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz * ne12 * ne13, 144) * 144);
  5288. } else {
  5289. d_Y = d_Qy;
  5290. y_buf_offset = qy_buf_offset;
  5291. GGML_ASSERT(qy_sz == y_sz);
  5292. }
  5293. if (x_non_contig || qx_needs_dequant) {
  5294. if (ctx->prealloc_x_need_sync) {
  5295. ggml_vk_sync_buffers(ctx, subctx);
  5296. }
  5297. }
  5298. if (x_non_contig) {
  5299. 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 });
  5300. } else if (qx_needs_dequant) {
  5301. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  5302. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, vk_subbuffer{ d_X, 0, x_sz * ne02 * ne03 } }, pc, { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  5303. ggml_vk_sync_buffers(ctx, subctx);
  5304. }
  5305. if (y_non_contig) {
  5306. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5307. ctx->prealloc_y_last_tensor_used != src1) {
  5308. if (ctx->prealloc_y_need_sync) {
  5309. ggml_vk_sync_buffers(ctx, subctx);
  5310. }
  5311. 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 });
  5312. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5313. ctx->prealloc_y_last_tensor_used = src1;
  5314. }
  5315. }
  5316. if (quantize_y) {
  5317. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5318. ctx->prealloc_y_last_tensor_used != src1) {
  5319. if (ctx->prealloc_y_need_sync) {
  5320. ggml_vk_sync_buffers(ctx, subctx);
  5321. }
  5322. ggml_vk_quantize_q8_1(ctx, subctx, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE }, y_ne * ne12 * ne13, true);
  5323. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5324. ctx->prealloc_y_last_tensor_used = src1;
  5325. }
  5326. }
  5327. uint32_t stride_batch_x = ne00*ne01;
  5328. uint32_t stride_batch_y = ne10*ne11;
  5329. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5330. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5331. }
  5332. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  5333. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5334. }
  5335. uint32_t y_sz_total = y_sz * ne12 * ne13;
  5336. if (quantize_y) {
  5337. y_sz_total = CEIL_DIV(y_sz_total, 144) * 144;
  5338. }
  5339. // compute
  5340. ggml_vk_matmul(
  5341. ctx, subctx, pipeline,
  5342. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz_total },
  5343. { d_D, d_buf_offset, d_sz * ne12 * ne13 }, { ctx->prealloc_split_k, 0, d_sz * ne12 * ne13 * split_k },
  5344. ne01, ne11, ne10,
  5345. ne10, ne10, ne01, stride_batch_x, stride_batch_y, ne20*ne21,
  5346. split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n
  5347. ); // NOLINT
  5348. if (x_non_contig || qx_needs_dequant) {
  5349. ctx->prealloc_x_need_sync = true;
  5350. }
  5351. if (y_non_contig || quantize_y) {
  5352. ctx->prealloc_y_need_sync = true;
  5353. }
  5354. }
  5355. // Device tuning
  5356. static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_t n, uint32_t k, ggml_type src0_type) {
  5357. if (device->mmvq_mode == 1) {
  5358. return true;
  5359. } else if (device->mmvq_mode == -1) {
  5360. return false;
  5361. }
  5362. // MMVQ is generally good for batches
  5363. if (n > 1) {
  5364. return true;
  5365. }
  5366. switch (device->vendor_id) {
  5367. case VK_VENDOR_ID_NVIDIA:
  5368. switch (src0_type) {
  5369. case GGML_TYPE_Q8_0:
  5370. return device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  5371. default:
  5372. return true;
  5373. }
  5374. case VK_VENDOR_ID_AMD:
  5375. switch (src0_type) {
  5376. case GGML_TYPE_Q8_0:
  5377. return device->architecture == vk_device_architecture::AMD_GCN;
  5378. default:
  5379. return true;
  5380. }
  5381. case VK_VENDOR_ID_INTEL:
  5382. switch (src0_type) {
  5383. // From tests on A770 Linux, may need more tuning
  5384. case GGML_TYPE_Q4_0:
  5385. case GGML_TYPE_Q5_1:
  5386. return false;
  5387. default:
  5388. return true;
  5389. }
  5390. default:
  5391. return true;
  5392. }
  5393. GGML_UNUSED(m);
  5394. GGML_UNUSED(k);
  5395. }
  5396. 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) {
  5397. 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];
  5398. 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];
  5399. 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];
  5400. std::cerr << "), " << (dryrun ? "dryrun" : "") << "),)");
  5401. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5402. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5403. const uint64_t ne00 = src0->ne[0];
  5404. const uint64_t ne01 = src0->ne[1];
  5405. const uint64_t ne02 = src0->ne[2];
  5406. const uint64_t ne03 = src0->ne[3];
  5407. const uint64_t ne10 = src1->ne[0];
  5408. const uint64_t ne11 = src1->ne[1];
  5409. const uint64_t ne12 = src1->ne[2];
  5410. const uint64_t ne13 = src1->ne[3];
  5411. const uint64_t ne20 = dst->ne[0];
  5412. const uint64_t ne21 = dst->ne[1];
  5413. const uint64_t ne22 = dst->ne[2];
  5414. const uint64_t ne23 = dst->ne[3];
  5415. const uint64_t r2 = ne12 / ne02;
  5416. const uint64_t r3 = ne13 / ne03;
  5417. // batch_n indicates that we need to compute a few vector results, and this assumes
  5418. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  5419. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  5420. bool batch_n = ne11 > 1;
  5421. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5422. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5423. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5424. vk_buffer d_Qx = nullptr;
  5425. size_t qx_buf_offset = 0;
  5426. vk_buffer d_Qy = nullptr;
  5427. size_t qy_buf_offset = 0;
  5428. bool src0_uma = false;
  5429. bool src1_uma = false;
  5430. if (ctx->device->uma) {
  5431. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5432. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5433. src0_uma = d_Qx != nullptr;
  5434. src1_uma = d_Qy != nullptr;
  5435. }
  5436. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  5437. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  5438. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  5439. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0 && ggml_vk_should_use_mmvq(ctx->device, ne01, ne11, ne10, src0->type);
  5440. vk_pipeline to_fp16_vk_0 = nullptr;
  5441. vk_pipeline to_fp16_vk_1 = nullptr;
  5442. if (x_non_contig) {
  5443. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  5444. }
  5445. if (y_non_contig) {
  5446. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  5447. } else {
  5448. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5449. }
  5450. // Check for mmq first
  5451. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr;
  5452. vk_pipeline to_q8_1 = nullptr;
  5453. if (dmmv == nullptr) {
  5454. // Fall back to f16 dequant mul mat
  5455. dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11, ne20, ne00);
  5456. quantize_y = false;
  5457. }
  5458. if (quantize_y) {
  5459. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true);
  5460. }
  5461. const bool qx_needs_dequant = x_non_contig;
  5462. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  5463. // Not implemented
  5464. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5465. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5466. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5467. GGML_ASSERT(dmmv != nullptr);
  5468. const uint64_t x_ne = ne01 * ne00;
  5469. const uint64_t y_ne = ne11 * ne10;
  5470. const uint64_t d_ne = ne11 * ne01;
  5471. 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);
  5472. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5473. 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;
  5474. const uint64_t y_sz = quantize_y ? (y_ne * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) : (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  5475. const uint64_t d_sz = sizeof(float) * d_ne;
  5476. if (dryrun) {
  5477. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  5478. uint64_t y_sz_upd = y_sz * ne12 * ne13;
  5479. if (quantize_y) {
  5480. y_sz_upd = CEIL_DIV(y_sz_upd, 144) * 144;
  5481. }
  5482. if (
  5483. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  5484. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  5485. GGML_ABORT("Requested preallocation size is too large");
  5486. }
  5487. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  5488. ctx->prealloc_size_x = x_sz_upd;
  5489. }
  5490. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz_upd) {
  5491. ctx->prealloc_size_y = y_sz_upd;
  5492. }
  5493. // Request descriptor sets
  5494. if (qx_needs_dequant) {
  5495. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5496. }
  5497. if (qy_needs_dequant) {
  5498. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5499. }
  5500. if (quantize_y) {
  5501. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5502. }
  5503. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  5504. return;
  5505. }
  5506. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5507. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5508. GGML_ASSERT(d_D != nullptr);
  5509. vk_buffer d_X;
  5510. uint64_t x_buf_offset = 0;
  5511. vk_buffer d_Y;
  5512. uint64_t y_buf_offset = 0;
  5513. if(!src0_uma) {
  5514. d_Qx = src0_buf_ctx->dev_buffer;
  5515. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5516. GGML_ASSERT(d_Qx != nullptr);
  5517. }
  5518. if(!src1_uma) {
  5519. d_Qy = src1_buf_ctx->dev_buffer;
  5520. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5521. GGML_ASSERT(d_Qy != nullptr);
  5522. }
  5523. if (qx_needs_dequant) {
  5524. d_X = ctx->prealloc_x;
  5525. } else {
  5526. d_X = d_Qx;
  5527. x_buf_offset = qx_buf_offset;
  5528. GGML_ASSERT(qx_sz == x_sz);
  5529. }
  5530. if (qy_needs_dequant) {
  5531. d_Y = ctx->prealloc_y;
  5532. } else if (quantize_y) {
  5533. d_Y = ctx->prealloc_y;
  5534. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz * ne12 * ne13, 144) * 144);
  5535. } else {
  5536. d_Y = d_Qy;
  5537. y_buf_offset = qy_buf_offset;
  5538. GGML_ASSERT(qy_sz == y_sz);
  5539. }
  5540. if (x_non_contig) {
  5541. if (ctx->prealloc_x_need_sync) {
  5542. ggml_vk_sync_buffers(ctx, subctx);
  5543. }
  5544. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  5545. 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 });
  5546. }
  5547. if (y_non_contig) {
  5548. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  5549. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5550. ctx->prealloc_y_last_tensor_used != src1) {
  5551. if (ctx->prealloc_y_need_sync) {
  5552. ggml_vk_sync_buffers(ctx, subctx);
  5553. }
  5554. 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 });
  5555. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5556. ctx->prealloc_y_last_tensor_used = src1;
  5557. }
  5558. }
  5559. if (quantize_y) {
  5560. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5561. ctx->prealloc_y_last_tensor_used != src1) {
  5562. if (ctx->prealloc_y_need_sync) {
  5563. ggml_vk_sync_buffers(ctx, subctx);
  5564. }
  5565. ggml_vk_quantize_q8_1(ctx, subctx, { d_Qy, qy_buf_offset, VK_WHOLE_SIZE }, { d_Y, 0, VK_WHOLE_SIZE }, y_ne * ne12 * ne13, true);
  5566. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5567. ctx->prealloc_y_last_tensor_used = src1;
  5568. }
  5569. }
  5570. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  5571. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  5572. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  5573. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  5574. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5575. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5576. }
  5577. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  5578. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5579. }
  5580. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  5581. uint32_t groups_x = ne01;
  5582. uint32_t groups_z = 1;
  5583. if (ne01 > max_groups_x) {
  5584. groups_z = 64;
  5585. groups_x = CEIL_DIV(groups_x, groups_z);
  5586. }
  5587. // TODO: Clean up this whole sz * ne_2 * ne_3 thing, it hasn't been necessary for a long time
  5588. uint32_t y_sz_total = y_sz * ne12 * ne13;
  5589. if (quantize_y) {
  5590. y_sz_total = CEIL_DIV(y_sz_total, 144) * 144;
  5591. }
  5592. // compute
  5593. const vk_mat_vec_push_constants pc = {
  5594. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  5595. stride_batch_x, stride_batch_y, stride_batch_d,
  5596. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  5597. };
  5598. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  5599. { vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 }, vk_subbuffer{ d_Y, y_buf_offset, y_sz_total }, vk_subbuffer{ d_D, d_buf_offset, d_sz * ne22 * ne23} },
  5600. pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  5601. if (x_non_contig) {
  5602. ctx->prealloc_x_need_sync = true;
  5603. }
  5604. if (y_non_contig || quantize_y) {
  5605. ctx->prealloc_y_need_sync = true;
  5606. }
  5607. }
  5608. 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) {
  5609. 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];
  5610. 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];
  5611. 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];
  5612. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5613. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  5614. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  5615. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  5616. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  5617. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  5618. const uint64_t ne00 = src0->ne[0];
  5619. const uint64_t ne01 = src0->ne[1];
  5620. const uint64_t ne02 = src0->ne[2];
  5621. // const uint64_t ne03 = src0->ne[3];
  5622. const uint64_t ne10 = src1->ne[0];
  5623. const uint64_t ne11 = src1->ne[1];
  5624. const uint64_t ne12 = src1->ne[2];
  5625. // const uint64_t ne13 = src1->ne[3];
  5626. GGML_ASSERT(ne11 == 1);
  5627. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5628. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5629. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5630. vk_buffer d_Qy = nullptr;
  5631. size_t qy_buf_offset = 0;
  5632. bool src1_uma = false;
  5633. if (ctx->device->uma) {
  5634. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5635. src1_uma = d_Qy != nullptr;
  5636. }
  5637. const uint64_t x_ne = ne00 * ne01 * ne02;
  5638. const uint64_t y_ne = ne10 * ne11 * ne12;
  5639. const uint64_t d_ne = ne01 * ne11 * ne12;
  5640. 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);
  5641. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5642. const uint64_t d_sz = sizeof(float) * d_ne;
  5643. // With grouped query attention there are > 1 Q matrices per K, V matrix.
  5644. uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02;
  5645. if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) {
  5646. gqa_ratio = 1;
  5647. }
  5648. if (dryrun) {
  5649. // Request descriptor sets
  5650. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], 1);
  5651. return;
  5652. }
  5653. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5654. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5655. GGML_ASSERT(d_D != nullptr);
  5656. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  5657. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5658. GGML_ASSERT(d_Qx != nullptr);
  5659. if (!src1_uma) {
  5660. d_Qy = src1_buf_ctx->dev_buffer;
  5661. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5662. GGML_ASSERT(d_Qx != nullptr);
  5663. }
  5664. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5665. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  5666. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5667. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  5668. // compute
  5669. 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)) };
  5670. uint32_t workgroups_z = (uint32_t)ne12;
  5671. // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups
  5672. if (gqa_ratio > 1) {
  5673. workgroups_z /= gqa_ratio;
  5674. }
  5675. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset }, vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset } }, pc, { 1, (uint32_t)ne01, workgroups_z });
  5676. }
  5677. 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) {
  5678. 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];
  5679. 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];
  5680. 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];
  5681. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5682. GGML_ASSERT(!ggml_is_transposed(src0));
  5683. GGML_ASSERT(!ggml_is_transposed(src1));
  5684. GGML_ASSERT(!ggml_is_permuted(src0));
  5685. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  5686. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  5687. const uint64_t ne00 = src0->ne[0];
  5688. const uint64_t ne01 = src0->ne[1];
  5689. const uint64_t ne02 = src0->ne[2];
  5690. const uint64_t ne03 = src0->ne[3];
  5691. const uint64_t nb01 = src0->nb[1];
  5692. const uint64_t nb02 = src0->nb[2];
  5693. const uint64_t nb12 = src1->nb[2];
  5694. // const uint64_t ne10 = src1->ne[0];
  5695. const uint64_t ne11 = src1->ne[1];
  5696. const uint64_t ne12 = src1->ne[2];
  5697. // const uint64_t ne13 = src1->ne[3];
  5698. const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t));
  5699. const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float));
  5700. const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float));
  5701. GGML_ASSERT(ne11 == 1);
  5702. GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in supports_op
  5703. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5704. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5705. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5706. vk_buffer d_Qy = nullptr;
  5707. size_t qy_buf_offset = 0;
  5708. bool src1_uma = false;
  5709. if (ctx->device->uma) {
  5710. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5711. src1_uma = d_Qy != nullptr;
  5712. }
  5713. const uint64_t d_ne = ne01 * ne11 * ne12 * ne03;
  5714. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  5715. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  5716. const uint32_t channel_stride_y = nb12 / sizeof(float);
  5717. const uint64_t qx_sz = ggml_nbytes(src0);
  5718. const uint64_t qy_sz = ggml_nbytes(src1);
  5719. const uint64_t d_sz = sizeof(float) * d_ne;
  5720. if (dryrun) {
  5721. // Request descriptor sets
  5722. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  5723. return;
  5724. }
  5725. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5726. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5727. GGML_ASSERT(d_D != nullptr);
  5728. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  5729. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5730. GGML_ASSERT(d_Qx != nullptr);
  5731. if (!src1_uma) {
  5732. d_Qy = src1_buf_ctx->dev_buffer;
  5733. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5734. GGML_ASSERT(d_Qx != nullptr);
  5735. }
  5736. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5737. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  5738. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5739. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  5740. // compute
  5741. const std::array<uint32_t, 12> pc = { (uint32_t)ne00, (uint32_t)ne01, row_stride_x, channel_stride_x, channel_stride_y, (uint32_t)(ne12 / ne02), (uint32_t)ne12, (uint32_t)(qy_shader_offset / ggml_type_size(src1->type)), (uint32_t)(d_shader_offset / ggml_type_size(dst->type)), nb03, nb13, nb23 };
  5742. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  5743. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_Qy, qy_buffer_offset, qy_sz + qy_shader_offset }, vk_subbuffer{ d_D, d_buffer_offset, d_sz + d_shader_offset } }, pc, { (uint32_t)ne03, (uint32_t)ne01, (uint32_t)ne12 });
  5744. }
  5745. 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) {
  5746. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  5747. if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  5748. // detect 0213 permutation, and batch size of 1
  5749. src0->nb[0] <= src0->nb[2] &&
  5750. src0->nb[2] <= src0->nb[1] &&
  5751. src0->nb[1] <= src0->nb[3] &&
  5752. src1->nb[0] <= src1->nb[2] &&
  5753. src1->nb[2] <= src1->nb[1] &&
  5754. src1->nb[1] <= src1->nb[3] &&
  5755. src0->ne[3] == 1 &&
  5756. src1->ne[3] == 1) {
  5757. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  5758. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  5759. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  5760. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  5761. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  5762. // when ne12 and ne13 are one.
  5763. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  5764. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
  5765. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, src0, src1, dst, dryrun);
  5766. } else {
  5767. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, dryrun);
  5768. }
  5769. }
  5770. 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) {
  5771. 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];
  5772. 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];
  5773. 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];
  5774. 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] << "),)");
  5775. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5776. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  5777. const uint64_t ne00 = src0->ne[0];
  5778. const uint64_t ne01 = src0->ne[1];
  5779. const uint64_t ne02 = src0->ne[2];
  5780. const uint64_t ne03 = src0->ne[3];
  5781. const uint64_t ne10 = src1->ne[0];
  5782. const uint64_t ne11 = src1->ne[1];
  5783. const uint64_t ne12 = src1->ne[2];
  5784. const uint64_t ne13 = src1->ne[3];
  5785. const uint64_t nei0 = ids->ne[0];
  5786. const uint64_t nei1 = ids->ne[1];
  5787. const uint32_t nbi1 = ids->nb[1];
  5788. const uint32_t nbi2 = ids->nb[2];
  5789. const uint64_t ne20 = dst->ne[0];
  5790. const uint64_t ne21 = dst->ne[1];
  5791. const uint64_t ne22 = dst->ne[2];
  5792. const uint64_t ne23 = dst->ne[3];
  5793. const uint64_t n_as = ne02;
  5794. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5795. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5796. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5797. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  5798. vk_buffer d_Qx = nullptr;
  5799. size_t qx_buf_offset = 0;
  5800. vk_buffer d_Qy = nullptr;
  5801. size_t qy_buf_offset = 0;
  5802. vk_buffer d_ids = nullptr;
  5803. size_t ids_buf_offset = 0;
  5804. bool src0_uma = false;
  5805. bool src1_uma = false;
  5806. bool ids_uma = false;
  5807. if (ctx->device->uma) {
  5808. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5809. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5810. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  5811. src0_uma = d_Qx != nullptr;
  5812. src1_uma = d_Qy != nullptr;
  5813. ids_uma = d_ids != nullptr;
  5814. }
  5815. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5816. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5817. !ggml_vk_dim01_contiguous(src0);
  5818. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5819. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5820. !ggml_vk_dim01_contiguous(src1);
  5821. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5822. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5823. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5824. vk_matmul_pipeline mmp = ggml_vk_get_mul_mat_mat_id_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  5825. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5826. const bool qy_needs_dequant = (src1->type != f16_type && !y_f32_kernel) || y_non_contig;
  5827. if (qx_needs_dequant) {
  5828. // Fall back to dequant + f16 mulmat
  5829. mmp = ggml_vk_get_mul_mat_mat_id_pipeline(ctx, f16_type, y_f32_kernel ? GGML_TYPE_F32 : f16_type, (ggml_prec)dst->op_params[0]);
  5830. }
  5831. // Not implemented
  5832. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5833. const uint32_t kpad = ggml_vk_align_size(ne10, ggml_vk_guess_matmul_id_pipeline_align(ctx, mmp, ne01, nei1, qx_needs_dequant ? f16_type : src0->type));
  5834. const bool aligned = ne10 == kpad && ne01 > 8 && nei1 > 8;
  5835. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned, qx_needs_dequant ? f16_type : src0->type);
  5836. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  5837. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) :ne11;
  5838. const uint64_t x_ne = ne01 * ne00;
  5839. const uint64_t y_ne = padded_n * ne10;
  5840. const uint64_t d_ne = ne21 * ne20;
  5841. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  5842. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5843. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  5844. const uint64_t y_sz = y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  5845. const uint64_t ids_sz = nbi2;
  5846. const uint64_t d_sz = sizeof(float) * d_ne;
  5847. vk_pipeline to_fp16_vk_0 = nullptr;
  5848. vk_pipeline to_fp16_vk_1 = nullptr;
  5849. if (x_non_contig) {
  5850. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  5851. } else {
  5852. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  5853. }
  5854. if (y_non_contig) {
  5855. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  5856. } else {
  5857. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5858. }
  5859. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5860. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5861. if (dryrun) {
  5862. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  5863. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  5864. if (
  5865. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  5866. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  5867. GGML_ABORT("Requested preallocation size is too large");
  5868. }
  5869. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  5870. ctx->prealloc_size_x = x_sz_upd;
  5871. }
  5872. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  5873. ctx->prealloc_size_y = y_sz_upd;
  5874. }
  5875. // Request descriptor sets
  5876. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  5877. if (qx_needs_dequant) {
  5878. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5879. }
  5880. if (qy_needs_dequant) {
  5881. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5882. }
  5883. return;
  5884. }
  5885. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5886. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5887. GGML_ASSERT(d_D != nullptr);
  5888. vk_buffer d_X;
  5889. uint64_t x_buf_offset = 0;
  5890. vk_buffer d_Y;
  5891. uint64_t y_buf_offset = 0;
  5892. if (!src0_uma) {
  5893. d_Qx = src0_buf_ctx->dev_buffer;
  5894. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5895. GGML_ASSERT(d_Qx != nullptr);
  5896. }
  5897. if (!src1_uma) {
  5898. d_Qy = src1_buf_ctx->dev_buffer;
  5899. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5900. GGML_ASSERT(d_Qy != nullptr);
  5901. }
  5902. if (!ids_uma) {
  5903. d_ids = ids_buf_ctx->dev_buffer;
  5904. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  5905. GGML_ASSERT(d_ids != nullptr);
  5906. }
  5907. if (qx_needs_dequant) {
  5908. d_X = ctx->prealloc_x;
  5909. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  5910. } else {
  5911. d_X = d_Qx;
  5912. x_buf_offset = qx_buf_offset;
  5913. GGML_ASSERT(qx_sz == x_sz);
  5914. }
  5915. if (qy_needs_dequant) {
  5916. d_Y = ctx->prealloc_y;
  5917. GGML_ASSERT(d_Y->size >= y_sz * ne12 * ne13);
  5918. } else {
  5919. d_Y = d_Qy;
  5920. y_buf_offset = qy_buf_offset;
  5921. GGML_ASSERT(qy_sz == y_sz);
  5922. }
  5923. if (x_non_contig || qx_needs_dequant) {
  5924. if (ctx->prealloc_x_need_sync) {
  5925. ggml_vk_sync_buffers(ctx, subctx);
  5926. }
  5927. }
  5928. if (x_non_contig) {
  5929. 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 });
  5930. } else if (qx_needs_dequant) {
  5931. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  5932. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  5933. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz * ne02 * ne03 }, vk_subbuffer{ d_X, 0, x_sz * ne02 * ne03 } }, pc, { (uint32_t)(x_ne * ne02 * ne03), 1, 1});
  5934. ggml_vk_sync_buffers(ctx, subctx);
  5935. }
  5936. if (y_non_contig) {
  5937. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5938. ctx->prealloc_y_last_tensor_used != src1) {
  5939. if (ctx->prealloc_y_need_sync) {
  5940. ggml_vk_sync_buffers(ctx, subctx);
  5941. }
  5942. 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 });
  5943. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5944. ctx->prealloc_y_last_tensor_used = src1;
  5945. }
  5946. }
  5947. uint32_t stride_batch_x = ne00*ne01;
  5948. uint32_t stride_batch_y = ne10*ne11;
  5949. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5950. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5951. }
  5952. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  5953. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5954. }
  5955. // compute
  5956. ggml_vk_matmul_id(
  5957. ctx, subctx, pipeline,
  5958. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz * ne12 * ne13 },
  5959. { d_D, d_buf_offset, d_sz * ne22 * ne23 }, { d_ids, ids_buf_offset, ids_sz },
  5960. ne01, ne21, ne10, ne10, ne10, ne01,
  5961. stride_batch_x, stride_batch_y, ne20*ne21,
  5962. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, padded_n
  5963. ); // NOLINT
  5964. if (x_non_contig || qx_needs_dequant) {
  5965. ctx->prealloc_x_need_sync = true;
  5966. }
  5967. if (y_non_contig) {
  5968. ctx->prealloc_y_need_sync = true;
  5969. }
  5970. }
  5971. 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) {
  5972. 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];
  5973. 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];
  5974. 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];
  5975. 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];
  5976. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5977. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5978. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5979. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  5980. const uint64_t ne00 = src0->ne[0];
  5981. const uint64_t ne01 = src0->ne[1];
  5982. const uint64_t ne02 = src0->ne[2];
  5983. const uint64_t ne03 = src0->ne[3];
  5984. const uint64_t ne10 = src1->ne[0];
  5985. const uint64_t ne11 = src1->ne[1];
  5986. const uint64_t ne12 = src1->ne[2];
  5987. const uint64_t ne13 = src1->ne[3];
  5988. const uint64_t nei0 = ids->ne[0];
  5989. const uint64_t nei1 = ids->ne[1];
  5990. const uint64_t nbi2 = ids->nb[2];
  5991. GGML_ASSERT(nei1 == 1);
  5992. const uint64_t ne20 = dst->ne[0];
  5993. const uint64_t ne21 = dst->ne[1];
  5994. const uint64_t ne22 = dst->ne[2];
  5995. const uint64_t ne23 = dst->ne[3];
  5996. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5997. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5998. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5999. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6000. vk_buffer d_Qx = nullptr;
  6001. size_t qx_buf_offset = 0;
  6002. vk_buffer d_Qy = nullptr;
  6003. size_t qy_buf_offset = 0;
  6004. vk_buffer d_ids = nullptr;
  6005. size_t ids_buf_offset = 0;
  6006. bool src0_uma = false;
  6007. bool src1_uma = false;
  6008. bool ids_uma = false;
  6009. if (ctx->device->uma) {
  6010. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6011. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6012. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6013. src0_uma = d_Qx != nullptr;
  6014. src1_uma = d_Qy != nullptr;
  6015. ids_uma = d_ids != nullptr;
  6016. }
  6017. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6018. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6019. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6020. const bool qx_needs_dequant = x_non_contig;
  6021. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  6022. // Not implemented
  6023. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6024. const uint64_t x_ne = ne01 * ne00;
  6025. const uint64_t y_ne = ne11 * ne10;
  6026. const uint64_t d_ne = ne21 * ne20;
  6027. 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);
  6028. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6029. 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;
  6030. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  6031. const uint64_t ids_sz = nbi2;
  6032. const uint64_t d_sz = sizeof(float) * d_ne;
  6033. vk_pipeline to_fp16_vk_0 = nullptr;
  6034. vk_pipeline to_fp16_vk_1 = nullptr;
  6035. if (x_non_contig) {
  6036. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6037. }
  6038. if (y_non_contig) {
  6039. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6040. } else {
  6041. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6042. }
  6043. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type);
  6044. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6045. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6046. GGML_ASSERT(dmmv != nullptr);
  6047. if (dryrun) {
  6048. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  6049. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  6050. if (
  6051. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  6052. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  6053. GGML_ABORT("Requested preallocation size is too large");
  6054. }
  6055. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  6056. ctx->prealloc_size_x = x_sz_upd;
  6057. }
  6058. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  6059. ctx->prealloc_size_y = y_sz_upd;
  6060. }
  6061. // Request descriptor sets
  6062. if (qx_needs_dequant) {
  6063. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6064. }
  6065. if (qy_needs_dequant) {
  6066. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6067. }
  6068. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6069. return;
  6070. }
  6071. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6072. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6073. GGML_ASSERT(d_D != nullptr);
  6074. vk_buffer d_X;
  6075. uint64_t x_buf_offset = 0;
  6076. vk_buffer d_Y;
  6077. uint64_t y_buf_offset = 0;
  6078. if(!src0_uma) {
  6079. d_Qx = src0_buf_ctx->dev_buffer;
  6080. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6081. GGML_ASSERT(d_Qx != nullptr);
  6082. }
  6083. if(!src1_uma) {
  6084. d_Qy = src1_buf_ctx->dev_buffer;
  6085. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6086. GGML_ASSERT(d_Qy != nullptr);
  6087. }
  6088. if(!ids_uma) {
  6089. d_ids = ids_buf_ctx->dev_buffer;
  6090. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6091. GGML_ASSERT(d_ids != nullptr);
  6092. }
  6093. if (qx_needs_dequant) {
  6094. d_X = ctx->prealloc_x;
  6095. } else {
  6096. d_X = d_Qx;
  6097. x_buf_offset = qx_buf_offset;
  6098. GGML_ASSERT(qx_sz == x_sz);
  6099. }
  6100. if (qy_needs_dequant) {
  6101. d_Y = ctx->prealloc_y;
  6102. } else {
  6103. d_Y = d_Qy;
  6104. y_buf_offset = qy_buf_offset;
  6105. GGML_ASSERT(qy_sz == y_sz);
  6106. }
  6107. if (x_non_contig) {
  6108. if (ctx->prealloc_x_need_sync) {
  6109. ggml_vk_sync_buffers(ctx, subctx);
  6110. }
  6111. }
  6112. if (x_non_contig) {
  6113. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6114. 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 });
  6115. }
  6116. if (y_non_contig) {
  6117. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6118. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6119. ctx->prealloc_y_last_tensor_used != src1) {
  6120. if (ctx->prealloc_y_need_sync) {
  6121. ggml_vk_sync_buffers(ctx, subctx);
  6122. }
  6123. 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 });
  6124. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6125. ctx->prealloc_y_last_tensor_used = src1;
  6126. }
  6127. }
  6128. uint32_t stride_batch_y = ne10*ne11;
  6129. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6130. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6131. }
  6132. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6133. uint32_t groups_x = ne01;
  6134. uint32_t groups_z = 1;
  6135. if (ne01 > max_groups_x) {
  6136. groups_z = 64;
  6137. groups_x = CEIL_DIV(groups_x, groups_z);
  6138. }
  6139. // compute
  6140. const vk_mat_vec_id_push_constants pc = {
  6141. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6142. (uint32_t)x_ne, stride_batch_y, (uint32_t)(ne20*ne21),
  6143. (uint32_t)nei0, (uint32_t)ne11,
  6144. };
  6145. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6146. { vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 },
  6147. 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 } },
  6148. pc, { groups_x, (uint32_t)nei0, groups_z });
  6149. if (x_non_contig) {
  6150. ctx->prealloc_x_need_sync = true;
  6151. }
  6152. if (y_non_contig) {
  6153. ctx->prealloc_y_need_sync = true;
  6154. }
  6155. }
  6156. 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) {
  6157. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  6158. if (src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type))) {
  6159. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  6160. } else {
  6161. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  6162. }
  6163. }
  6164. static bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv) {
  6165. // Needs to be kept up to date on shader changes
  6166. GGML_UNUSED(hsv);
  6167. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6168. const uint32_t Br = get_fa_scalar_num_large_rows(hsv);
  6169. const uint32_t Bc = scalar_flash_attention_Bc;
  6170. const uint32_t tmpsh = wg_size * sizeof(float);
  6171. const uint32_t tmpshv4 = wg_size * 4 * sizeof(float);
  6172. const uint32_t masksh = Bc * Br * sizeof(float);
  6173. const uint32_t Qf = Br * (hsk / 4 + 2) * 4 * sizeof(float);
  6174. const uint32_t total_size = tmpsh + tmpshv4 + masksh + Qf;
  6175. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6176. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported);
  6177. return supported;
  6178. }
  6179. static bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool f32acc) {
  6180. // Needs to be kept up to date on shader changes
  6181. GGML_UNUSED(hsv);
  6182. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6183. const uint32_t Br = coopmat1_flash_attention_num_large_rows;
  6184. const uint32_t Bc = scalar_flash_attention_Bc;
  6185. const uint32_t hsk_pad = ROUNDUP_POW2(hsk, 16);
  6186. const uint32_t acctype = f32acc ? 4 : 2;
  6187. const uint32_t f16vec4 = 8;
  6188. const uint32_t tmpsh = wg_size * sizeof(float);
  6189. const uint32_t tmpshv4 = wg_size * 4 * acctype;
  6190. const uint32_t qstride = hsk_pad / 4 + 2;
  6191. const uint32_t Qf = Br * qstride * f16vec4;
  6192. const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br;
  6193. const uint32_t sfsh = Bc * sfshstride * acctype;
  6194. const uint32_t kshstride = hsk_pad / 4 + 2;
  6195. const uint32_t ksh = Bc * kshstride * f16vec4;
  6196. const uint32_t slope = Br * sizeof(float);
  6197. const uint32_t total_size = tmpsh + tmpshv4 + Qf + sfsh + ksh + slope;
  6198. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6199. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported);
  6200. return supported;
  6201. }
  6202. static void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * q, const ggml_tensor * k, const ggml_tensor * v, const ggml_tensor * mask, const ggml_tensor * sinks, ggml_tensor * dst, bool dryrun = false) {
  6203. 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];
  6204. 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];
  6205. 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];
  6206. 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];
  6207. if (sinks) {
  6208. std::cerr << "), (" << sinks << ", name=" << sinks->name << ", type=" << sinks->type << ", ne0=" << sinks->ne[0] << ", ne1=" << sinks->ne[1] << ", ne2=" << sinks->ne[2] << ", ne3=" << sinks->ne[3] << ", nb0=" << sinks->nb[0] << ", nb1=" << sinks->nb[1] << ", nb2=" << sinks->nb[2] << ", nb3=" << sinks->nb[3];
  6209. }
  6210. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  6211. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  6212. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  6213. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  6214. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  6215. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  6216. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  6217. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  6218. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  6219. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  6220. const uint32_t nem2 = mask ? mask->ne[2] : 0;
  6221. const uint32_t nem3 = mask ? mask->ne[3] : 0;
  6222. const uint32_t HSK = nek0;
  6223. const uint32_t HSV = nev0;
  6224. uint32_t N = neq1;
  6225. const uint32_t KV = nek1;
  6226. GGML_ASSERT(ne0 == HSV);
  6227. GGML_ASSERT(ne2 == N);
  6228. // input tensor rows must be contiguous
  6229. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  6230. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  6231. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  6232. GGML_ASSERT(neq0 == HSK);
  6233. GGML_ASSERT(neq1 == N);
  6234. GGML_ASSERT(nev1 == nek1);
  6235. // dst cannot be transposed or permuted
  6236. GGML_ASSERT(nb0 == sizeof(float));
  6237. GGML_ASSERT(nb0 <= nb1);
  6238. GGML_ASSERT(nb1 <= nb2);
  6239. GGML_ASSERT(nb2 <= nb3);
  6240. assert(dst->type == GGML_TYPE_F32);
  6241. assert(q->type == GGML_TYPE_F32);
  6242. assert(k->type == v->type);
  6243. FaCodePath path = ctx->device->coopmat2 ? FA_COOPMAT2 :
  6244. ctx->device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;
  6245. if (path == FA_COOPMAT1) {
  6246. const bool coopmat_shape_supported = (dst->op_params[3] == GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f32acc) ||
  6247. (dst->op_params[3] != GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f16acc);
  6248. const bool coopmat_shmem_supported = ggml_vk_flash_attn_coopmat_shmem_support(ctx->device, HSK, HSV, dst->op_params[3] == GGML_PREC_F32);
  6249. if (!coopmat_shape_supported || !coopmat_shmem_supported) {
  6250. path = FA_SCALAR;
  6251. }
  6252. }
  6253. uint32_t gqa_ratio = 1;
  6254. uint32_t qk_ratio = neq2 / nek2;
  6255. uint32_t workgroups_x = (uint32_t)neq1;
  6256. uint32_t workgroups_y = (uint32_t)neq2;
  6257. uint32_t workgroups_z = (uint32_t)neq3;
  6258. // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga.
  6259. // For coopmat2 FA, we always use the small size (which is still pretty large for gqa).
  6260. uint32_t max_gqa;
  6261. switch (path) {
  6262. case FA_SCALAR:
  6263. case FA_COOPMAT1:
  6264. // We may switch from coopmat1 to scalar, so use the scalar limit for both
  6265. max_gqa = get_fa_scalar_num_large_rows(HSV);
  6266. break;
  6267. case FA_COOPMAT2:
  6268. max_gqa = get_fa_num_small_rows(FA_COOPMAT2);
  6269. break;
  6270. default:
  6271. GGML_ASSERT(0);
  6272. }
  6273. if (N == 1 && qk_ratio > 1 && qk_ratio <= max_gqa &&
  6274. qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) {
  6275. // grouped query attention - make the N dimension equal to gqa_ratio, reduce
  6276. // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1
  6277. // and change addressing calculations to index Q's dimension 2.
  6278. gqa_ratio = qk_ratio;
  6279. N = gqa_ratio;
  6280. workgroups_y /= N;
  6281. }
  6282. bool small_rows = N <= get_fa_num_small_rows(path);
  6283. // coopmat1 does not actually support "small rows" (it needs 16 rows).
  6284. // So use scalar instead.
  6285. if (small_rows && path == FA_COOPMAT1) {
  6286. path = FA_SCALAR;
  6287. }
  6288. // scalar is faster than coopmat2 when N==1
  6289. if (N == 1 && path == FA_COOPMAT2) {
  6290. path = FA_SCALAR;
  6291. }
  6292. // with large hsk/hsv, scalar path may need to use small_rows to fit in shared memory
  6293. if (path == FA_SCALAR &&
  6294. !ggml_vk_flash_attn_scalar_shmem_support(ctx->device, HSK, HSV)) {
  6295. small_rows = true;
  6296. }
  6297. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  6298. const uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  6299. const uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  6300. uint32_t alignment = fa_align(path, HSK, HSV, k->type, small_rows);
  6301. bool aligned = (KV % alignment) == 0 &&
  6302. // the "aligned" shader variant will forcibly align strides, for performance
  6303. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  6304. // Need to use the coopmat2 variant that clamps loads when HSK/HSV aren't sufficiently aligned.
  6305. if (((HSK | HSV) % 16) != 0 && path == FA_COOPMAT2) {
  6306. aligned = false;
  6307. }
  6308. // mask dim1 is padded to 64, we rely on this to avoid clamping mask loads
  6309. GGML_ASSERT((nem1 % GGML_KQ_MASK_PAD) == 0);
  6310. bool f32acc = path == FA_SCALAR || dst->op_params[3] == GGML_PREC_F32;
  6311. vk_fa_pipeline_state fa_pipeline_state(HSK, HSV, small_rows, path, aligned, f32acc);
  6312. vk_pipeline pipeline = nullptr;
  6313. auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16[k->type];
  6314. auto it = pipelines.find(fa_pipeline_state);
  6315. if (it != pipelines.end()) {
  6316. pipeline = it->second;
  6317. } else {
  6318. pipelines[fa_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  6319. }
  6320. assert(pipeline);
  6321. uint32_t split_kv = KV;
  6322. uint32_t split_k = 1;
  6323. // Use a placeholder core count if one isn't available. split_k is a big help for perf.
  6324. const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count : 16;
  6325. // Try to use split_k when KV is large enough to be worth the overhead
  6326. if (workgroups_x == 1 && shader_core_count > 0) {
  6327. // Try to run two workgroups per SM.
  6328. split_k = shader_core_count * 2 / (workgroups_y * workgroups_z);
  6329. if (split_k > 1) {
  6330. // Try to evenly split KV into split_k chunks, but it needs to be a multiple
  6331. // of "align", so recompute split_k based on that.
  6332. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment);
  6333. split_k = CEIL_DIV(KV, split_kv);
  6334. workgroups_x = split_k;
  6335. }
  6336. }
  6337. // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1)
  6338. // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows.
  6339. const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne3 : 0;
  6340. if (split_k_size > ctx->device->max_memory_allocation_size) {
  6341. GGML_ABORT("Requested preallocation size is too large");
  6342. }
  6343. if (ctx->prealloc_size_split_k < split_k_size) {
  6344. ctx->prealloc_size_split_k = split_k_size;
  6345. }
  6346. if (dryrun) {
  6347. // Request descriptor sets
  6348. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6349. if (split_k > 1) {
  6350. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1);
  6351. }
  6352. return;
  6353. }
  6354. float scale = 1.0f;
  6355. float max_bias = 0.0f;
  6356. float logit_softcap = 0.0f;
  6357. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  6358. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  6359. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  6360. if (logit_softcap != 0) {
  6361. scale /= logit_softcap;
  6362. }
  6363. const uint32_t n_head_kv = neq2;
  6364. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  6365. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  6366. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  6367. vk_buffer d_Q = nullptr, d_K = nullptr, d_V = nullptr, d_D = nullptr, d_M = nullptr, d_S = nullptr;
  6368. size_t q_buf_offset = 0, k_buf_offset = 0, v_buf_offset = 0, d_buf_offset = 0, m_buf_offset = 0, s_buf_offset = 0;
  6369. bool Q_uma = false, K_uma = false, V_uma = false, D_uma = false, M_uma = false, S_uma = false;
  6370. if (ctx->device->uma) {
  6371. ggml_vk_host_get(ctx->device, q->data, d_Q, q_buf_offset);
  6372. ggml_vk_host_get(ctx->device, k->data, d_K, k_buf_offset);
  6373. ggml_vk_host_get(ctx->device, v->data, d_V, v_buf_offset);
  6374. ggml_vk_host_get(ctx->device, dst->data, d_D, d_buf_offset);
  6375. Q_uma = d_Q != nullptr;
  6376. K_uma = d_K != nullptr;
  6377. V_uma = d_V != nullptr;
  6378. D_uma = d_D != nullptr;
  6379. if (mask) {
  6380. ggml_vk_host_get(ctx->device, mask->data, d_M, m_buf_offset);
  6381. M_uma = d_M != nullptr;
  6382. }
  6383. if (sinks) {
  6384. ggml_vk_host_get(ctx->device, sinks->data, d_S, s_buf_offset);
  6385. S_uma = d_S != nullptr;
  6386. }
  6387. }
  6388. ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6389. ggml_backend_vk_buffer_context * q_buf_ctx = (ggml_backend_vk_buffer_context *)q->buffer->context;
  6390. ggml_backend_vk_buffer_context * k_buf_ctx = (ggml_backend_vk_buffer_context *)k->buffer->context;
  6391. ggml_backend_vk_buffer_context * v_buf_ctx = (ggml_backend_vk_buffer_context *)v->buffer->context;
  6392. if (!Q_uma) {
  6393. d_Q = q_buf_ctx->dev_buffer;
  6394. q_buf_offset = vk_tensor_offset(q) + q->view_offs;
  6395. }
  6396. if (!K_uma) {
  6397. d_K = k_buf_ctx->dev_buffer;
  6398. k_buf_offset = vk_tensor_offset(k) + k->view_offs;
  6399. }
  6400. if (!V_uma) {
  6401. d_V = v_buf_ctx->dev_buffer;
  6402. v_buf_offset = vk_tensor_offset(v) + v->view_offs;
  6403. }
  6404. if (!D_uma) {
  6405. d_D = d_buf_ctx->dev_buffer;
  6406. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6407. }
  6408. if (!M_uma) {
  6409. d_M = d_Q;
  6410. m_buf_offset = q_buf_offset;
  6411. if (mask) {
  6412. ggml_backend_vk_buffer_context * m_buf_ctx = (ggml_backend_vk_buffer_context*)mask->buffer->context;
  6413. d_M = m_buf_ctx->dev_buffer;
  6414. m_buf_offset = vk_tensor_offset(mask) + mask->view_offs;
  6415. }
  6416. }
  6417. if (!S_uma) {
  6418. d_S = d_Q;
  6419. s_buf_offset = q_buf_offset;
  6420. if (sinks) {
  6421. ggml_backend_vk_buffer_context * s_buf_ctx = (ggml_backend_vk_buffer_context*)sinks->buffer->context;
  6422. d_S = s_buf_ctx->dev_buffer;
  6423. s_buf_offset = vk_tensor_offset(sinks) + sinks->view_offs;
  6424. }
  6425. }
  6426. uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | ((mask != nullptr) << 16) | n_head_log2;
  6427. const vk_flash_attn_push_constants pc = { N, KV,
  6428. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  6429. (uint32_t)neq2, (uint32_t)neq3,
  6430. (uint32_t)nek2, (uint32_t)nek3,
  6431. (uint32_t)nev2, (uint32_t)nev3,
  6432. nem1, nem2, nem3,
  6433. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  6434. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  6435. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  6436. scale, max_bias, logit_softcap,
  6437. mask_n_head_log2, m0, m1,
  6438. gqa_ratio, split_kv, split_k };
  6439. if (split_k > 1) {
  6440. if (ctx->prealloc_split_k_need_sync) {
  6441. ggml_vk_sync_buffers(ctx, subctx);
  6442. }
  6443. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6444. {
  6445. vk_subbuffer{d_Q, q_buf_offset, VK_WHOLE_SIZE},
  6446. vk_subbuffer{d_K, k_buf_offset, VK_WHOLE_SIZE},
  6447. vk_subbuffer{d_V, v_buf_offset, VK_WHOLE_SIZE},
  6448. vk_subbuffer{d_M, m_buf_offset, VK_WHOLE_SIZE},
  6449. vk_subbuffer{d_S, s_buf_offset, VK_WHOLE_SIZE},
  6450. vk_subbuffer{ctx->prealloc_split_k, 0, VK_WHOLE_SIZE},
  6451. },
  6452. // We only use split_k when group query attention is enabled, which means
  6453. // there's no more than one tile of rows (i.e. workgroups_x would have been
  6454. // one). We reuse workgroups_x to mean the number of splits, so we need to
  6455. // cancel out the divide by wg_denoms[0].
  6456. pc, { workgroups_x * pipeline->wg_denoms[0], workgroups_y, workgroups_z });
  6457. ggml_vk_sync_buffers(ctx, subctx);
  6458. const std::array<uint32_t, 5> pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne3, split_k, (sinks != nullptr) };
  6459. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce,
  6460. {
  6461. vk_subbuffer{ctx->prealloc_split_k, 0, VK_WHOLE_SIZE},
  6462. vk_subbuffer{d_S, s_buf_offset, VK_WHOLE_SIZE},
  6463. vk_subbuffer{d_D, d_buf_offset, VK_WHOLE_SIZE},
  6464. },
  6465. pc2, { (uint32_t)ne1, HSV, (uint32_t)ne3 });
  6466. ctx->prealloc_split_k_need_sync = true;
  6467. } else {
  6468. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6469. {
  6470. vk_subbuffer{d_Q, q_buf_offset, VK_WHOLE_SIZE},
  6471. vk_subbuffer{d_K, k_buf_offset, VK_WHOLE_SIZE},
  6472. vk_subbuffer{d_V, v_buf_offset, VK_WHOLE_SIZE},
  6473. vk_subbuffer{d_M, m_buf_offset, VK_WHOLE_SIZE},
  6474. vk_subbuffer{d_S, s_buf_offset, VK_WHOLE_SIZE},
  6475. vk_subbuffer{d_D, d_buf_offset, VK_WHOLE_SIZE},
  6476. },
  6477. pc, { workgroups_x, workgroups_y, workgroups_z });
  6478. }
  6479. }
  6480. static std::array<uint32_t, 3> ggml_vk_get_conv_elements(const ggml_tensor *dst) {
  6481. const ggml_tensor *src0 = dst->src[0];
  6482. const ggml_tensor *src1 = dst->src[1];
  6483. // src0 - kernel: [KW, KH, Cin, Cout]
  6484. // src1 - input: [W, H, Cin, N]
  6485. // dst - result: [OW, OH, Cout, N]
  6486. // Copied from ggml.c: int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d)
  6487. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6488. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  6489. };
  6490. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6491. int64_t W = src1->ne[0];
  6492. int64_t H = src1->ne[1];
  6493. int64_t KW = src0->ne[0];
  6494. int64_t KH = src0->ne[1];
  6495. int64_t Cout = src0->ne[3];
  6496. int64_t N = src1->ne[3];
  6497. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[1], dst->op_params[3], dst->op_params[5]);
  6498. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], dst->op_params[2], dst->op_params[4]);
  6499. int64_t NPQ = N * OW * OH;
  6500. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6501. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6502. return elements;
  6503. }
  6504. static std::array<uint32_t, 3> ggml_vk_get_conv_transpose_2d_elements(const ggml_tensor *dst) {
  6505. const ggml_tensor *src0 = dst->src[0];
  6506. const ggml_tensor *src1 = dst->src[1];
  6507. // src0 - kernel: [KW, KH, Cout, Cin]
  6508. // src1 - input: [W, H, Cin, N]
  6509. // dst - result: [OW, OH, Cout, N]
  6510. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6511. return (ins - 1) * s - 2 * p + (ks - 1) * d + 1;
  6512. };
  6513. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6514. int64_t W = src1->ne[0];
  6515. int64_t H = src1->ne[1];
  6516. int64_t KW = src0->ne[0];
  6517. int64_t KH = src0->ne[1];
  6518. int64_t Cout = src0->ne[2];
  6519. int64_t N = src1->ne[3];
  6520. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[0], 0, 1);
  6521. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], 0, 1);
  6522. int64_t NPQ = N * OW * OH;
  6523. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6524. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6525. return elements;
  6526. }
  6527. static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * dst, ggml_op op) {
  6528. switch (op) {
  6529. case GGML_OP_GET_ROWS:
  6530. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  6531. if (dst->type == GGML_TYPE_F16) {
  6532. return ctx->device->pipeline_get_rows[src0->type];
  6533. }
  6534. if (dst->type == GGML_TYPE_F32) {
  6535. return ctx->device->pipeline_get_rows_f32[src0->type];
  6536. }
  6537. return nullptr;
  6538. case GGML_OP_ACC:
  6539. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6540. return ctx->device->pipeline_acc_f32;
  6541. }
  6542. return nullptr;
  6543. case GGML_OP_ADD:
  6544. case GGML_OP_SUB:
  6545. case GGML_OP_MUL:
  6546. case GGML_OP_DIV:
  6547. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  6548. (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
  6549. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
  6550. return nullptr;
  6551. }
  6552. switch (op) {
  6553. case GGML_OP_ADD:
  6554. {
  6555. if (ctx->num_additional_fused_ops > 0) {
  6556. if (ctx->do_add_rms_partials) {
  6557. return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops];
  6558. } else {
  6559. return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  6560. }
  6561. }
  6562. if (ctx->do_add_rms_partials) {
  6563. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_rms_norepeat : ctx->device->pipeline_add_rms;
  6564. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6565. } else {
  6566. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add;
  6567. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6568. }
  6569. }
  6570. case GGML_OP_SUB:
  6571. {
  6572. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub;
  6573. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6574. }
  6575. case GGML_OP_MUL:
  6576. {
  6577. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul;
  6578. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6579. }
  6580. case GGML_OP_DIV:
  6581. {
  6582. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div;
  6583. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6584. }
  6585. default:
  6586. break;
  6587. }
  6588. return nullptr;
  6589. case GGML_OP_ADD_ID:
  6590. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) {
  6591. return ctx->device->pipeline_add_id_f32;
  6592. }
  6593. return nullptr;
  6594. case GGML_OP_CONCAT:
  6595. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6596. return ctx->device->pipeline_concat_f32;
  6597. }
  6598. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6599. return ctx->device->pipeline_concat_f16;
  6600. }
  6601. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  6602. return ctx->device->pipeline_concat_i32;
  6603. }
  6604. return nullptr;
  6605. case GGML_OP_UPSCALE:
  6606. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6607. int mode = ggml_get_op_params_i32(dst, 0);
  6608. switch (mode) {
  6609. case GGML_SCALE_MODE_NEAREST:
  6610. return ctx->device->pipeline_upscale_nearest_f32;
  6611. case GGML_SCALE_MODE_BILINEAR:
  6612. return ctx->device->pipeline_upscale_bilinear_f32;
  6613. case GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ALIGN_CORNERS:
  6614. return ctx->device->pipeline_upscale_bilinear_ac_f32;
  6615. }
  6616. }
  6617. return nullptr;
  6618. case GGML_OP_SCALE:
  6619. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6620. return ctx->device->pipeline_scale_f32;
  6621. }
  6622. return nullptr;
  6623. case GGML_OP_SQR:
  6624. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6625. return ctx->device->pipeline_sqr_f32;
  6626. }
  6627. return nullptr;
  6628. case GGML_OP_SQRT:
  6629. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6630. return ctx->device->pipeline_sqrt_f32;
  6631. }
  6632. return nullptr;
  6633. case GGML_OP_SIN:
  6634. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6635. return ctx->device->pipeline_sin_f32;
  6636. }
  6637. return nullptr;
  6638. case GGML_OP_COS:
  6639. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6640. return ctx->device->pipeline_cos_f32;
  6641. }
  6642. return nullptr;
  6643. case GGML_OP_CLAMP:
  6644. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6645. return ctx->device->pipeline_clamp_f32;
  6646. }
  6647. return nullptr;
  6648. case GGML_OP_PAD:
  6649. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6650. return ctx->device->pipeline_pad_f32;
  6651. }
  6652. return nullptr;
  6653. case GGML_OP_ROLL:
  6654. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6655. return ctx->device->pipeline_roll_f32;
  6656. }
  6657. return nullptr;
  6658. case GGML_OP_REPEAT:
  6659. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  6660. return ctx->device->pipeline_repeat_f32;
  6661. }
  6662. return nullptr;
  6663. case GGML_OP_REPEAT_BACK:
  6664. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6665. return ctx->device->pipeline_repeat_back_f32;
  6666. }
  6667. return nullptr;
  6668. case GGML_OP_CPY:
  6669. case GGML_OP_CONT:
  6670. case GGML_OP_DUP:
  6671. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  6672. case GGML_OP_SET_ROWS:
  6673. if (src1->type == GGML_TYPE_I64) {
  6674. return ctx->device->pipeline_set_rows_i64[dst->type];
  6675. } else {
  6676. return ctx->device->pipeline_set_rows_i32[dst->type];
  6677. }
  6678. case GGML_OP_SILU_BACK:
  6679. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6680. return ctx->device->pipeline_silu_back_f32;
  6681. }
  6682. return nullptr;
  6683. case GGML_OP_NORM:
  6684. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6685. return ctx->device->pipeline_norm_f32;
  6686. }
  6687. return nullptr;
  6688. case GGML_OP_GROUP_NORM:
  6689. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6690. return ctx->device->pipeline_group_norm_f32;
  6691. }
  6692. return nullptr;
  6693. case GGML_OP_RMS_NORM:
  6694. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6695. if (ctx->do_add_rms_partials) {
  6696. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32;
  6697. } else {
  6698. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32;
  6699. }
  6700. }
  6701. return nullptr;
  6702. case GGML_OP_RMS_NORM_BACK:
  6703. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6704. return ctx->device->pipeline_rms_norm_back_f32;
  6705. }
  6706. return nullptr;
  6707. case GGML_OP_L2_NORM:
  6708. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6709. return ctx->device->pipeline_l2_norm_f32;
  6710. }
  6711. return nullptr;
  6712. case GGML_OP_UNARY:
  6713. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  6714. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  6715. (src0->type != dst->type)) {
  6716. return nullptr;
  6717. }
  6718. switch (ggml_get_unary_op(dst)) {
  6719. case GGML_UNARY_OP_EXP:
  6720. return ctx->device->pipeline_exp[dst->type == GGML_TYPE_F16];
  6721. case GGML_UNARY_OP_SILU:
  6722. return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16];
  6723. case GGML_UNARY_OP_GELU:
  6724. return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16];
  6725. case GGML_UNARY_OP_GELU_ERF:
  6726. return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16];
  6727. case GGML_UNARY_OP_GELU_QUICK:
  6728. return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16];
  6729. case GGML_UNARY_OP_RELU:
  6730. return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16];
  6731. case GGML_UNARY_OP_TANH:
  6732. return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16];
  6733. case GGML_UNARY_OP_SIGMOID:
  6734. return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16];
  6735. case GGML_UNARY_OP_HARDSIGMOID:
  6736. return ctx->device->pipeline_hardsigmoid[dst->type == GGML_TYPE_F16];
  6737. case GGML_UNARY_OP_HARDSWISH:
  6738. return ctx->device->pipeline_hardswish[dst->type == GGML_TYPE_F16];
  6739. default:
  6740. break;
  6741. }
  6742. return nullptr;
  6743. case GGML_OP_GLU:
  6744. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  6745. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  6746. (src0->type != dst->type)) {
  6747. return nullptr;
  6748. }
  6749. switch (ggml_get_glu_op(dst)) {
  6750. case GGML_GLU_OP_GEGLU:
  6751. return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16];
  6752. case GGML_GLU_OP_REGLU:
  6753. return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16];
  6754. case GGML_GLU_OP_SWIGLU:
  6755. return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16];
  6756. case GGML_GLU_OP_SWIGLU_OAI:
  6757. return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16];
  6758. case GGML_GLU_OP_GEGLU_ERF:
  6759. return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16];
  6760. case GGML_GLU_OP_GEGLU_QUICK:
  6761. return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16];
  6762. default:
  6763. break;
  6764. }
  6765. return nullptr;
  6766. case GGML_OP_DIAG_MASK_INF:
  6767. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6768. return ctx->device->pipeline_diag_mask_inf_f32;
  6769. }
  6770. return nullptr;
  6771. case GGML_OP_SOFT_MAX:
  6772. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  6773. GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32);
  6774. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  6775. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  6776. }
  6777. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  6778. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  6779. }
  6780. return nullptr;
  6781. case GGML_OP_SOFT_MAX_BACK:
  6782. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6783. return ctx->device->pipeline_soft_max_back_f32;
  6784. }
  6785. return nullptr;
  6786. case GGML_OP_ROPE:
  6787. case GGML_OP_ROPE_BACK:
  6788. {
  6789. const int mode = ((const int32_t *) dst->op_params)[2];
  6790. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  6791. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  6792. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  6793. if (is_neox) {
  6794. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6795. return ctx->device->pipeline_rope_neox_f32;
  6796. }
  6797. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6798. return ctx->device->pipeline_rope_neox_f16;
  6799. }
  6800. } else if (is_mrope && !is_vision) {
  6801. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6802. return ctx->device->pipeline_rope_multi_f32;
  6803. }
  6804. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6805. return ctx->device->pipeline_rope_multi_f16;
  6806. }
  6807. } else if (is_vision) {
  6808. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6809. return ctx->device->pipeline_rope_vision_f32;
  6810. }
  6811. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6812. return ctx->device->pipeline_rope_vision_f16;
  6813. }
  6814. } else {
  6815. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6816. return ctx->device->pipeline_rope_norm_f32;
  6817. }
  6818. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6819. return ctx->device->pipeline_rope_norm_f16;
  6820. }
  6821. }
  6822. return nullptr;
  6823. }
  6824. case GGML_OP_ARGSORT:
  6825. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  6826. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  6827. return ctx->device->pipeline_argsort_f32[idx];
  6828. }
  6829. return nullptr;
  6830. case GGML_OP_SUM:
  6831. case GGML_OP_SUM_ROWS:
  6832. case GGML_OP_MEAN:
  6833. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6834. return ctx->device->pipeline_sum_rows_f32;
  6835. }
  6836. return nullptr;
  6837. case GGML_OP_ARGMAX:
  6838. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  6839. return ctx->device->pipeline_argmax_f32;
  6840. }
  6841. return nullptr;
  6842. case GGML_OP_COUNT_EQUAL:
  6843. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) {
  6844. return ctx->device->pipeline_count_equal_i32;
  6845. }
  6846. return nullptr;
  6847. case GGML_OP_IM2COL:
  6848. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6849. return ctx->device->pipeline_im2col_f32;
  6850. }
  6851. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  6852. return ctx->device->pipeline_im2col_f32_f16;
  6853. }
  6854. return nullptr;
  6855. case GGML_OP_IM2COL_3D:
  6856. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6857. return ctx->device->pipeline_im2col_3d_f32;
  6858. }
  6859. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  6860. return ctx->device->pipeline_im2col_3d_f32_f16;
  6861. }
  6862. return nullptr;
  6863. case GGML_OP_TIMESTEP_EMBEDDING:
  6864. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6865. return ctx->device->pipeline_timestep_embedding_f32;
  6866. }
  6867. return nullptr;
  6868. case GGML_OP_CONV_TRANSPOSE_1D:
  6869. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6870. return ctx->device->pipeline_conv_transpose_1d_f32;
  6871. }
  6872. return nullptr;
  6873. case GGML_OP_POOL_2D:
  6874. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6875. return ctx->device->pipeline_pool2d_f32;
  6876. }
  6877. return nullptr;
  6878. case GGML_OP_RWKV_WKV6:
  6879. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6880. return ctx->device->pipeline_rwkv_wkv6_f32;
  6881. }
  6882. return nullptr;
  6883. case GGML_OP_RWKV_WKV7:
  6884. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6885. return ctx->device->pipeline_rwkv_wkv7_f32;
  6886. }
  6887. return nullptr;
  6888. case GGML_OP_OPT_STEP_ADAMW:
  6889. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6890. return ctx->device->pipeline_opt_step_adamw_f32;
  6891. }
  6892. return nullptr;
  6893. case GGML_OP_OPT_STEP_SGD:
  6894. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6895. return ctx->device->pipeline_opt_step_sgd_f32;
  6896. }
  6897. return nullptr;
  6898. case GGML_OP_LEAKY_RELU:
  6899. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6900. return ctx->device->pipeline_leaky_relu_f32;
  6901. }
  6902. return nullptr;
  6903. case GGML_OP_CONV_2D:
  6904. case GGML_OP_CONV_TRANSPOSE_2D:
  6905. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 &&
  6906. ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst)) {
  6907. std::array<uint32_t, 3> elements;
  6908. if (op == GGML_OP_CONV_2D) elements = ggml_vk_get_conv_elements(dst);
  6909. else if (op == GGML_OP_CONV_TRANSPOSE_2D) elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  6910. vk_conv_shapes shape;
  6911. uint32_t tiles[CONV_SHAPE_COUNT];
  6912. for (uint32_t i = 0; i < CONV_SHAPE_COUNT; ++i) {
  6913. tiles[i] = CEIL_DIV(elements[0], ctx->device->pipeline_conv2d_f32[i]->wg_denoms[0]) * CEIL_DIV(elements[1], ctx->device->pipeline_conv2d_f32[i]->wg_denoms[1]);
  6914. }
  6915. // We can't query number of shader cores on Intel, use 32 as a placeholder
  6916. // so small convolutions will still choose a smaller tile.
  6917. const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32;
  6918. if (elements[0] > 64 && tiles[CONV_SHAPE_128x128] >= shader_core_count * 2) {
  6919. shape = CONV_SHAPE_128x128;
  6920. } else if (elements[0] <= 32 && tiles[CONV_SHAPE_32x256] >= shader_core_count * 2) {
  6921. shape = CONV_SHAPE_32x256;
  6922. } else {
  6923. shape = CONV_SHAPE_64x32;
  6924. }
  6925. if (op == GGML_OP_CONV_2D) {
  6926. if (src0->type == GGML_TYPE_F32) {
  6927. return ctx->device->pipeline_conv2d_f32[shape];
  6928. } else if (src0->type == GGML_TYPE_F16) {
  6929. return ctx->device->pipeline_conv2d_f16_f32[shape];
  6930. }
  6931. } else if (op == GGML_OP_CONV_TRANSPOSE_2D) {
  6932. if (src0->type == GGML_TYPE_F32) {
  6933. return ctx->device->pipeline_conv_transpose_2d_f32[shape];
  6934. } else if (src0->type == GGML_TYPE_F16) {
  6935. return ctx->device->pipeline_conv_transpose_2d_f16_f32[shape];
  6936. }
  6937. }
  6938. }
  6939. return nullptr;
  6940. case GGML_OP_CONV_2D_DW:
  6941. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6942. if (ggml_is_contiguous(src1)) {
  6943. return ctx->device->pipeline_conv2d_dw_whcn_f32;
  6944. } else if (ggml_is_contiguous_channels(src1)) {
  6945. return ctx->device->pipeline_conv2d_dw_cwhn_f32;
  6946. }
  6947. } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  6948. if (ggml_is_contiguous(src1)) {
  6949. return ctx->device->pipeline_conv2d_dw_whcn_f16_f32;
  6950. } else if (ggml_is_contiguous_channels(src1)) {
  6951. return ctx->device->pipeline_conv2d_dw_cwhn_f16_f32;
  6952. }
  6953. }
  6954. return nullptr;
  6955. default:
  6956. return nullptr;
  6957. }
  6958. GGML_UNUSED(src2);
  6959. }
  6960. static bool ggml_vk_op_supports_incontiguous(ggml_op op) {
  6961. switch (op) {
  6962. case GGML_OP_CPY:
  6963. case GGML_OP_GET_ROWS:
  6964. case GGML_OP_ADD:
  6965. case GGML_OP_SUB:
  6966. case GGML_OP_MUL:
  6967. case GGML_OP_DIV:
  6968. case GGML_OP_ADD_ID:
  6969. case GGML_OP_CONCAT:
  6970. case GGML_OP_UPSCALE:
  6971. case GGML_OP_SQR:
  6972. case GGML_OP_SQRT:
  6973. case GGML_OP_SIN:
  6974. case GGML_OP_COS:
  6975. case GGML_OP_CLAMP:
  6976. case GGML_OP_PAD:
  6977. case GGML_OP_REPEAT:
  6978. case GGML_OP_REPEAT_BACK:
  6979. case GGML_OP_ROPE:
  6980. case GGML_OP_RMS_NORM:
  6981. case GGML_OP_CONV_2D_DW:
  6982. case GGML_OP_IM2COL:
  6983. case GGML_OP_IM2COL_3D:
  6984. case GGML_OP_SET_ROWS:
  6985. case GGML_OP_SUM:
  6986. case GGML_OP_SUM_ROWS:
  6987. case GGML_OP_MEAN:
  6988. return true;
  6989. default:
  6990. return false;
  6991. }
  6992. }
  6993. static uint32_t get_misalign_bytes(ggml_backend_vk_context * ctx, const ggml_tensor * t)
  6994. {
  6995. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  6996. }
  6997. 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) {
  6998. GGML_UNUSED(p);
  6999. GGML_UNUSED(src0);
  7000. GGML_UNUSED(src1);
  7001. GGML_UNUSED(src2);
  7002. GGML_UNUSED(dst);
  7003. static_assert(!std::is_const<T>::value, "unexpected type");
  7004. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  7005. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  7006. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  7007. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  7008. }
  7009. 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) {
  7010. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7011. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7012. p.misalign_offsets = (a_offset << 16) | d_offset;
  7013. GGML_UNUSED(src1);
  7014. GGML_UNUSED(src2);
  7015. }
  7016. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_sum_rows_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  7017. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7018. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7019. p.misalign_offsets = (a_offset << 16) | d_offset;
  7020. GGML_UNUSED(src1);
  7021. GGML_UNUSED(src2);
  7022. }
  7023. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_pad_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  7024. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7025. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7026. p.misalign_offsets = (a_offset << 16) | d_offset;
  7027. GGML_UNUSED(src1);
  7028. GGML_UNUSED(src2);
  7029. }
  7030. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_im2col_3d_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst) {
  7031. const uint32_t a_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7032. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7033. p.misalign_offsets = (a_offset << 16) | d_offset;
  7034. GGML_UNUSED(src0);
  7035. GGML_UNUSED(src2);
  7036. }
  7037. 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) {
  7038. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7039. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7040. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7041. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  7042. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  7043. GGML_UNUSED(src2);
  7044. }
  7045. 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) {
  7046. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7047. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7048. p.a_offset = a_offset;
  7049. p.d_offset = d_offset;
  7050. GGML_UNUSED(src1);
  7051. GGML_UNUSED(src2);
  7052. }
  7053. template<typename PC>
  7054. 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) {
  7055. 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];
  7056. if (src1 != nullptr) {
  7057. 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];
  7058. }
  7059. if (src2 != nullptr) {
  7060. 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];
  7061. }
  7062. 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];
  7063. std::cerr << "), " << ggml_op_name(op) << ", " << (dryrun ? "dryrun" : "") << ")");
  7064. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  7065. GGML_ASSERT(ggml_vk_op_supports_incontiguous(op) || ggml_vk_dim01_contiguous(src0)); // NOLINT
  7066. GGML_ASSERT(dst->buffer != nullptr);
  7067. const uint64_t ne00 = src0->ne[0];
  7068. const uint64_t ne01 = src0->ne[1];
  7069. const uint64_t ne02 = src0->ne[2];
  7070. const uint64_t ne03 = src0->ne[3];
  7071. const uint64_t ne0 = ne00 * ne01;
  7072. const bool use_src1 = src1 != nullptr;
  7073. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  7074. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  7075. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  7076. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  7077. const uint64_t ne1 = ne10 * ne11;
  7078. // const uint64_t nb10 = use_src1 ? src1->nb[0] : 0;
  7079. const bool use_src2 = src2 != nullptr;
  7080. const uint64_t ne20 = use_src2 ? src2->ne[0] : 0;
  7081. const uint64_t ne21 = use_src2 ? src2->ne[1] : 0;
  7082. const uint64_t ne22 = use_src2 ? src2->ne[2] : 0;
  7083. const uint64_t ne23 = use_src2 ? src2->ne[3] : 0;
  7084. const uint64_t ne2 = ne20 * ne21;
  7085. const uint64_t ned0 = dst->ne[0];
  7086. const uint64_t ned1 = dst->ne[1];
  7087. const uint64_t ned2 = dst->ne[2];
  7088. const uint64_t ned3 = dst->ne[3];
  7089. const uint64_t ned = ned0 * ned1;
  7090. init_pushconst_fastdiv(pc);
  7091. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  7092. if (pipeline == nullptr) {
  7093. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  7094. if (src1 != nullptr) {
  7095. std::cerr << " and " << ggml_type_name(src1->type);
  7096. }
  7097. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  7098. GGML_ABORT("fatal error");
  7099. }
  7100. if (dryrun) {
  7101. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7102. return;
  7103. }
  7104. const bool op_supports_incontiguous = ggml_vk_op_supports_incontiguous(op);
  7105. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  7106. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  7107. ggml_backend_vk_buffer_context * src1_buf_ctx = use_src1 ? (ggml_backend_vk_buffer_context *)src1->buffer->context : nullptr;
  7108. ggml_backend_vk_buffer_context * src2_buf_ctx = use_src2 ? (ggml_backend_vk_buffer_context *)src2->buffer->context : nullptr;
  7109. vk_buffer d_X = nullptr;
  7110. size_t x_buf_offset = 0;
  7111. vk_buffer d_Y = nullptr;
  7112. size_t y_buf_offset = 0;
  7113. vk_buffer d_Z = nullptr;
  7114. size_t z_buf_offset = 0;
  7115. bool src0_uma = false;
  7116. bool src1_uma = false;
  7117. bool src2_uma = false;
  7118. if (ctx->device->uma) {
  7119. ggml_vk_host_get(ctx->device, src0->data, d_X, x_buf_offset);
  7120. src0_uma = d_X != nullptr;
  7121. if (use_src1) {
  7122. ggml_vk_host_get(ctx->device, src1->data, d_Y, y_buf_offset);
  7123. src1_uma = d_Y != nullptr;
  7124. }
  7125. if (use_src2) {
  7126. ggml_vk_host_get(ctx->device, src2->data, d_Z, z_buf_offset);
  7127. src2_uma = d_Z != nullptr;
  7128. }
  7129. }
  7130. uint64_t x_sz = ggml_type_size(src0->type)/ggml_blck_size(src0->type) * ne0;
  7131. uint64_t y_sz = use_src1 ? ggml_type_size(src1->type) * ne1 : 0;
  7132. uint64_t z_sz = use_src2 ? ggml_type_size(src2->type) * ne2 : 0;
  7133. uint64_t d_sz = ggml_type_size(dst->type) * ned;
  7134. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  7135. // Workaround for tiny tensor inputs on ROPE
  7136. if (op == GGML_OP_ROPE && use_src1 && y_sz > d_D->size) {
  7137. y_sz = VK_WHOLE_SIZE;
  7138. }
  7139. GGML_ASSERT(d_D != nullptr);
  7140. uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  7141. if(!src0_uma) {
  7142. d_X = src0_buf_ctx->dev_buffer;
  7143. x_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  7144. GGML_ASSERT(d_X != nullptr);
  7145. }
  7146. if (use_src1 && !src1_uma) {
  7147. d_Y = src1_buf_ctx->dev_buffer;
  7148. y_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  7149. GGML_ASSERT(d_Y != nullptr);
  7150. }
  7151. if (use_src2 && !src2_uma) {
  7152. d_Z = src2_buf_ctx->dev_buffer;
  7153. z_buf_offset = vk_tensor_offset(src2) + src2->view_offs;
  7154. GGML_ASSERT(d_Z != nullptr);
  7155. }
  7156. // Compute misalignment offset for descriptors and store it in in push constants, then align the descriptor offsets.
  7157. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, dst);
  7158. x_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7159. y_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7160. z_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7161. d_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7162. if (op_supports_incontiguous) {
  7163. x_sz = ggml_nbytes(src0) + get_misalign_bytes(ctx, src0);
  7164. y_sz = use_src1 ? ggml_nbytes(src1) + get_misalign_bytes(ctx, src1) : 0;
  7165. z_sz = use_src2 ? ggml_nbytes(src2) + get_misalign_bytes(ctx, src2) : 0;
  7166. d_sz = ggml_nbytes(dst) + get_misalign_bytes(ctx, dst);
  7167. if (x_buf_offset + x_sz >= d_X->size) {
  7168. x_sz = VK_WHOLE_SIZE;
  7169. }
  7170. if (use_src1 && y_buf_offset + y_sz >= d_Y->size) {
  7171. y_sz = VK_WHOLE_SIZE;
  7172. }
  7173. if (use_src2 && z_buf_offset + z_sz >= d_Z->size) {
  7174. z_sz = VK_WHOLE_SIZE;
  7175. }
  7176. if (d_buf_offset + d_sz >= d_D->size) {
  7177. d_sz = VK_WHOLE_SIZE;
  7178. }
  7179. }
  7180. std::array<uint32_t, 3> elements;
  7181. // Single call if dimension 2 is contiguous
  7182. GGML_ASSERT(op_supports_incontiguous || (ggml_is_contiguous(src0) && (src1 == nullptr || ggml_is_contiguous(src1))));
  7183. switch (op) {
  7184. case GGML_OP_NORM:
  7185. case GGML_OP_RMS_NORM_BACK:
  7186. case GGML_OP_L2_NORM:
  7187. case GGML_OP_SOFT_MAX:
  7188. case GGML_OP_SOFT_MAX_BACK:
  7189. case GGML_OP_SUM_ROWS:
  7190. case GGML_OP_MEAN:
  7191. case GGML_OP_ARGMAX:
  7192. {
  7193. const uint32_t nr = ggml_nrows(src0);
  7194. if (nr > 262144) {
  7195. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7196. } else if (nr > 512) {
  7197. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7198. } else {
  7199. elements = { nr, 1, 1 };
  7200. }
  7201. } break;
  7202. case GGML_OP_RMS_NORM:
  7203. if (ctx->do_add_rms_partials) {
  7204. // Run one element per thread, 128 threads per workgroup
  7205. elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 };
  7206. } else {
  7207. elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 };
  7208. }
  7209. break;
  7210. case GGML_OP_SUM:
  7211. // We use GGML_OP_SUM_ROWS with 1 row.
  7212. elements = { 1, 1, 1 };
  7213. break;
  7214. case GGML_OP_GROUP_NORM:
  7215. {
  7216. const uint32_t num_groups = dst->op_params[0];
  7217. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  7218. } break;
  7219. case GGML_OP_DIAG_MASK_INF:
  7220. case GGML_OP_ROPE:
  7221. case GGML_OP_ROPE_BACK:
  7222. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  7223. break;
  7224. case GGML_OP_GET_ROWS:
  7225. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  7226. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7227. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7228. break;
  7229. case GGML_OP_ARGSORT:
  7230. elements = { (uint32_t)ne00, (uint32_t)ggml_nrows(src0), 1 };
  7231. break;
  7232. case GGML_OP_IM2COL:
  7233. {
  7234. const bool is_2D = dst->op_params[6] == 1;
  7235. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  7236. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  7237. const uint32_t KW = src0->ne[0];
  7238. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  7239. const uint32_t OW = dst->ne[1];
  7240. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  7241. elements = { OW * KW * KH, OH, batch * IC };
  7242. } break;
  7243. case GGML_OP_IM2COL_3D:
  7244. {
  7245. const uint32_t IC = ((const uint32_t *)(dst->op_params))[9];
  7246. const uint32_t N = ne13 / IC;
  7247. const uint32_t KD = ne02;
  7248. const uint32_t KH = ne01;
  7249. const uint32_t KW = ne00;
  7250. const uint32_t OD = ned3 / N;
  7251. const uint32_t OH = ned2;
  7252. const uint32_t OW = ned1;
  7253. const uint32_t IC_KD_KH_KW = IC*KD*KH*KW;
  7254. const uint32_t N_OD_OH = N*OD*OH;
  7255. elements = { IC_KD_KH_KW, OW, N_OD_OH };
  7256. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7257. } break;
  7258. case GGML_OP_TIMESTEP_EMBEDDING:
  7259. {
  7260. const uint32_t dim = dst->op_params[0];
  7261. uint32_t half_ceil = (dim + 1) / 2;
  7262. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  7263. } break;
  7264. case GGML_OP_CONV_TRANSPOSE_1D:
  7265. {
  7266. elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1}
  7267. } break;
  7268. case GGML_OP_POOL_2D:
  7269. {
  7270. const uint32_t N = dst->ne[3];
  7271. const uint32_t OC = dst->ne[2];
  7272. const uint32_t OH = dst->ne[1];
  7273. const uint32_t OW = dst->ne[0];
  7274. elements = { N * OC * OH * OW, 1, 1};
  7275. } break;
  7276. case GGML_OP_CONV_2D:
  7277. {
  7278. elements = ggml_vk_get_conv_elements(dst);
  7279. } break;
  7280. case GGML_OP_CONV_TRANSPOSE_2D:
  7281. {
  7282. elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  7283. } break;
  7284. case GGML_OP_ADD:
  7285. case GGML_OP_SUB:
  7286. case GGML_OP_DIV:
  7287. case GGML_OP_MUL:
  7288. case GGML_OP_SCALE:
  7289. case GGML_OP_SQR:
  7290. case GGML_OP_SQRT:
  7291. case GGML_OP_SIN:
  7292. case GGML_OP_COS:
  7293. case GGML_OP_CLAMP:
  7294. case GGML_OP_PAD:
  7295. case GGML_OP_ROLL:
  7296. case GGML_OP_REPEAT:
  7297. case GGML_OP_REPEAT_BACK:
  7298. case GGML_OP_CPY:
  7299. case GGML_OP_CONCAT:
  7300. case GGML_OP_UPSCALE:
  7301. case GGML_OP_UNARY:
  7302. case GGML_OP_GLU:
  7303. case GGML_OP_CONV_2D_DW:
  7304. {
  7305. uint32_t ne = ggml_nelements(dst);
  7306. if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7307. // Convert from number of logical elements to 2- or 4-byte units.
  7308. ne /= ggml_blck_size(src0->type);
  7309. if ((ggml_type_size(src0->type) % 4) == 0) {
  7310. ne *= ggml_type_size(src0->type) / 4;
  7311. } else {
  7312. ne *= ggml_type_size(src0->type) / 2;
  7313. }
  7314. }
  7315. // copy_to_quant has block size of 32, and each thread does QUANT_K elements.
  7316. // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements.
  7317. // So divide by block size here before splitting into 512x512 groups.
  7318. if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7319. ne = CEIL_DIV(ne, ggml_blck_size(dst->type));
  7320. }
  7321. if (ne > 262144) {
  7322. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7323. } else if (ne > 512) {
  7324. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7325. } else {
  7326. elements = { ne, 1, 1 };
  7327. }
  7328. } break;
  7329. case GGML_OP_ADD_ID:
  7330. {
  7331. elements = { (uint32_t)ne01, (uint32_t)ne02, 1 };
  7332. } break;
  7333. case GGML_OP_SET_ROWS:
  7334. {
  7335. uint32_t ne = ggml_nelements(src0);
  7336. if (ggml_is_quantized(dst->type)) {
  7337. // quants run 32 threads each doing QUANT_K elements
  7338. ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type));
  7339. } else {
  7340. // scalar types do one element per thread, running 512 threads
  7341. ne = CEIL_DIV(ne, 512);
  7342. }
  7343. if (ne > 262144) {
  7344. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7345. } else if (ne > 512) {
  7346. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7347. } else {
  7348. elements = { ne, 1, 1 };
  7349. }
  7350. }
  7351. break;
  7352. default:
  7353. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  7354. break;
  7355. }
  7356. if (!op_supports_incontiguous) {
  7357. if (x_sz != VK_WHOLE_SIZE) {
  7358. x_sz *= ne02 * ne03;
  7359. }
  7360. if (use_src1 && y_sz != VK_WHOLE_SIZE) {
  7361. y_sz *= ne12 * ne13;
  7362. }
  7363. if (use_src2 && z_sz != VK_WHOLE_SIZE) {
  7364. z_sz *= ne22 * ne23;
  7365. }
  7366. if (d_sz != VK_WHOLE_SIZE) {
  7367. d_sz *= ned2 * ned3;
  7368. }
  7369. }
  7370. if (op == GGML_OP_ADD || op == GGML_OP_RMS_NORM) {
  7371. vk_buffer d_A = ctx->do_add_rms_partials ? ctx->prealloc_add_rms_partials : d_X;
  7372. size_t a_buf_offset = ctx->do_add_rms_partials ? ctx->prealloc_size_add_rms_partials_offset : 0;
  7373. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7374. { vk_subbuffer{ d_X, x_buf_offset, x_sz },
  7375. vk_subbuffer{ d_Y, y_buf_offset, y_sz },
  7376. vk_subbuffer{ d_D, d_buf_offset, d_sz },
  7377. vk_subbuffer{ d_A, a_buf_offset, VK_WHOLE_SIZE },
  7378. }, pc, elements);
  7379. } else if (op == GGML_OP_GLU) {
  7380. // Empty src1 is possible in glu, but the shader needs a buffer
  7381. vk_subbuffer subbuf_y;
  7382. if (use_src1) {
  7383. subbuf_y = { d_Y, y_buf_offset, y_sz };
  7384. } else {
  7385. subbuf_y = { d_X, 0, x_sz };
  7386. }
  7387. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, subbuf_y, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7388. } else if (op == GGML_OP_SOFT_MAX) {
  7389. // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer
  7390. vk_subbuffer subbuf_y;
  7391. if (use_src1) {
  7392. subbuf_y = { d_Y, y_buf_offset, y_sz };
  7393. } else {
  7394. subbuf_y = { d_X, 0, x_sz };
  7395. }
  7396. vk_subbuffer subbuf_z;
  7397. if (use_src2) {
  7398. subbuf_z = { d_Z, z_buf_offset, z_sz };
  7399. } else {
  7400. subbuf_z = { d_X, 0, x_sz };
  7401. }
  7402. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, subbuf_y, subbuf_z, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7403. } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) {
  7404. // Empty src2 is possible in rope, but the shader needs a buffer
  7405. vk_subbuffer subbuf_z;
  7406. if (use_src2) {
  7407. subbuf_z = { d_Z, z_buf_offset, z_sz };
  7408. } else {
  7409. subbuf_z = { d_X, 0, x_sz };
  7410. }
  7411. 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 } }, pc, elements);
  7412. } else if (op == GGML_OP_IM2COL || op == GGML_OP_IM2COL_3D) {
  7413. // im2col uses only src1 and dst buffers
  7414. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7415. } else if (op == GGML_OP_COUNT_EQUAL) {
  7416. // count_equal assumes that destination buffer is initialized with zeroes
  7417. ggml_vk_buffer_memset_async(subctx, d_D, d_buf_offset, 0, d_sz);
  7418. ggml_vk_sync_buffers(ctx, subctx);
  7419. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7420. } else if (op == GGML_OP_OPT_STEP_SGD) {
  7421. // OPT_STEP_SGD works on src0, it does not need dst
  7422. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_Z, z_buf_offset, z_sz } }, pc, elements);
  7423. } else if (use_src2) {
  7424. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_Z, z_buf_offset, z_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7425. } else if (use_src1) {
  7426. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_Y, y_buf_offset, y_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7427. } else {
  7428. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { vk_subbuffer{ d_X, x_buf_offset, x_sz }, vk_subbuffer{ d_D, d_buf_offset, d_sz } }, pc, elements);
  7429. }
  7430. }
  7431. 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) {
  7432. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7433. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7434. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7435. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_GET_ROWS, {
  7436. (uint32_t)ggml_nelements(src0),
  7437. (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,
  7438. (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,
  7439. (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,
  7440. 0,
  7441. 0.0f, 0.0f, 0,
  7442. }, dryrun);
  7443. }
  7444. 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) {
  7445. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7446. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7447. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7448. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  7449. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  7450. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  7451. int offset = dst->op_params[3] / 4; // offset in bytes
  7452. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ACC, {
  7453. (uint32_t)ggml_nelements(src0),
  7454. (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,
  7455. (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,
  7456. (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,
  7457. 0,
  7458. 0.0f, 0.0f, offset,
  7459. }, dryrun);
  7460. }
  7461. static void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx, bool dryrun = false) {
  7462. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  7463. const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  7464. // Make a list of all the tensors used by the op.
  7465. // Last element of the list is the dest tensor.
  7466. const ggml_tensor *tensors[MAX_PARAMETER_COUNT];
  7467. uint32_t num_srcs = ctx->num_additional_fused_ops + 2;
  7468. uint32_t num_tensors = num_srcs + 1;
  7469. GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT);
  7470. tensors[0] = first_node->src[0];
  7471. tensors[1] = first_node->src[1];
  7472. for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) {
  7473. // check whether the previous result is src[0] or src[1]
  7474. if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) {
  7475. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1];
  7476. } else {
  7477. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0];
  7478. }
  7479. }
  7480. tensors[num_srcs] = dst;
  7481. vk_op_multi_add_push_constants pc;
  7482. pc.ne20 = (uint32_t)dst->ne[0];
  7483. pc.ne21 = (uint32_t)dst->ne[1];
  7484. pc.ne22 = (uint32_t)dst->ne[2];
  7485. pc.ne23 = (uint32_t)dst->ne[3];
  7486. for (uint32_t i = 0; i < num_tensors; ++i) {
  7487. const ggml_tensor *t = tensors[i];
  7488. pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float);
  7489. pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float);
  7490. pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float);
  7491. pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float);
  7492. }
  7493. pc.rms_partials = ctx->do_add_rms_partials;
  7494. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, tensors[0], tensors[1], nullptr, dst, dst->op);
  7495. if (pipeline == nullptr) {
  7496. std::cerr << "ggml_vulkan: Error: Missing multi_add";
  7497. GGML_ABORT("fatal error");
  7498. }
  7499. if (dryrun) {
  7500. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7501. return;
  7502. }
  7503. ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT];
  7504. vk_buffer buf[MAX_PARAMETER_COUNT];
  7505. size_t offset[MAX_PARAMETER_COUNT];
  7506. bool uma[MAX_PARAMETER_COUNT];
  7507. for (uint32_t i = 0; i < num_tensors; ++i) {
  7508. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  7509. buf[i] = nullptr;
  7510. offset[i] = 0;
  7511. uma[i] = false;
  7512. if (ctx->device->uma) {
  7513. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  7514. uma[i] = buf[i] != nullptr;
  7515. }
  7516. if (!uma[i]) {
  7517. buf[i] = buf_ctx[i]->dev_buffer;
  7518. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  7519. }
  7520. GGML_ASSERT(buf[i] != nullptr);
  7521. }
  7522. // If any remaining descriptors are unused, just point them at src[0]
  7523. for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) {
  7524. buf[i] = buf[0];
  7525. offset[i] = 0;
  7526. }
  7527. if (ctx->do_add_rms_partials) {
  7528. buf[num_tensors] = ctx->prealloc_add_rms_partials;
  7529. offset[num_tensors] = ctx->prealloc_size_add_rms_partials_offset;
  7530. }
  7531. std::array<uint32_t, 3> elements;
  7532. uint32_t ne = ggml_nelements(dst);
  7533. if (ne > 262144) {
  7534. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7535. } else if (ne > 512) {
  7536. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7537. } else {
  7538. elements = { ne, 1, 1 };
  7539. }
  7540. static_assert(MAX_PARAMETER_COUNT == 12);
  7541. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7542. {
  7543. vk_subbuffer{ buf[0], offset[0], VK_WHOLE_SIZE },
  7544. vk_subbuffer{ buf[1], offset[1], VK_WHOLE_SIZE },
  7545. vk_subbuffer{ buf[2], offset[2], VK_WHOLE_SIZE },
  7546. vk_subbuffer{ buf[3], offset[3], VK_WHOLE_SIZE },
  7547. vk_subbuffer{ buf[4], offset[4], VK_WHOLE_SIZE },
  7548. vk_subbuffer{ buf[5], offset[5], VK_WHOLE_SIZE },
  7549. vk_subbuffer{ buf[6], offset[6], VK_WHOLE_SIZE },
  7550. vk_subbuffer{ buf[7], offset[7], VK_WHOLE_SIZE },
  7551. vk_subbuffer{ buf[8], offset[8], VK_WHOLE_SIZE },
  7552. vk_subbuffer{ buf[9], offset[9], VK_WHOLE_SIZE },
  7553. vk_subbuffer{ buf[10], offset[10], VK_WHOLE_SIZE },
  7554. vk_subbuffer{ buf[11], offset[11], VK_WHOLE_SIZE },
  7555. }, pc, elements);
  7556. }
  7557. 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) {
  7558. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7559. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7560. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7561. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ADD, {
  7562. (uint32_t)ggml_nelements(src0),
  7563. (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,
  7564. (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,
  7565. (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,
  7566. 0,
  7567. 0.0f, 0.0f, ctx->do_add_rms_partials,
  7568. }, dryrun);
  7569. }
  7570. static void ggml_vk_sub(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  7571. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7572. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7573. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7574. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_SUB, {
  7575. (uint32_t)ggml_nelements(src0),
  7576. (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,
  7577. (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,
  7578. (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,
  7579. 0,
  7580. 0.0f, 0.0f, 0,
  7581. }, dryrun);
  7582. }
  7583. 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) {
  7584. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7585. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7586. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7587. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_MUL, {
  7588. (uint32_t)ggml_nelements(src0),
  7589. (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,
  7590. (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,
  7591. (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,
  7592. 0,
  7593. 0.0f, 0.0f, 0,
  7594. }, dryrun);
  7595. }
  7596. 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) {
  7597. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7598. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7599. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7600. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_DIV, {
  7601. (uint32_t)ggml_nelements(src0),
  7602. (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,
  7603. (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,
  7604. (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,
  7605. 0,
  7606. 0.0f, 0.0f, 0,
  7607. }, dryrun);
  7608. }
  7609. static void ggml_vk_add_id(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, bool dryrun = false) {
  7610. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7611. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7612. const uint32_t src2_type_size = ggml_type_size(src2->type);
  7613. ggml_vk_op_f32<vk_op_add_id_push_constants>(ctx, subctx, src0, src1, src2, dst, GGML_OP_ADD_ID, {
  7614. (uint32_t)dst->ne[0],
  7615. (uint32_t)dst->ne[1],
  7616. (uint32_t)src0->nb[1] / src0_type_size,
  7617. (uint32_t)src0->nb[2] / src0_type_size,
  7618. (uint32_t)src1->nb[1] / src1_type_size,
  7619. (uint32_t)src2->nb[1] / src2_type_size,
  7620. }, dryrun);
  7621. }
  7622. static void ggml_vk_op_f32_wkv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, const vk_op_rwkv_wkv6_push_constants&& pc, int version, bool dryrun = false) {
  7623. GGML_ASSERT(version == 6 || version == 7);
  7624. int num_srcs = version == 6 ? 6 : 7;
  7625. for (int i = 0; i < num_srcs; i++) {
  7626. GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type));
  7627. }
  7628. GGML_ASSERT(dst->buffer != nullptr);
  7629. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op);
  7630. GGML_ASSERT(pipeline != nullptr);
  7631. if (dryrun) {
  7632. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7633. return;
  7634. }
  7635. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  7636. ggml_backend_vk_buffer_context * src_buf_ctxs[7] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
  7637. for (int i = 0; i < num_srcs; i++) {
  7638. src_buf_ctxs[i] = (ggml_backend_vk_buffer_context *)dst->src[i]->buffer->context;
  7639. }
  7640. vk_buffer d_D = nullptr, d_srcs[7] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
  7641. size_t dst_offset = 0, src_offsets[7] = { 0, 0, 0, 0, 0, 0, 0 };
  7642. bool dst_uma = false, srcs_uma[7] = { false, false, false, false, false, false, false };
  7643. if (ctx->device->uma) {
  7644. for (int i = 0; i < num_srcs; i++) {
  7645. ggml_vk_host_get(ctx->device, dst->src[i]->data, d_srcs[i], src_offsets[i]);
  7646. srcs_uma[i] = d_srcs[i] != nullptr;
  7647. }
  7648. ggml_vk_host_get(ctx->device, dst->data, d_D, dst_offset);
  7649. dst_uma = d_D != nullptr;
  7650. }
  7651. uint64_t src_sizes[7] = { 0, 0, 0, 0, 0, 0, 0 };
  7652. for (int i = 0; i < num_srcs; i++) {
  7653. src_sizes[i] = ggml_nbytes(dst->src[i]);
  7654. if (!srcs_uma[i]) {
  7655. d_srcs[i] = src_buf_ctxs[i]->dev_buffer;
  7656. src_offsets[i] = vk_tensor_offset(dst->src[i]) + dst->src[i]->view_offs;
  7657. }
  7658. }
  7659. const uint64_t dst_size = ggml_nbytes(dst);
  7660. if (!dst_uma) {
  7661. d_D = dst_buf_ctx->dev_buffer;
  7662. dst_offset = vk_tensor_offset(dst) + dst->view_offs;
  7663. }
  7664. std::array<uint32_t, 3> elements = {
  7665. (uint32_t)(pc.B * pc.H),
  7666. 1,
  7667. 1
  7668. };
  7669. if (version == 6) {
  7670. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  7671. vk_subbuffer{ d_srcs[0], src_offsets[0], src_sizes[0] },
  7672. vk_subbuffer{ d_srcs[1], src_offsets[1], src_sizes[1] },
  7673. vk_subbuffer{ d_srcs[2], src_offsets[2], src_sizes[2] },
  7674. vk_subbuffer{ d_srcs[3], src_offsets[3], src_sizes[3] },
  7675. vk_subbuffer{ d_srcs[4], src_offsets[4], src_sizes[4] },
  7676. vk_subbuffer{ d_srcs[5], src_offsets[5], src_sizes[5] },
  7677. vk_subbuffer{ d_D, dst_offset, dst_size }
  7678. }, pc, elements);
  7679. } else if (version == 7) {
  7680. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  7681. vk_subbuffer{ d_srcs[0], src_offsets[0], src_sizes[0] },
  7682. vk_subbuffer{ d_srcs[1], src_offsets[1], src_sizes[1] },
  7683. vk_subbuffer{ d_srcs[2], src_offsets[2], src_sizes[2] },
  7684. vk_subbuffer{ d_srcs[3], src_offsets[3], src_sizes[3] },
  7685. vk_subbuffer{ d_srcs[4], src_offsets[4], src_sizes[4] },
  7686. vk_subbuffer{ d_srcs[5], src_offsets[5], src_sizes[5] },
  7687. vk_subbuffer{ d_srcs[6], src_offsets[6], src_sizes[6] },
  7688. vk_subbuffer{ d_D, dst_offset, dst_size }
  7689. }, pc, elements);
  7690. } else {
  7691. // shouldn't happen
  7692. GGML_ASSERT(false);
  7693. }
  7694. }
  7695. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  7696. const size_t seq_length = dst->src[0]->ne[2];
  7697. const size_t n_embed = dst->ne[0];
  7698. const size_t n_heads = dst->src[0]->ne[1];
  7699. const size_t n_seqs = dst->src[5]->ne[1];
  7700. ggml_vk_op_f32_wkv(
  7701. ctx, subctx, dst,
  7702. {
  7703. (uint32_t)n_seqs,
  7704. (uint32_t)seq_length,
  7705. (uint32_t)n_embed,
  7706. (uint32_t)n_heads,
  7707. },
  7708. 6,
  7709. dryrun
  7710. );
  7711. }
  7712. static void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  7713. const size_t seq_length = dst->src[0]->ne[2];
  7714. const size_t n_embed = dst->ne[0];
  7715. const size_t n_heads = dst->src[0]->ne[1];
  7716. const size_t n_seqs = dst->src[6]->ne[1];
  7717. ggml_vk_op_f32_wkv(
  7718. ctx, subctx, dst,
  7719. {
  7720. (uint32_t)n_seqs,
  7721. (uint32_t)seq_length,
  7722. (uint32_t)n_embed,
  7723. (uint32_t)n_heads,
  7724. },
  7725. 7,
  7726. dryrun
  7727. );
  7728. }
  7729. static void ggml_vk_op_f32_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, const vk_op_push_constants&& pc, bool dryrun = false) {
  7730. const ggml_tensor * x = dst->src[0];
  7731. const ggml_tensor * g = dst->src[1];
  7732. const ggml_tensor * gm = dst->src[2];
  7733. const ggml_tensor * gv = dst->src[3];
  7734. const ggml_tensor * p = dst->src[4];
  7735. GGML_ASSERT(x->type == GGML_TYPE_F32);
  7736. GGML_ASSERT(g->type == GGML_TYPE_F32);
  7737. GGML_ASSERT(gm->type == GGML_TYPE_F32);
  7738. GGML_ASSERT(gv->type == GGML_TYPE_F32);
  7739. GGML_ASSERT(p->type == GGML_TYPE_F32);
  7740. GGML_ASSERT(dst->buffer != nullptr);
  7741. GGML_ASSERT(ggml_is_contiguous(x));
  7742. GGML_ASSERT(ggml_is_contiguous(g));
  7743. GGML_ASSERT(ggml_is_contiguous(gm));
  7744. GGML_ASSERT(ggml_is_contiguous(gv));
  7745. GGML_ASSERT(ggml_is_contiguous(p));
  7746. GGML_ASSERT(ggml_are_same_shape(x, g));
  7747. GGML_ASSERT(ggml_are_same_shape(x, gm));
  7748. GGML_ASSERT(ggml_are_same_shape(x, gv));
  7749. GGML_ASSERT(ggml_nelements(p) == 7);
  7750. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW);
  7751. GGML_ASSERT(pipeline != nullptr);
  7752. if (dryrun) {
  7753. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7754. return;
  7755. }
  7756. ggml_backend_vk_buffer_context * x_buf_ctx = (ggml_backend_vk_buffer_context *)x->buffer->context;
  7757. ggml_backend_vk_buffer_context * g_buf_ctx = (ggml_backend_vk_buffer_context *)g->buffer->context;
  7758. ggml_backend_vk_buffer_context * gm_buf_ctx = (ggml_backend_vk_buffer_context *)gm->buffer->context;
  7759. ggml_backend_vk_buffer_context * gv_buf_ctx = (ggml_backend_vk_buffer_context *)gv->buffer->context;
  7760. ggml_backend_vk_buffer_context * p_buf_ctx = (ggml_backend_vk_buffer_context *)p->buffer->context;
  7761. vk_buffer d_X = nullptr, d_G = nullptr, d_GM = nullptr, d_GV = nullptr, d_P = nullptr;
  7762. size_t x_offset = 0, g_offset = 0, gm_offset = 0, gv_offset = 0, p_offset = 0;
  7763. bool X_uma = false, G_uma = false, GM_uma = false, GV_uma = false, P_uma = false;
  7764. if (ctx->device->uma) {
  7765. ggml_vk_host_get(ctx->device, x->data, d_X, x_offset);
  7766. ggml_vk_host_get(ctx->device, g->data, d_G, g_offset);
  7767. ggml_vk_host_get(ctx->device, gm->data, d_GM, gm_offset);
  7768. ggml_vk_host_get(ctx->device, gv->data, d_GV, gv_offset);
  7769. ggml_vk_host_get(ctx->device, p->data, d_P, p_offset);
  7770. X_uma = d_X != nullptr;
  7771. G_uma = d_G != nullptr;
  7772. GM_uma = d_GM != nullptr;
  7773. GV_uma = d_GV != nullptr;
  7774. P_uma = d_P != nullptr;
  7775. }
  7776. if (!X_uma) {
  7777. d_X = x_buf_ctx->dev_buffer;
  7778. x_offset = vk_tensor_offset(x) + x->view_offs;
  7779. }
  7780. if (!G_uma) {
  7781. d_G = g_buf_ctx->dev_buffer;
  7782. g_offset = vk_tensor_offset(g) + g->view_offs;
  7783. }
  7784. if (!GM_uma) {
  7785. d_GM = gm_buf_ctx->dev_buffer;
  7786. gm_offset = vk_tensor_offset(gm) + gm->view_offs;
  7787. }
  7788. if (!GV_uma) {
  7789. d_GV = gv_buf_ctx->dev_buffer;
  7790. gv_offset = vk_tensor_offset(gv) + gv->view_offs;
  7791. }
  7792. if (!P_uma) {
  7793. d_P = p_buf_ctx->dev_buffer;
  7794. p_offset = vk_tensor_offset(p) + p->view_offs;
  7795. }
  7796. const uint64_t x_size = ggml_nbytes(x);
  7797. const uint64_t g_size = ggml_nbytes(g);
  7798. const uint64_t gm_size = ggml_nbytes(gm);
  7799. const uint64_t gv_size = ggml_nbytes(gv);
  7800. const uint64_t p_size = ggml_nbytes(p);
  7801. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(x), 1, 1 };
  7802. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  7803. vk_subbuffer{ d_X, x_offset, x_size },
  7804. vk_subbuffer{ d_G, g_offset, g_size },
  7805. vk_subbuffer{ d_GM, gm_offset, gm_size },
  7806. vk_subbuffer{ d_GV, gv_offset, gv_size },
  7807. vk_subbuffer{ d_P, p_offset, p_size },
  7808. }, pc, elements);
  7809. }
  7810. static void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  7811. const size_t n = ggml_nelements(dst->src[0]);
  7812. ggml_vk_op_f32_opt_step_adamw(
  7813. ctx, subctx, dst,
  7814. { (uint32_t)n, 0, 0.0f, 0.0f },
  7815. dryrun
  7816. );
  7817. }
  7818. static void ggml_vk_opt_step_sgd(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, bool dryrun = false) {
  7819. const size_t n = ggml_nelements(dst->src[0]);
  7820. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, src2, dst, GGML_OP_OPT_STEP_SGD, { (uint32_t)n, 0, 0.0f, 0.0f }, dryrun);
  7821. }
  7822. 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) {
  7823. int * op_params = (int *)dst->op_params;
  7824. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7825. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7826. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7827. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONCAT, {
  7828. (uint32_t)ggml_nelements(dst),
  7829. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],(uint32_t)src0->ne[3], (uint32_t)src0->nb[0] / src0_type_size, (uint32_t)src0->nb[1] / src0_type_size, (uint32_t)src0->nb[2] / src0_type_size, (uint32_t)src0->nb[3] / src0_type_size,
  7830. (uint32_t)src1->ne[0], (uint32_t)src1->ne[1], (uint32_t)src1->ne[2],(uint32_t)src1->ne[3], (uint32_t)src1->nb[0] / src1_type_size, (uint32_t)src1->nb[1] / src1_type_size, (uint32_t)src1->nb[2] / src1_type_size, (uint32_t)src1->nb[3] / src1_type_size,
  7831. (uint32_t) dst->ne[0], (uint32_t) dst->ne[1], (uint32_t) dst->ne[2],(uint32_t) dst->ne[3], (uint32_t) dst->nb[0] / dst_type_size, (uint32_t) dst->nb[1] / dst_type_size, (uint32_t) dst->nb[2] / dst_type_size, (uint32_t) dst->nb[3] / dst_type_size,
  7832. 0,
  7833. 0.0f, 0.0f, op_params[0],
  7834. }, dryrun);
  7835. }
  7836. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7837. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7838. const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0);
  7839. float sf0 = (float)dst->ne[0] / src0->ne[0];
  7840. float sf1 = (float)dst->ne[1] / src0->ne[1];
  7841. float sf2 = (float)dst->ne[2] / src0->ne[2];
  7842. float sf3 = (float)dst->ne[3] / src0->ne[3];
  7843. if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) {
  7844. sf0 = (float)(dst->ne[0] - 1) / (src0->ne[0] - 1);
  7845. sf1 = (float)(dst->ne[1] - 1) / (src0->ne[1] - 1);
  7846. }
  7847. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  7848. (uint32_t)ggml_nelements(dst), 0, 0,
  7849. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1],
  7850. (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,
  7851. (uint32_t)dst->ne[0], (uint32_t)dst->ne[1], (uint32_t)dst->ne[2],(uint32_t)dst->ne[3],
  7852. sf0, sf1, sf2, sf3,
  7853. }, dryrun);
  7854. }
  7855. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7856. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  7857. p.param1 = ggml_get_op_params_f32(dst, 0);
  7858. p.param2 = ggml_get_op_params_f32(dst, 1);
  7859. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p), dryrun);
  7860. }
  7861. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7862. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst), dryrun);
  7863. }
  7864. static void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7865. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst), dryrun);
  7866. }
  7867. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7868. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst), dryrun);
  7869. }
  7870. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7871. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst), dryrun);
  7872. }
  7873. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7874. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  7875. p.param1 = ggml_get_op_params_f32(dst, 0);
  7876. p.param2 = ggml_get_op_params_f32(dst, 1);
  7877. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p), dryrun);
  7878. }
  7879. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7880. vk_op_pad_push_constants p = vk_op_pad_push_constants_init(src0, dst);
  7881. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p), dryrun);
  7882. }
  7883. static void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7884. const int32_t s0 = ggml_get_op_params_i32(dst, 0);
  7885. const int32_t s1 = ggml_get_op_params_i32(dst, 1);
  7886. const int32_t s2 = ggml_get_op_params_i32(dst, 2);
  7887. const int32_t s3 = ggml_get_op_params_i32(dst, 3);
  7888. const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
  7889. const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
  7890. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  7891. memcpy(&p.param1, &s01_packed, sizeof(float));
  7892. memcpy(&p.param2, &s23_packed, sizeof(float));
  7893. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p), dryrun);
  7894. }
  7895. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7896. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  7897. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p), dryrun);
  7898. }
  7899. static void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7900. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  7901. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p), dryrun);
  7902. }
  7903. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7904. uint32_t ne = (uint32_t)ggml_nelements(src0);
  7905. if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7906. // Convert from number of logical elements to 2- or 4-byte units.
  7907. ne /= ggml_blck_size(src0->type);
  7908. if ((ggml_type_size(src0->type) % 4) == 0) {
  7909. ne *= ggml_type_size(src0->type) / 4;
  7910. } else {
  7911. ne *= ggml_type_size(src0->type) / 2;
  7912. }
  7913. }
  7914. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne);
  7915. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p), dryrun);
  7916. }
  7917. static void ggml_vk_set_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  7918. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7919. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7920. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7921. // Skip empty skip_rows operations. For most ops the empty check at the start
  7922. // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst
  7923. // with empty srcs.
  7924. if (ggml_is_empty(src0) || ggml_is_empty(src1)) {
  7925. return;
  7926. }
  7927. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_SET_ROWS, {
  7928. (uint32_t)ggml_nelements(src0),
  7929. (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,
  7930. (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,
  7931. (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,
  7932. 0,
  7933. 0.0f, 0.0f, 0,
  7934. }, dryrun);
  7935. }
  7936. static void ggml_vk_silu_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  7937. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_SILU_BACK, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f }, dryrun);
  7938. }
  7939. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7940. float * op_params = (float *)dst->op_params;
  7941. 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);
  7942. }
  7943. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7944. const int * int_op_params = (const int *)dst->op_params;
  7945. const float * float_op_params = (const float *)dst->op_params;
  7946. const uint32_t num_groups = int_op_params[0];
  7947. const float eps = float_op_params[1];
  7948. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  7949. 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);
  7950. }
  7951. static uint32_t ggml_vk_rms_num_partials(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  7952. const uint32_t ne = (uint32_t)node->ne[0];
  7953. const uint32_t denom = ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0];
  7954. const uint32_t num_partials = CEIL_DIV(ne, denom);
  7955. return num_partials;
  7956. }
  7957. static uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  7958. const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node);
  7959. const uint32_t num_bytes = ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment);
  7960. return num_bytes;
  7961. }
  7962. static void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, float * op_params, bool dryrun = false) {
  7963. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7964. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7965. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7966. uint32_t param3 = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0;
  7967. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_RMS_NORM, {
  7968. (uint32_t)ggml_nelements(src0),
  7969. (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,
  7970. (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,
  7971. (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,
  7972. 0,
  7973. op_params[0], 0.0f, (int32_t)param3,
  7974. }, dryrun);
  7975. if (ctx->do_add_rms_partials) {
  7976. ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0);
  7977. ctx->do_add_rms_partials = false;
  7978. }
  7979. }
  7980. static void ggml_vk_rms_norm_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  7981. float * op_params = (float *)dst->op_params;
  7982. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_RMS_NORM_BACK, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f }, dryrun);
  7983. }
  7984. static void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7985. float * op_params = (float *)dst->op_params;
  7986. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_L2_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f }, dryrun);
  7987. }
  7988. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7989. 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);
  7990. }
  7991. static void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  7992. const float * op_params_f = (const float *)dst->op_params;
  7993. const bool swapped = (bool)dst->op_params[1];
  7994. const bool split = src1 != nullptr;
  7995. const float alpha = op_params_f[2];
  7996. const float limit = op_params_f[3];
  7997. GGML_ASSERT(ggml_is_contiguous(src0));
  7998. if (!split) {
  7999. GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]);
  8000. } else {
  8001. GGML_ASSERT(src0->ne[0] == src1->ne[0]);
  8002. GGML_ASSERT(src0->ne[0] == dst->ne[0]);
  8003. GGML_ASSERT(src0->type == src1->type);
  8004. }
  8005. const uint32_t mode = split ? 2 : (swapped ? 1 : 0);
  8006. ggml_vk_op_f32<vk_op_glu_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_GLU,
  8007. {
  8008. (uint32_t)ggml_nelements(dst),
  8009. (uint32_t)src0->ne[0],
  8010. (uint32_t)dst->ne[0],
  8011. mode,
  8012. alpha,
  8013. limit
  8014. }, dryrun);
  8015. }
  8016. 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) {
  8017. int32_t * op_params = (int32_t *)dst->op_params;
  8018. 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);
  8019. }
  8020. static void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, bool dryrun = false) {
  8021. float * op_params = (float *)dst->op_params;
  8022. float scale = op_params[0];
  8023. float max_bias = op_params[1];
  8024. const uint32_t ncols = (uint32_t)src0->ne[0];
  8025. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  8026. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  8027. const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u;
  8028. const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u;
  8029. const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u;
  8030. const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u;
  8031. const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u;
  8032. const uint32_t n_head_kv = src0->ne[2];
  8033. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  8034. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  8035. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  8036. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, dst, GGML_OP_SOFT_MAX, {
  8037. ncols,
  8038. src1 != nullptr ? nrows_y : (uint32_t)0,
  8039. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],
  8040. ne12, ne13,
  8041. nb11, nb12, nb13,
  8042. scale, max_bias,
  8043. m0, m1,
  8044. n_head_log2,
  8045. nrows_x,
  8046. src2 != nullptr
  8047. }, dryrun);
  8048. }
  8049. static void ggml_vk_soft_max_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8050. float * op_params = (float *)dst->op_params;
  8051. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_SOFT_MAX_BACK, { (uint32_t)src0->ne[0], (uint32_t)ggml_nrows(src0), op_params[0], op_params[1] }, dryrun);
  8052. }
  8053. 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 backprop, bool dryrun = false) {
  8054. const int n_dims = ((int32_t *) dst->op_params)[1];
  8055. const int mode = ((int32_t *) dst->op_params)[2];
  8056. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  8057. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  8058. const float freq_base = ((float *) dst->op_params)[5];
  8059. const float freq_scale = ((float *) dst->op_params)[6];
  8060. const float ext_factor = ((float *) dst->op_params)[7];
  8061. const float attn_factor = ((float *) dst->op_params)[8];
  8062. const float beta_fast = ((float *) dst->op_params)[9];
  8063. const float beta_slow = ((float *) dst->op_params)[10];
  8064. int sections[4] {};
  8065. if (mode & GGML_ROPE_TYPE_MROPE) {
  8066. memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4);
  8067. }
  8068. float corr_dims[2];
  8069. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8070. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  8071. uint32_t s1 = src0->nb[1] / ggml_type_size(src0->type);
  8072. uint32_t s2 = src0->nb[2] / ggml_type_size(src0->type);
  8073. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, dst, GGML_OP_ROPE, {
  8074. (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  8075. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  8076. src2 != nullptr, (uint32_t)src0->ne[2], s1, s2,
  8077. { sections[0], sections[1], sections[2], sections[3] }, backprop
  8078. }, dryrun);
  8079. }
  8080. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8081. int32_t * op_params = (int32_t *)dst->op_params;
  8082. uint32_t ncols = src0->ne[0];
  8083. ggml_vk_op_f32<vk_op_argsort_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_ARGSORT, {
  8084. ncols,
  8085. op_params[0],
  8086. }, dryrun);
  8087. }
  8088. static void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8089. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, ggml_nelements(src0));
  8090. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SUM, p, dryrun);
  8091. }
  8092. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8093. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8094. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, p, dryrun);
  8095. }
  8096. static void ggml_vk_mean(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8097. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8098. p.weight = 1.0f / (float)src0->ne[0];
  8099. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_MEAN, p, dryrun);
  8100. }
  8101. static void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8102. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_ARGMAX, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], 0.0f, 0.0f }, dryrun);
  8103. }
  8104. static void ggml_vk_count_equal(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8105. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_COUNT_EQUAL, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f }, dryrun);
  8106. }
  8107. 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) {
  8108. const int32_t s0 = dst->op_params[0];
  8109. const int32_t s1 = dst->op_params[1];
  8110. const int32_t p0 = dst->op_params[2];
  8111. const int32_t p1 = dst->op_params[3];
  8112. const int32_t d0 = dst->op_params[4];
  8113. const int32_t d1 = dst->op_params[5];
  8114. const bool is_2D = dst->op_params[6] == 1;
  8115. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  8116. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  8117. const uint32_t IW = src1->ne[0];
  8118. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  8119. const uint32_t KW = src0->ne[0];
  8120. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  8121. const uint32_t OW = dst->ne[1];
  8122. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  8123. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  8124. const uint32_t pelements = OW * KW * KH;
  8125. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_IM2COL, {
  8126. batch_offset, offset_delta,
  8127. IC, IW, IH, OW, OH, KW, KH,
  8128. pelements,
  8129. IC * KH * KW,
  8130. s0, s1, p0, p1, d0, d1,
  8131. }, dryrun);
  8132. }
  8133. static void ggml_vk_im2col_3d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8134. GGML_TENSOR_BINARY_OP_LOCALS
  8135. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  8136. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  8137. const int32_t s2 = ((const int32_t *)(dst->op_params))[2];
  8138. const int32_t p0 = ((const int32_t *)(dst->op_params))[3];
  8139. const int32_t p1 = ((const int32_t *)(dst->op_params))[4];
  8140. const int32_t p2 = ((const int32_t *)(dst->op_params))[5];
  8141. const int32_t d0 = ((const int32_t *)(dst->op_params))[6];
  8142. const int32_t d1 = ((const int32_t *)(dst->op_params))[7];
  8143. const int32_t d2 = ((const int32_t *)(dst->op_params))[8];
  8144. const int32_t IC = ((const int32_t *)(dst->op_params))[9];
  8145. const int64_t N = ne13 / IC;
  8146. const int64_t ID = ne12;
  8147. const int64_t IH = ne11;
  8148. const int64_t IW = ne10;
  8149. const int64_t KD = ne02;
  8150. const int64_t KH = ne01;
  8151. const int64_t KW = ne00;
  8152. const int64_t OD = ne3 / N;
  8153. const int64_t OH = ne2;
  8154. const int64_t OW = ne1;
  8155. vk_op_im2col_3d_push_constants pc {};
  8156. pc.nb10 = nb10 / ggml_type_size(src1->type);
  8157. pc.nb11 = nb11 / ggml_type_size(src1->type);
  8158. pc.nb12 = nb12 / ggml_type_size(src1->type);
  8159. pc.nb13 = nb13 / ggml_type_size(src1->type);
  8160. pc.s0 = s0;
  8161. pc.s1 = s1;
  8162. pc.s2 = s2;
  8163. pc.p0 = p0;
  8164. pc.p1 = p1;
  8165. pc.p2 = p2;
  8166. pc.d0 = d0;
  8167. pc.d1 = d1;
  8168. pc.d2 = d2;
  8169. pc.IW = IW;
  8170. pc.IH = IH;
  8171. pc.ID = ID;
  8172. pc.IC = IC;
  8173. pc.KW = KW;
  8174. pc.OH = OH;
  8175. pc.KD_KH_KW = KD*KH*KW;
  8176. pc.KH_KW = KH*KW;
  8177. pc.IC_KD_KH_KW = IC*KD*KH*KW;
  8178. pc.N_OD_OH = N*OD*OH;
  8179. pc.OD_OH = OD*OH;
  8180. pc.OD_OH_OW_IC_KD_KH_KW = OD*OH*OW*IC*KD*KH*KW;
  8181. pc.OH_OW_IC_KD_KH_KW = OH*OW*IC*KD*KH*KW;
  8182. pc.OW_IC_KD_KH_KW = OW*IC*KD*KH*KW;
  8183. ggml_vk_op_f32<vk_op_im2col_3d_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_IM2COL_3D, std::move(pc), dryrun);
  8184. }
  8185. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8186. const uint32_t dim = dst->op_params[0];
  8187. const uint32_t max_period = dst->op_params[1];
  8188. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  8189. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  8190. nb1, dim, max_period,
  8191. }, dryrun);
  8192. }
  8193. static void ggml_vk_conv_transpose_1d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8194. // src0: (K, Cout, Cin, 1) -- kernel
  8195. // src1: (L, Cin, 1, 1) -- input
  8196. // dst: (*, Cout, 1, 1)
  8197. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  8198. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8199. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  8200. GGML_TENSOR_BINARY_OP_LOCALS
  8201. GGML_ASSERT(nb00 == sizeof(float));
  8202. GGML_ASSERT(nb10 == sizeof(float));
  8203. const int32_t s0 = dst->op_params[0];
  8204. vk_op_conv_transpose_1d_push_constants p{};
  8205. p.Cout = static_cast<uint32_t>(ne01);
  8206. p.Cin = static_cast<uint32_t>(ne02);
  8207. p.K = static_cast<uint32_t>(ne00);
  8208. p.L = static_cast<uint32_t>(ne10);
  8209. p.KL = static_cast<uint32_t>(ne0);
  8210. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8211. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8212. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8213. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8214. p.s0 = static_cast<uint32_t>(s0);
  8215. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p), dryrun);
  8216. }
  8217. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8218. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  8219. const int32_t k1 = dst->op_params[1];
  8220. const int32_t k0 = dst->op_params[2];
  8221. const int32_t s1 = dst->op_params[3];
  8222. const int32_t s0 = dst->op_params[4];
  8223. const int32_t p1 = dst->op_params[5];
  8224. const int32_t p0 = dst->op_params[6];
  8225. const uint32_t IH = src0->ne[1];
  8226. const uint32_t IW = src0->ne[0];
  8227. const uint32_t N = dst->ne[3];
  8228. const uint32_t OC = dst->ne[2];
  8229. const uint32_t OH = dst->ne[1];
  8230. const uint32_t OW = dst->ne[0];
  8231. const uint32_t parallel_elements = N * OC * OH * OW;
  8232. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  8233. IW, IH, OW, OH, OC,
  8234. parallel_elements,
  8235. op,
  8236. k0, k1, s0, s1, p0, p1,
  8237. }, dryrun);
  8238. }
  8239. static void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8240. const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8241. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8242. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8243. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8244. GGML_TENSOR_BINARY_OP_LOCALS
  8245. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8246. GGML_ASSERT(nb10 == sizeof(float));
  8247. GGML_ASSERT(nb0 == sizeof(float));
  8248. vk_op_conv2d_push_constants p{};
  8249. p.Cout = static_cast<uint32_t>(ne03);
  8250. p.Cin = static_cast<uint32_t>(ne02);
  8251. p.N = static_cast<uint32_t>(ne13);
  8252. p.KW = static_cast<uint32_t>(ne00);
  8253. p.KH = static_cast<uint32_t>(ne01);
  8254. p.W = static_cast<uint32_t>(ne10);
  8255. p.H = static_cast<uint32_t>(ne11);
  8256. p.OW = static_cast<uint32_t>(ne0);
  8257. p.OH = static_cast<uint32_t>(ne1);
  8258. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8259. p.s1 = static_cast<uint32_t>(dst->op_params[1]);
  8260. p.p0 = static_cast<uint32_t>(dst->op_params[2]);
  8261. p.p1 = static_cast<uint32_t>(dst->op_params[3]);
  8262. p.d0 = static_cast<uint32_t>(dst->op_params[4]);
  8263. p.d1 = static_cast<uint32_t>(dst->op_params[5]);
  8264. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8265. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8266. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  8267. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8268. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  8269. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  8270. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8271. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  8272. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  8273. GGML_ASSERT(ne03 == ne2);
  8274. GGML_ASSERT(ne02 == ne12);
  8275. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONV_2D, std::move(p), dryrun);
  8276. }
  8277. static void ggml_vk_conv_transpose_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8278. const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8279. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8280. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8281. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8282. GGML_TENSOR_BINARY_OP_LOCALS
  8283. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8284. GGML_ASSERT(nb10 == sizeof(float));
  8285. GGML_ASSERT(nb0 == sizeof(float));
  8286. vk_op_conv_transpose_2d_push_constants p{};
  8287. p.Cout = static_cast<uint32_t>(ne02);
  8288. p.Cin = static_cast<uint32_t>(ne03);
  8289. p.N = static_cast<uint32_t>(ne13);
  8290. p.KW = static_cast<uint32_t>(ne00);
  8291. p.KH = static_cast<uint32_t>(ne01);
  8292. p.W = static_cast<uint32_t>(ne10);
  8293. p.H = static_cast<uint32_t>(ne11);
  8294. p.OW = static_cast<uint32_t>(ne0);
  8295. p.OH = static_cast<uint32_t>(ne1);
  8296. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8297. p.s1 = static_cast<uint32_t>(dst->op_params[0]);
  8298. p.p0 = 0;
  8299. p.p1 = 0;
  8300. p.d0 = 1;
  8301. p.d1 = 1;
  8302. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8303. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8304. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  8305. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8306. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  8307. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  8308. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8309. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  8310. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  8311. GGML_ASSERT(ne02 == ne2);
  8312. GGML_ASSERT(ne03 == ne12);
  8313. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONV_TRANSPOSE_2D, std::move(p), dryrun);
  8314. }
  8315. static void ggml_vk_conv_2d_dw(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8316. vk_op_conv2d_dw_push_constants p{};
  8317. p.ne = ggml_nelements(dst);
  8318. p.channels = dst->ne[2];
  8319. p.batches = dst->ne[3];
  8320. p.dst_w = dst->ne[0];
  8321. p.dst_h = dst->ne[1];
  8322. p.src_w = src1->ne[0];
  8323. p.src_h = src1->ne[1];
  8324. p.knl_w = src0->ne[0];
  8325. p.knl_h = src0->ne[1];
  8326. p.stride_x = dst->op_params[0];
  8327. p.stride_y = dst->op_params[1];
  8328. p.pad_x = dst->op_params[2];
  8329. p.pad_y = dst->op_params[3];
  8330. p.dilation_x = dst->op_params[4];
  8331. p.dilation_y = dst->op_params[5];
  8332. GGML_ASSERT(src0->ne[3] == p.channels);
  8333. GGML_ASSERT(src1->ne[3] == p.batches);
  8334. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p), dryrun);
  8335. }
  8336. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8337. const float * op_params = (const float *)dst->op_params;
  8338. 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);
  8339. }
  8340. #ifdef GGML_VULKAN_RUN_TESTS
  8341. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  8342. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  8343. return;
  8344. }
  8345. i0 = std::max(i0, 5);
  8346. i1 = std::max(i1, 5);
  8347. i2 = std::max(i2, 0);
  8348. fprintf(stderr, " ");
  8349. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8350. fprintf(stderr, "%7d ", idx1);
  8351. }
  8352. fprintf(stderr, "\n");
  8353. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  8354. fprintf(stderr, "%7d: ", idx0);
  8355. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8356. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  8357. float val;
  8358. if (type == GGML_TYPE_F32) {
  8359. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  8360. } else if (type == GGML_TYPE_F16) {
  8361. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  8362. } else {
  8363. GGML_ABORT("fatal error");
  8364. }
  8365. fprintf(stderr, "% 7.2f ", val);
  8366. } else {
  8367. fprintf(stderr, " ");
  8368. }
  8369. }
  8370. fprintf(stderr, "\n");
  8371. }
  8372. }
  8373. template <typename X_TYPE, typename Y_TYPE>
  8374. 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) {
  8375. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  8376. const size_t x_ne = m * k * batch;
  8377. const size_t y_ne = k * n * batch;
  8378. const size_t d_ne = m * n * batch;
  8379. vk_pipeline p;
  8380. std::string shname;
  8381. if (shader_size == 0) {
  8382. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8383. p = ctx->device->pipeline_matmul_f32->a_s;
  8384. shname = "F32_ALIGNED_S";
  8385. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8386. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  8387. shname = "F32_F16_ALIGNED_S";
  8388. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8389. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  8390. shname = "F16_F32_ALIGNED_S";
  8391. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8392. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  8393. shname = "F16_ALIGNED_S";
  8394. } else {
  8395. GGML_ABORT("fatal error");
  8396. }
  8397. } else if (shader_size == 1) {
  8398. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8399. p = ctx->device->pipeline_matmul_f32->a_m;
  8400. shname = "F32_ALIGNED_M";
  8401. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8402. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  8403. shname = "F32_F16_ALIGNED_M";
  8404. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8405. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  8406. shname = "F16_F32_ALIGNED_M";
  8407. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8408. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  8409. shname = "F16_ALIGNED_M";
  8410. } else {
  8411. GGML_ABORT("fatal error");
  8412. }
  8413. } else if (shader_size == 2) {
  8414. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8415. p = ctx->device->pipeline_matmul_f32->a_l;
  8416. shname = "F32_ALIGNED_L";
  8417. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8418. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  8419. shname = "F32_F16_ALIGNED_L";
  8420. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8421. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  8422. shname = "F16_F32_ALIGNED_L";
  8423. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8424. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  8425. shname = "F16_ALIGNED_L";
  8426. } else {
  8427. GGML_ABORT("fatal error");
  8428. }
  8429. } else {
  8430. GGML_ASSERT(0);
  8431. }
  8432. const size_t kpad = ggml_vk_align_size(k, p->align);
  8433. if (k != kpad) {
  8434. if (shader_size == 0) {
  8435. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8436. p = ctx->device->pipeline_matmul_f32->s;
  8437. shname = "F32_S";
  8438. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8439. p = ctx->device->pipeline_matmul_f32_f16->s;
  8440. shname = "F32_F16_S";
  8441. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8442. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  8443. shname = "F16_F32_S";
  8444. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8445. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  8446. shname = "F16_S";
  8447. }
  8448. } else if (shader_size == 1) {
  8449. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8450. p = ctx->device->pipeline_matmul_f32->m;
  8451. shname = "F32_M";
  8452. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8453. p = ctx->device->pipeline_matmul_f32_f16->m;
  8454. shname = "F32_F16_M";
  8455. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8456. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  8457. shname = "F16_F32_M";
  8458. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8459. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  8460. shname = "F16_M";
  8461. }
  8462. } else if (shader_size == 2) {
  8463. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8464. p = ctx->device->pipeline_matmul_f32->l;
  8465. shname = "F32_L";
  8466. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8467. p = ctx->device->pipeline_matmul_f32_f16->l;
  8468. shname = "F32_F16_L";
  8469. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8470. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  8471. shname = "F16_F32_L";
  8472. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8473. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  8474. shname = "F16_L";
  8475. }
  8476. }
  8477. }
  8478. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  8479. if (split_k > 1) {
  8480. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  8481. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  8482. // Resize buffer
  8483. if (ctx->prealloc_split_k != nullptr) {
  8484. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  8485. }
  8486. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8487. }
  8488. }
  8489. if (ctx->device->need_compiles) {
  8490. ggml_vk_load_shaders(ctx->device);
  8491. }
  8492. ggml_pipeline_allocate_descriptor_sets(ctx);
  8493. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8494. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8495. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8496. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  8497. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  8498. float* d = (float *) malloc(sizeof(float) * d_ne);
  8499. for (size_t i = 0; i < x_ne; i++) {
  8500. if (std::is_same<float, X_TYPE>()) {
  8501. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  8502. // x[i] = 1.0f;
  8503. // x[i] = i + 1;
  8504. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  8505. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  8506. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  8507. // x[i] = ggml_fp32_to_fp16(1.0f);
  8508. // x[i] = ggml_fp32_to_fp16(i + 1);
  8509. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  8510. } else {
  8511. GGML_ABORT("fatal error");
  8512. }
  8513. }
  8514. for (size_t i = 0; i < y_ne; i++) {
  8515. if (std::is_same<float, Y_TYPE>()) {
  8516. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  8517. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  8518. // y[i] = i + 1;
  8519. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8520. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  8521. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  8522. // y[i] = ggml_fp32_to_fp16(i + 1);
  8523. } else {
  8524. GGML_ABORT("fatal error");
  8525. }
  8526. }
  8527. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  8528. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  8529. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  8530. ggml_vk_ctx_begin(ctx->device, subctx);
  8531. for (size_t i = 0; i < num_it; i++) {
  8532. ggml_vk_matmul(
  8533. 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),
  8534. m, n, k,
  8535. k, k, m, k*m, k*n, m*n,
  8536. split_k, batch, batch, batch, 1, 1, n
  8537. );
  8538. }
  8539. ggml_vk_ctx_end(subctx);
  8540. auto begin = std::chrono::high_resolution_clock::now();
  8541. ggml_vk_submit(subctx, ctx->fence);
  8542. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  8543. ctx->device->device.resetFences({ ctx->fence });
  8544. ggml_vk_queue_command_pools_cleanup(ctx->device);
  8545. auto end = std::chrono::high_resolution_clock::now();
  8546. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  8547. // copy dst to host
  8548. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  8549. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  8550. ggml_init_params iparams = {
  8551. /*.mem_size =*/ 1024*1024*1024,
  8552. /*.mem_buffer =*/ NULL,
  8553. /*.no_alloc =*/ true,
  8554. };
  8555. ggml_context * ggml_ctx = ggml_init(iparams);
  8556. ggml_type src0_type;
  8557. ggml_type src1_type;
  8558. if (std::is_same<float, X_TYPE>()) {
  8559. src0_type = GGML_TYPE_F32;
  8560. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  8561. src0_type = GGML_TYPE_F16;
  8562. } else {
  8563. GGML_ABORT("fatal error");
  8564. }
  8565. if (std::is_same<float, Y_TYPE>()) {
  8566. src1_type = GGML_TYPE_F32;
  8567. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8568. src1_type = GGML_TYPE_F16;
  8569. } else {
  8570. GGML_ABORT("fatal error");
  8571. }
  8572. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  8573. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  8574. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  8575. src0_ggml->data = x;
  8576. src1_ggml->data = y;
  8577. tensor_ggml->data = d_chk;
  8578. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  8579. ggml_build_forward_expand(cgraph, tensor_ggml);
  8580. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  8581. ggml_free(ggml_ctx);
  8582. double avg_err = 0.0;
  8583. int first_err_n = -1;
  8584. int first_err_m = -1;
  8585. int first_err_b = -1;
  8586. for (size_t i = 0; i < m*n*batch; i++) {
  8587. double err = std::fabs(d[i] - d_chk[i]);
  8588. avg_err += err;
  8589. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  8590. first_err_b = i / (m * n);
  8591. first_err_n = (i % (m * n)) / m;
  8592. first_err_m = (i % (m * n)) % m;
  8593. }
  8594. }
  8595. avg_err /= m * n;
  8596. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  8597. 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;
  8598. if (avg_err > 0.1 || std::isnan(avg_err)) {
  8599. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  8600. std::cerr << "Actual result: " << std::endl << std::endl;
  8601. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  8602. std::cerr << "Expected result: " << std::endl << std::endl;
  8603. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  8604. if (split_k > 1) {
  8605. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  8606. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  8607. std::cerr << "d_buf0: " << std::endl << std::endl;
  8608. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  8609. std::cerr << "d_buf1: " << std::endl << std::endl;
  8610. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  8611. std::cerr << "d_buf2: " << std::endl << std::endl;
  8612. 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);
  8613. std::cerr << "d_buf3: " << std::endl << std::endl;
  8614. 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);
  8615. free(split_k_buf);
  8616. }
  8617. }
  8618. free(d_chk);
  8619. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  8620. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  8621. ggml_vk_destroy_buffer(d_X);
  8622. ggml_vk_destroy_buffer(d_Y);
  8623. ggml_vk_destroy_buffer(d_D);
  8624. free(x);
  8625. free(y);
  8626. free(d);
  8627. }
  8628. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  8629. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  8630. return;
  8631. }
  8632. i0 = std::max(i0, 5);
  8633. i1 = std::max(i1, 5);
  8634. i2 = std::max(i2, 0);
  8635. i3 = std::max(i3, 0);
  8636. fprintf(stderr, " ");
  8637. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8638. fprintf(stderr, "%7d ", idx1);
  8639. }
  8640. fprintf(stderr, "\n");
  8641. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  8642. fprintf(stderr, "%7d: ", idx0);
  8643. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8644. 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]) {
  8645. float val;
  8646. if (tensor->type == GGML_TYPE_F32) {
  8647. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  8648. } else if (tensor->type == GGML_TYPE_F16) {
  8649. 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]));
  8650. } else {
  8651. GGML_ABORT("fatal error");
  8652. }
  8653. fprintf(stderr, "% 7.2f ", val);
  8654. } else {
  8655. fprintf(stderr, " ");
  8656. }
  8657. }
  8658. fprintf(stderr, "\n");
  8659. }
  8660. }
  8661. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  8662. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  8663. }
  8664. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  8665. if (quant == GGML_TYPE_F32) {
  8666. memcpy(to, from, sizeof(float) * ne);
  8667. return;
  8668. }
  8669. const auto * tt = ggml_get_type_traits(quant);
  8670. ggml_to_float_t dequant_fn = tt->to_float;
  8671. dequant_fn(from, to, ne);
  8672. }
  8673. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  8674. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  8675. const size_t x_sz = sizeof(float) * ne;
  8676. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  8677. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  8678. float * x = (float *) malloc(x_sz);
  8679. void * qx = malloc(qx_sz);
  8680. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8681. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8682. float * x_ref = (float *) malloc(x_sz);
  8683. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  8684. for (size_t i = 0; i < ne; i++) {
  8685. x[i] = rand() / (float)RAND_MAX;
  8686. }
  8687. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  8688. ggml_vk_quantize_data(x, qx, ne, quant);
  8689. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  8690. ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  8691. if (ctx->device->need_compiles) {
  8692. ggml_vk_load_shaders(ctx->device);
  8693. }
  8694. ggml_pipeline_allocate_descriptor_sets(ctx);
  8695. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  8696. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  8697. ggml_vk_ctx_begin(ctx->device, subctx);
  8698. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  8699. ggml_vk_dispatch_pipeline(ctx, subctx, p, { vk_subbuffer{ qx_buf, 0, qx_sz }, vk_subbuffer{ x_buf, 0, x_sz_f16 } }, pc, { (uint32_t)ne, 1, 1});
  8700. ggml_vk_ctx_end(subctx);
  8701. auto begin = std::chrono::high_resolution_clock::now();
  8702. ggml_vk_submit(subctx, ctx->fence);
  8703. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  8704. ctx->device->device.resetFences({ ctx->fence });
  8705. ggml_vk_queue_command_pools_cleanup(ctx->device);
  8706. auto end = std::chrono::high_resolution_clock::now();
  8707. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  8708. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  8709. int first_err = -1;
  8710. double avg_err = 0.0;
  8711. for (size_t i = 0; i < ne; i++) {
  8712. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  8713. avg_err += error;
  8714. if (first_err < 0 && error > 0.05) {
  8715. first_err = i;
  8716. }
  8717. }
  8718. avg_err /= ne;
  8719. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  8720. if (avg_err > 0.1) {
  8721. std::cerr << "first_error = " << first_err << std::endl;
  8722. std::cerr << "Actual result: " << std::endl << std::endl;
  8723. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  8724. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  8725. }
  8726. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  8727. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  8728. std::cerr << x_ref[i] << ", ";
  8729. }
  8730. std::cerr << std::endl;
  8731. }
  8732. ggml_vk_destroy_buffer(x_buf);
  8733. ggml_vk_destroy_buffer(qx_buf);
  8734. free(x);
  8735. free(qx);
  8736. free(x_ref);
  8737. free(x_chk);
  8738. }
  8739. // This does not work without ggml q8_1 quantization support
  8740. //
  8741. // typedef uint16_t ggml_half;
  8742. // typedef uint32_t ggml_half2;
  8743. //
  8744. // #define QK8_1 32
  8745. // typedef struct {
  8746. // union {
  8747. // struct {
  8748. // ggml_half d; // delta
  8749. // ggml_half s; // d * sum(qs[i])
  8750. // } GGML_COMMON_AGGR_S;
  8751. // ggml_half2 ds;
  8752. // } GGML_COMMON_AGGR_U;
  8753. // int8_t qs[QK8_1]; // quants
  8754. // } block_q8_1;
  8755. //
  8756. // static void ggml_vk_test_quantize(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  8757. // VK_LOG_DEBUG("ggml_vk_test_quantize(" << ne << ")");
  8758. // GGML_ASSERT(quant == GGML_TYPE_Q8_1);
  8759. //
  8760. // const size_t x_sz = sizeof(float) * ne;
  8761. // const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  8762. // float * x = (float *) malloc(x_sz);
  8763. // block_q8_1 * qx = (block_q8_1 *)malloc(qx_sz);
  8764. // block_q8_1 * qx_res = (block_q8_1 *)malloc(qx_sz);
  8765. // vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8766. // vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8767. //
  8768. // for (size_t i = 0; i < ne; i++) {
  8769. // x[i] = rand() / (float)RAND_MAX;
  8770. // }
  8771. //
  8772. // vk_pipeline p = ggml_vk_get_quantize_pipeline(ctx, quant);
  8773. //
  8774. // ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  8775. //
  8776. // if (ctx->device->need_compiles) {
  8777. // ggml_vk_load_shaders(ctx->device);
  8778. // }
  8779. //
  8780. // ggml_pipeline_allocate_descriptor_sets(ctx);
  8781. //
  8782. // ggml_vk_buffer_write(x_buf, 0, x, x_sz);
  8783. //
  8784. // vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  8785. // ggml_vk_ctx_begin(ctx->device, subctx);
  8786. // ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(x_buf), ggml_vk_subbuffer(qx_buf), ne);
  8787. // ggml_vk_ctx_end(subctx);
  8788. //
  8789. // auto begin = std::chrono::high_resolution_clock::now();
  8790. //
  8791. // ggml_vk_submit(subctx, ctx->fence);
  8792. // VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_quantize waitForFences");
  8793. // ctx->device->device.resetFences({ ctx->fence });
  8794. // ggml_vk_queue_command_pools_cleanup(ctx->device);
  8795. //
  8796. // auto end = std::chrono::high_resolution_clock::now();
  8797. //
  8798. // double ms_quant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  8799. // ggml_vk_buffer_read(qx_buf, 0, qx, qx_sz);
  8800. //
  8801. // ggml_vk_quantize_data(x, qx_res, ne, quant);
  8802. //
  8803. // int first_err = -1;
  8804. //
  8805. // for (size_t i = 0; i < ne / 32; i++) {
  8806. // double error = std::fabs(ggml_fp16_to_fp32(qx_res[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d) - ggml_fp16_to_fp32(qx[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d));
  8807. //
  8808. // if (first_err < 0 && error > 0.1) {
  8809. // first_err = i;
  8810. // }
  8811. //
  8812. // error = std::fabs(ggml_fp16_to_fp32(qx_res[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s) - ggml_fp16_to_fp32(qx[i].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s));
  8813. //
  8814. // if (first_err < 0 && error > 0.1) {
  8815. // first_err = i;
  8816. // }
  8817. //
  8818. // for (size_t j = 0; j < 32; j++) {
  8819. // uint64_t error = std::abs(qx_res[i].qs[j] - qx[i].qs[j]);
  8820. //
  8821. // if (first_err < 0 && error > 1) {
  8822. // first_err = i;
  8823. // }
  8824. // }
  8825. // }
  8826. //
  8827. // std::cerr << "TEST QUANTIZE " << ggml_type_name(quant) << " time=" << ms_quant << "ms " << (first_err == -1 ? "CORRECT" : "INCORRECT") << std::endl;
  8828. //
  8829. // if (first_err != -1) {
  8830. // std::cerr << "first_error = " << first_err << std::endl;
  8831. // std::cerr << "Actual result: " << std::endl << std::endl;
  8832. // std::cout << "d=" << ggml_fp16_to_fp32(qx[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d) << " s=" << ggml_fp16_to_fp32(qx[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s) << " ";
  8833. // for (size_t j = 0; j < 32; j++) {
  8834. // std::cout << " qs" << j << "=" << (uint32_t)qx[first_err].qs[j] << " ";
  8835. // }
  8836. // std::cerr << std::endl << std::endl << "Expected result: " << std::endl << std::endl;
  8837. // std::cout << "d=" << ggml_fp16_to_fp32(qx_res[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.d) << " s=" << ggml_fp16_to_fp32(qx_res[first_err].GGML_COMMON_AGGR_U.GGML_COMMON_AGGR_S.s) << " ";
  8838. // for (size_t j = 0; j < 32; j++) {
  8839. // std::cout << " qs" << j << "=" << (uint32_t)qx_res[first_err].qs[j] << " ";
  8840. // }
  8841. // std::cerr << std::endl;
  8842. // }
  8843. //
  8844. // ggml_vk_destroy_buffer(x_buf);
  8845. // ggml_vk_destroy_buffer(qx_buf);
  8846. //
  8847. // free(x);
  8848. // free(qx);
  8849. // free(qx_res);
  8850. // }
  8851. static void ggml_vk_test_dequant_matmul(ggml_backend_vk_context * ctx, size_t m, size_t n, size_t k, size_t batch, size_t num_it, size_t split_k, size_t shader_size, ggml_type quant, bool mmq = false) {
  8852. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  8853. const size_t x_ne = m * k * batch;
  8854. const size_t y_ne = k * n * batch;
  8855. const size_t d_ne = m * n * batch;
  8856. vk_matmul_pipeline2 * pipelines;
  8857. if (mmq) {
  8858. pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1;
  8859. } else {
  8860. pipelines = ctx->device->pipeline_dequant_mul_mat_mat;
  8861. }
  8862. const bool fp16acc = ctx->device->fp16;
  8863. vk_pipeline p;
  8864. std::string shname;
  8865. if (shader_size == 0) {
  8866. p = fp16acc ? pipelines[quant].f16acc->a_s : pipelines[quant].f32acc->a_s;
  8867. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  8868. } else if (shader_size == 1) {
  8869. p = fp16acc ? pipelines[quant].f16acc->a_m : pipelines[quant].f32acc->a_m;
  8870. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  8871. } else if (shader_size == 2) {
  8872. p = fp16acc ? pipelines[quant].f16acc->a_l : pipelines[quant].f32acc->a_l;
  8873. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  8874. } else {
  8875. GGML_ASSERT(0);
  8876. }
  8877. const size_t kpad = mmq ? 0 : ggml_vk_align_size(k, p->align);
  8878. if (mmq || k != kpad) {
  8879. if (shader_size == 0) {
  8880. p = fp16acc ? pipelines[quant].f16acc->s : pipelines[quant].f32acc->s;
  8881. shname = std::string(ggml_type_name(quant)) + "_S";
  8882. } else if (shader_size == 1) {
  8883. p = fp16acc ? pipelines[quant].f16acc->m : pipelines[quant].f32acc->m;
  8884. shname = std::string(ggml_type_name(quant)) + "_M";
  8885. } else if (shader_size == 2) {
  8886. p = fp16acc ? pipelines[quant].f16acc->l : pipelines[quant].f32acc->l;
  8887. shname = std::string(ggml_type_name(quant)) + "_L";
  8888. } else {
  8889. GGML_ASSERT(0);
  8890. }
  8891. }
  8892. if (p == nullptr) {
  8893. std::cerr << "error: no pipeline for ggml_vk_test_dequant_matmul " << ggml_type_name(quant) << std::endl;
  8894. return;
  8895. }
  8896. const size_t x_sz = sizeof(float) * x_ne;
  8897. const size_t y_sz = sizeof(float) * y_ne;
  8898. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  8899. const size_t qy_sz = mmq ? y_ne * ggml_type_size(GGML_TYPE_Q8_1)/ggml_blck_size(GGML_TYPE_Q8_1) : y_sz;
  8900. const size_t d_sz = sizeof(float) * d_ne;
  8901. float * x = (float *) malloc(x_sz);
  8902. float * y = (float *) malloc(y_sz);
  8903. void * qx = malloc(qx_sz);
  8904. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8905. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8906. vk_buffer qy_buf = ggml_vk_create_buffer_check(ctx->device, qy_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8907. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8908. float * d = (float *) malloc(d_sz);
  8909. float * d_chk = (float *) malloc(d_sz);
  8910. for (size_t i = 0; i < x_ne; i++) {
  8911. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  8912. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  8913. // x[i] = i % k;
  8914. }
  8915. ggml_vk_quantize_data(x, qx, x_ne, quant);
  8916. for (size_t i = 0; i < y_ne; i++) {
  8917. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  8918. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  8919. // y[i] = i % k;
  8920. }
  8921. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  8922. if (split_k > 1) {
  8923. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  8924. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  8925. // Resize buffer
  8926. if (ctx->prealloc_split_k != nullptr) {
  8927. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  8928. }
  8929. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8930. }
  8931. }
  8932. if (mmq) {
  8933. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_quantize_q8_1, num_it);
  8934. }
  8935. if (ctx->device->need_compiles) {
  8936. ggml_vk_load_shaders(ctx->device);
  8937. }
  8938. ggml_pipeline_allocate_descriptor_sets(ctx);
  8939. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  8940. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  8941. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  8942. ggml_vk_ctx_begin(ctx->device, subctx);
  8943. if (mmq) {
  8944. for (size_t i = 0; i < num_it; i++) {
  8945. ggml_vk_quantize_q8_1(ctx, subctx, { y_buf, 0, y_sz }, { qy_buf, 0, qy_sz }, y_ne);
  8946. ggml_vk_matmul(
  8947. ctx, subctx, p, { qx_buf, 0, qx_sz }, { qy_buf, 0, qy_sz }, { d_buf, 0, d_sz }, { ctx->prealloc_split_k, 0, ctx->prealloc_size_split_k },
  8948. m, n, k,
  8949. k, k, m, k*m, k*n, m*n,
  8950. split_k, batch, batch, batch, 1, 1, n
  8951. );
  8952. }
  8953. } else {
  8954. for (size_t i = 0; i < num_it; i++) {
  8955. ggml_vk_matmul(
  8956. ctx, subctx, p, { qx_buf, 0, qx_sz }, { y_buf, 0, y_sz }, { d_buf, 0, d_sz }, { ctx->prealloc_split_k, 0, ctx->prealloc_size_split_k },
  8957. m, n, k,
  8958. k, k, m, k*m, k*n, m*n,
  8959. split_k, batch, batch, batch, 1, 1, n
  8960. );
  8961. }
  8962. }
  8963. ggml_vk_ctx_end(subctx);
  8964. auto begin = std::chrono::high_resolution_clock::now();
  8965. ggml_vk_submit(subctx, ctx->fence);
  8966. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  8967. ctx->device->device.resetFences({ ctx->fence });
  8968. ggml_vk_queue_command_pools_cleanup(ctx->device);
  8969. auto end = std::chrono::high_resolution_clock::now();
  8970. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  8971. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  8972. ggml_init_params iparams = {
  8973. /*.mem_size =*/ 1024*1024*1024,
  8974. /*.mem_buffer =*/ NULL,
  8975. /*.no_alloc =*/ true,
  8976. };
  8977. ggml_context * ggml_ctx = ggml_init(iparams);
  8978. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  8979. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  8980. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  8981. src0_ggml->data = qx;
  8982. src1_ggml->data = y;
  8983. tensor_ggml->data = d_chk;
  8984. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  8985. ggml_build_forward_expand(cgraph, tensor_ggml);
  8986. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  8987. ggml_free(ggml_ctx);
  8988. double avg_err = 0.0;
  8989. int first_err_n = -1;
  8990. int first_err_m = -1;
  8991. int first_err_b = -1;
  8992. for (size_t i = 0; i < m*n*batch; i++) {
  8993. double err = std::fabs(d[i] - d_chk[i]);
  8994. avg_err += err;
  8995. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  8996. first_err_b = i / (m * n);
  8997. first_err_n = (i % (m * n)) / m;
  8998. first_err_m = (i % (m * n)) % m;
  8999. }
  9000. }
  9001. avg_err /= m * n;
  9002. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9003. std::cerr << "TEST dequant matmul " << shname;
  9004. if (mmq) {
  9005. std::cerr << " mmq";
  9006. }
  9007. std::cerr << " m=" << m << " n=" << n << " k=" << k << " batch=" << batch << " split_k=" << split_k << " matmul " << time_ms / num_it << "ms " << tflops << " TFLOPS avg_err=" << avg_err << std::endl;
  9008. if (avg_err > 0.01 || std::isnan(avg_err)) {
  9009. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9010. std::cerr << "Actual result: " << std::endl << std::endl;
  9011. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9012. std::cerr << std::endl;
  9013. std::cerr << "Expected result: " << std::endl << std::endl;
  9014. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9015. std::cerr << "src0: " << std::endl << std::endl;
  9016. ggml_vk_print_matrix_area(x, GGML_TYPE_F32, k, m, first_err_m, first_err_n, first_err_b);
  9017. std::cerr << std::endl;
  9018. std::cerr << "src1: " << std::endl << std::endl;
  9019. ggml_vk_print_matrix_area(y, GGML_TYPE_F32, k, n, first_err_m, first_err_n, first_err_b);
  9020. if (split_k > 1) {
  9021. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9022. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9023. std::cerr << "d_buf0: " << std::endl << std::endl;
  9024. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9025. std::cerr << "d_buf1: " << std::endl << std::endl;
  9026. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9027. std::cerr << "d_buf2: " << std::endl << std::endl;
  9028. 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);
  9029. std::cerr << "d_buf3: " << std::endl << std::endl;
  9030. 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);
  9031. free(split_k_buf);
  9032. }
  9033. }
  9034. ggml_vk_destroy_buffer(qx_buf);
  9035. ggml_vk_destroy_buffer(y_buf);
  9036. ggml_vk_destroy_buffer(qy_buf);
  9037. ggml_vk_destroy_buffer(d_buf);
  9038. free(x);
  9039. free(qx);
  9040. free(y);
  9041. free(d);
  9042. free(d_chk);
  9043. }
  9044. #endif
  9045. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx) {
  9046. #if defined(GGML_VULKAN_RUN_TESTS)
  9047. const std::vector<size_t> vals {
  9048. 512, 512, 128,
  9049. 128, 512, 512,
  9050. 4096, 512, 4096,
  9051. 11008, 512, 4096,
  9052. 4096, 512, 11008,
  9053. 32000, 512, 4096,
  9054. 8, 8, 8,
  9055. 100, 46, 576,
  9056. 623, 111, 128,
  9057. 100, 46, 558,
  9058. 512, 1, 256,
  9059. 128, 110, 622,
  9060. 511, 511, 127,
  9061. 511, 511, 7,
  9062. 511, 511, 17,
  9063. 49, 49, 128,
  9064. 128, 49, 49,
  9065. 4096, 49, 4096,
  9066. };
  9067. const size_t num_it = 100;
  9068. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9069. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9070. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9071. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true);
  9072. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true);
  9073. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true);
  9074. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0);
  9075. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0);
  9076. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0);
  9077. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true);
  9078. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true);
  9079. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true);
  9080. abort();
  9081. for (size_t i = 0; i < vals.size(); i += 3) {
  9082. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  9083. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  9084. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  9085. std::cerr << '\n';
  9086. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  9087. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  9088. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  9089. std::cerr << '\n';
  9090. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  9091. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  9092. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  9093. std::cerr << '\n' << std::endl;
  9094. if (vals[i + 2] % 32 == 0) {
  9095. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9096. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9097. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9098. std::cerr << '\n';
  9099. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  9100. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  9101. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  9102. std::cerr << '\n';
  9103. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  9104. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  9105. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  9106. std::cerr << '\n' << std::endl;
  9107. }
  9108. if (vals[i + 2] % 256 == 0) {
  9109. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  9110. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  9111. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  9112. std::cerr << '\n';
  9113. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  9114. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  9115. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  9116. std::cerr << '\n';
  9117. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  9118. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  9119. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  9120. std::cerr << '\n' << std::endl;
  9121. }
  9122. }
  9123. GGML_ABORT("fatal error");
  9124. #endif
  9125. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  9126. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  9127. // Resize buffer
  9128. if (ctx->prealloc_x != nullptr) {
  9129. ggml_vk_destroy_buffer(ctx->prealloc_x);
  9130. }
  9131. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  9132. }
  9133. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  9134. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  9135. // Resize buffer
  9136. if (ctx->prealloc_y != nullptr) {
  9137. ggml_vk_destroy_buffer(ctx->prealloc_y);
  9138. }
  9139. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  9140. }
  9141. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  9142. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  9143. // Resize buffer
  9144. if (ctx->prealloc_split_k != nullptr) {
  9145. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9146. }
  9147. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  9148. }
  9149. if (ctx->prealloc_add_rms_partials == nullptr || (ctx->prealloc_size_add_rms_partials > 0 && ctx->prealloc_add_rms_partials->size < ctx->prealloc_size_add_rms_partials)) {
  9150. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")");
  9151. // Resize buffer
  9152. if (ctx->prealloc_add_rms_partials != nullptr) {
  9153. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  9154. }
  9155. ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials);
  9156. }
  9157. }
  9158. static bool ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_cgraph * cgraph, ggml_tensor* tensor, int tensor_idx, bool use_fence, bool almost_ready);
  9159. // Returns true if node has enqueued work into the queue, false otherwise
  9160. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  9161. static bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int node_idx, ggml_tensor *node_begin, int node_idx_begin, bool dryrun, bool last_node, bool almost_ready, bool submit){
  9162. ggml_tensor * node = cgraph->nodes[node_idx];
  9163. if (ggml_is_empty(node) || !node->buffer) {
  9164. return false;
  9165. }
  9166. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  9167. ctx->semaphore_idx = 0;
  9168. const ggml_tensor * src0 = node->src[0];
  9169. const ggml_tensor * src1 = node->src[1];
  9170. const ggml_tensor * src2 = node->src[2];
  9171. const ggml_tensor * src3 = node->src[3];
  9172. switch (node->op) {
  9173. // Return on empty ops to avoid generating a compute_ctx and setting exit_tensor
  9174. case GGML_OP_RESHAPE:
  9175. case GGML_OP_VIEW:
  9176. case GGML_OP_PERMUTE:
  9177. case GGML_OP_TRANSPOSE:
  9178. case GGML_OP_NONE:
  9179. return false;
  9180. case GGML_OP_UNARY:
  9181. switch (ggml_get_unary_op(node)) {
  9182. case GGML_UNARY_OP_EXP:
  9183. case GGML_UNARY_OP_SILU:
  9184. case GGML_UNARY_OP_GELU:
  9185. case GGML_UNARY_OP_GELU_ERF:
  9186. case GGML_UNARY_OP_GELU_QUICK:
  9187. case GGML_UNARY_OP_RELU:
  9188. case GGML_UNARY_OP_TANH:
  9189. case GGML_UNARY_OP_SIGMOID:
  9190. case GGML_UNARY_OP_HARDSIGMOID:
  9191. case GGML_UNARY_OP_HARDSWISH:
  9192. break;
  9193. default:
  9194. return false;
  9195. }
  9196. break;
  9197. case GGML_OP_GLU:
  9198. switch (ggml_get_glu_op(node)) {
  9199. case GGML_GLU_OP_GEGLU:
  9200. case GGML_GLU_OP_REGLU:
  9201. case GGML_GLU_OP_SWIGLU:
  9202. case GGML_GLU_OP_SWIGLU_OAI:
  9203. case GGML_GLU_OP_GEGLU_ERF:
  9204. case GGML_GLU_OP_GEGLU_QUICK:
  9205. break;
  9206. default:
  9207. return false;
  9208. }
  9209. break;
  9210. case GGML_OP_ADD:
  9211. {
  9212. int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops;
  9213. if (next_node_idx < cgraph->n_nodes &&
  9214. cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM &&
  9215. cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] &&
  9216. ggml_nrows(cgraph->nodes[next_node_idx]) == 1 &&
  9217. ctx->device->add_rms_fusion) {
  9218. if (dryrun) {
  9219. ctx->prealloc_size_add_rms_partials += ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]);
  9220. }
  9221. ctx->do_add_rms_partials = true;
  9222. }
  9223. } break;
  9224. case GGML_OP_REPEAT:
  9225. case GGML_OP_REPEAT_BACK:
  9226. case GGML_OP_GET_ROWS:
  9227. case GGML_OP_ADD_ID:
  9228. case GGML_OP_ACC:
  9229. case GGML_OP_SUB:
  9230. case GGML_OP_MUL:
  9231. case GGML_OP_DIV:
  9232. case GGML_OP_CONCAT:
  9233. case GGML_OP_UPSCALE:
  9234. case GGML_OP_SCALE:
  9235. case GGML_OP_SQR:
  9236. case GGML_OP_SQRT:
  9237. case GGML_OP_SIN:
  9238. case GGML_OP_COS:
  9239. case GGML_OP_CLAMP:
  9240. case GGML_OP_PAD:
  9241. case GGML_OP_ROLL:
  9242. case GGML_OP_CPY:
  9243. case GGML_OP_SET_ROWS:
  9244. case GGML_OP_CONT:
  9245. case GGML_OP_DUP:
  9246. case GGML_OP_SILU_BACK:
  9247. case GGML_OP_NORM:
  9248. case GGML_OP_GROUP_NORM:
  9249. case GGML_OP_RMS_NORM:
  9250. case GGML_OP_RMS_NORM_BACK:
  9251. case GGML_OP_L2_NORM:
  9252. case GGML_OP_DIAG_MASK_INF:
  9253. case GGML_OP_SOFT_MAX:
  9254. case GGML_OP_SOFT_MAX_BACK:
  9255. case GGML_OP_ROPE:
  9256. case GGML_OP_ROPE_BACK:
  9257. case GGML_OP_MUL_MAT:
  9258. case GGML_OP_MUL_MAT_ID:
  9259. case GGML_OP_ARGSORT:
  9260. case GGML_OP_SUM:
  9261. case GGML_OP_SUM_ROWS:
  9262. case GGML_OP_MEAN:
  9263. case GGML_OP_ARGMAX:
  9264. case GGML_OP_COUNT_EQUAL:
  9265. case GGML_OP_IM2COL:
  9266. case GGML_OP_IM2COL_3D:
  9267. case GGML_OP_TIMESTEP_EMBEDDING:
  9268. case GGML_OP_CONV_TRANSPOSE_1D:
  9269. case GGML_OP_POOL_2D:
  9270. case GGML_OP_CONV_2D:
  9271. case GGML_OP_CONV_TRANSPOSE_2D:
  9272. case GGML_OP_CONV_2D_DW:
  9273. case GGML_OP_RWKV_WKV6:
  9274. case GGML_OP_RWKV_WKV7:
  9275. case GGML_OP_LEAKY_RELU:
  9276. case GGML_OP_FLASH_ATTN_EXT:
  9277. case GGML_OP_OPT_STEP_ADAMW:
  9278. case GGML_OP_OPT_STEP_SGD:
  9279. break;
  9280. default:
  9281. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(node->op) << std::endl;
  9282. GGML_ABORT("fatal error");
  9283. }
  9284. vk_context compute_ctx;
  9285. if (!dryrun) {
  9286. if (ctx->compute_ctx.expired()) {
  9287. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9288. ctx->compute_ctx = compute_ctx;
  9289. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  9290. } else {
  9291. compute_ctx = ctx->compute_ctx.lock();
  9292. }
  9293. } else {
  9294. switch (node->op) {
  9295. case GGML_OP_REPEAT:
  9296. case GGML_OP_REPEAT_BACK:
  9297. case GGML_OP_ACC:
  9298. case GGML_OP_GET_ROWS:
  9299. case GGML_OP_ADD:
  9300. case GGML_OP_SUB:
  9301. case GGML_OP_MUL:
  9302. case GGML_OP_DIV:
  9303. case GGML_OP_CONCAT:
  9304. case GGML_OP_UPSCALE:
  9305. case GGML_OP_SCALE:
  9306. case GGML_OP_SQR:
  9307. case GGML_OP_SQRT:
  9308. case GGML_OP_SIN:
  9309. case GGML_OP_COS:
  9310. case GGML_OP_CLAMP:
  9311. case GGML_OP_PAD:
  9312. case GGML_OP_CPY:
  9313. case GGML_OP_SET_ROWS:
  9314. case GGML_OP_CONT:
  9315. case GGML_OP_DUP:
  9316. case GGML_OP_SILU_BACK:
  9317. case GGML_OP_NORM:
  9318. case GGML_OP_GROUP_NORM:
  9319. case GGML_OP_RMS_NORM:
  9320. case GGML_OP_RMS_NORM_BACK:
  9321. case GGML_OP_L2_NORM:
  9322. case GGML_OP_UNARY:
  9323. case GGML_OP_GLU:
  9324. case GGML_OP_DIAG_MASK_INF:
  9325. case GGML_OP_SOFT_MAX:
  9326. case GGML_OP_SOFT_MAX_BACK:
  9327. case GGML_OP_ROPE:
  9328. case GGML_OP_ROPE_BACK:
  9329. case GGML_OP_ARGSORT:
  9330. case GGML_OP_SUM:
  9331. case GGML_OP_SUM_ROWS:
  9332. case GGML_OP_MEAN:
  9333. case GGML_OP_ARGMAX:
  9334. case GGML_OP_COUNT_EQUAL:
  9335. case GGML_OP_IM2COL:
  9336. case GGML_OP_IM2COL_3D:
  9337. case GGML_OP_TIMESTEP_EMBEDDING:
  9338. case GGML_OP_CONV_TRANSPOSE_1D:
  9339. case GGML_OP_POOL_2D:
  9340. case GGML_OP_CONV_2D:
  9341. case GGML_OP_CONV_TRANSPOSE_2D:
  9342. case GGML_OP_CONV_2D_DW:
  9343. case GGML_OP_LEAKY_RELU:
  9344. case GGML_OP_OPT_STEP_SGD:
  9345. {
  9346. // These operations all go through ggml_vk_op_f32, so short-circuit and
  9347. // do the only thing needed for the dryrun.
  9348. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, node, node->op);
  9349. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9350. if (node->op == GGML_OP_RMS_NORM) {
  9351. ctx->do_add_rms_partials = false;
  9352. }
  9353. return false;
  9354. }
  9355. default:
  9356. break;
  9357. }
  9358. }
  9359. if (!dryrun) {
  9360. // This logic detects dependencies between modes in the graph and calls ggml_vk_sync_buffers
  9361. // to synchronize them. This handles most "normal" synchronization when computing the graph, and when
  9362. // there is no auxiliary memory use, it shouldn't be necessary to call ggml_vk_sync_buffers
  9363. // outside of this logic. When a node uses one of the prealloc buffers for something like
  9364. // dequantization or split_k, additional synchronization is needed between those passes.
  9365. bool need_sync = false;
  9366. // Check whether "node" requires synchronization. The node requires synchronization if it
  9367. // overlaps in memory with another unsynchronized node and at least one of them is a write.
  9368. // Destination nodes are checked against both the written/read lists. Source nodes are only
  9369. // checked against the written list. Two nodes overlap in memory if they come from the same
  9370. // buffer and the tensor or view ranges overlap.
  9371. auto const &overlaps_unsynced = [&](const ggml_tensor *node, const std::vector<const ggml_tensor *> &unsynced_nodes) -> bool {
  9372. if (unsynced_nodes.size() == 0) {
  9373. return false;
  9374. }
  9375. auto n_base = vk_tensor_offset(node) + node->view_offs;
  9376. auto n_size = ggml_nbytes(node);
  9377. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context;
  9378. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  9379. for (auto &other : unsynced_nodes) {
  9380. ggml_backend_vk_buffer_context * o_buf_ctx = (ggml_backend_vk_buffer_context *)other->buffer->context;
  9381. vk_buffer o_buf = o_buf_ctx->dev_buffer;
  9382. if (a_buf == o_buf) {
  9383. auto o_base = vk_tensor_offset(other) + other->view_offs;
  9384. auto o_size = ggml_nbytes(other);
  9385. if ((o_base <= n_base && n_base < o_base + o_size) ||
  9386. (n_base <= o_base && o_base < n_base + n_size)) {
  9387. return true;
  9388. }
  9389. }
  9390. }
  9391. return false;
  9392. };
  9393. // For all fused ops, check if the destination node or any of the source
  9394. // nodes require synchronization.
  9395. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) {
  9396. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  9397. if (overlaps_unsynced(cur_node, ctx->unsynced_nodes_read) || overlaps_unsynced(cur_node, ctx->unsynced_nodes_written)) {
  9398. need_sync = true;
  9399. break;
  9400. }
  9401. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  9402. if (!cur_node->src[j]) {
  9403. continue;
  9404. }
  9405. if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) {
  9406. need_sync = true;
  9407. break;
  9408. }
  9409. }
  9410. }
  9411. if (need_sync) {
  9412. ctx->unsynced_nodes_written.clear();
  9413. ctx->unsynced_nodes_read.clear();
  9414. ggml_vk_sync_buffers(ctx, compute_ctx);
  9415. }
  9416. // Add the last fused node and all fused source nodes to the unsynchronized list.
  9417. const ggml_tensor * last_node = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  9418. ctx->unsynced_nodes_written.push_back(last_node);
  9419. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  9420. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  9421. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  9422. if (!cur_node->src[j]) {
  9423. continue;
  9424. }
  9425. ctx->unsynced_nodes_read.push_back(cur_node->src[j]);
  9426. }
  9427. }
  9428. }
  9429. switch (node->op) {
  9430. case GGML_OP_REPEAT:
  9431. ggml_vk_repeat(ctx, compute_ctx, src0, node, dryrun);
  9432. break;
  9433. case GGML_OP_REPEAT_BACK:
  9434. ggml_vk_repeat_back(ctx, compute_ctx, src0, node, dryrun);
  9435. break;
  9436. case GGML_OP_ACC:
  9437. ggml_vk_acc(ctx, compute_ctx, src0, src1, node, dryrun);
  9438. break;
  9439. case GGML_OP_GET_ROWS:
  9440. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node, dryrun);
  9441. break;
  9442. case GGML_OP_ADD:
  9443. if (ctx->num_additional_fused_ops) {
  9444. ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx, dryrun);
  9445. } else {
  9446. ggml_vk_add(ctx, compute_ctx, src0, src1, node, dryrun);
  9447. }
  9448. break;
  9449. case GGML_OP_SUB:
  9450. ggml_vk_sub(ctx, compute_ctx, src0, src1, node, dryrun);
  9451. break;
  9452. case GGML_OP_MUL:
  9453. ggml_vk_mul(ctx, compute_ctx, src0, src1, node, dryrun);
  9454. break;
  9455. case GGML_OP_DIV:
  9456. ggml_vk_div(ctx, compute_ctx, src0, src1, node, dryrun);
  9457. break;
  9458. case GGML_OP_ADD_ID:
  9459. ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  9460. break;
  9461. case GGML_OP_CONCAT:
  9462. ggml_vk_concat(ctx, compute_ctx, src0, src1, node, dryrun);
  9463. break;
  9464. case GGML_OP_UPSCALE:
  9465. ggml_vk_upscale(ctx, compute_ctx, src0, node, dryrun);
  9466. break;
  9467. case GGML_OP_SCALE:
  9468. ggml_vk_scale(ctx, compute_ctx, src0, node, dryrun);
  9469. break;
  9470. case GGML_OP_SQR:
  9471. ggml_vk_sqr(ctx, compute_ctx, src0, node, dryrun);
  9472. break;
  9473. case GGML_OP_SQRT:
  9474. ggml_vk_sqrt(ctx, compute_ctx, src0, node, dryrun);
  9475. break;
  9476. case GGML_OP_SIN:
  9477. ggml_vk_sin(ctx, compute_ctx, src0, node, dryrun);
  9478. break;
  9479. case GGML_OP_COS:
  9480. ggml_vk_cos(ctx, compute_ctx, src0, node, dryrun);
  9481. break;
  9482. case GGML_OP_CLAMP:
  9483. ggml_vk_clamp(ctx, compute_ctx, src0, node, dryrun);
  9484. break;
  9485. case GGML_OP_PAD:
  9486. ggml_vk_pad(ctx, compute_ctx, src0, node, dryrun);
  9487. break;
  9488. case GGML_OP_ROLL:
  9489. ggml_vk_roll(ctx, compute_ctx, src0, node, dryrun);
  9490. break;
  9491. case GGML_OP_CPY:
  9492. case GGML_OP_CONT:
  9493. case GGML_OP_DUP:
  9494. ggml_vk_cpy(ctx, compute_ctx, src0, node, dryrun);
  9495. break;
  9496. case GGML_OP_SET_ROWS:
  9497. ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node, dryrun);
  9498. break;
  9499. case GGML_OP_SILU_BACK:
  9500. ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node, dryrun);
  9501. break;
  9502. case GGML_OP_NORM:
  9503. ggml_vk_norm(ctx, compute_ctx, src0, node, dryrun);
  9504. break;
  9505. case GGML_OP_GROUP_NORM:
  9506. ggml_vk_group_norm(ctx, compute_ctx, src0, node, dryrun);
  9507. break;
  9508. case GGML_OP_RMS_NORM:
  9509. if (ctx->num_additional_fused_ops > 0) {
  9510. // fused rms_norm + mul
  9511. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  9512. ggml_tensor *other_src = mul->src[0] == node ? mul->src[1] : mul->src[0];
  9513. ggml_vk_rms_norm(ctx, compute_ctx, src0, other_src, mul, (float *)node->op_params, dryrun);
  9514. } else {
  9515. ggml_vk_rms_norm(ctx, compute_ctx, src0, src0, node, (float *)node->op_params, dryrun);
  9516. }
  9517. break;
  9518. case GGML_OP_RMS_NORM_BACK:
  9519. ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node, dryrun);
  9520. break;
  9521. case GGML_OP_L2_NORM:
  9522. ggml_vk_l2_norm(ctx, compute_ctx, src0, node, dryrun);
  9523. break;
  9524. case GGML_OP_UNARY:
  9525. switch (ggml_get_unary_op(node)) {
  9526. case GGML_UNARY_OP_EXP:
  9527. case GGML_UNARY_OP_SILU:
  9528. case GGML_UNARY_OP_GELU:
  9529. case GGML_UNARY_OP_GELU_ERF:
  9530. case GGML_UNARY_OP_GELU_QUICK:
  9531. case GGML_UNARY_OP_RELU:
  9532. case GGML_UNARY_OP_TANH:
  9533. case GGML_UNARY_OP_SIGMOID:
  9534. case GGML_UNARY_OP_HARDSIGMOID:
  9535. case GGML_UNARY_OP_HARDSWISH:
  9536. ggml_vk_unary(ctx, compute_ctx, src0, node, dryrun);
  9537. break;
  9538. default:
  9539. return false;
  9540. }
  9541. break;
  9542. case GGML_OP_GLU:
  9543. switch (ggml_get_glu_op(node)) {
  9544. case GGML_GLU_OP_GEGLU:
  9545. case GGML_GLU_OP_REGLU:
  9546. case GGML_GLU_OP_SWIGLU:
  9547. case GGML_GLU_OP_SWIGLU_OAI:
  9548. case GGML_GLU_OP_GEGLU_ERF:
  9549. case GGML_GLU_OP_GEGLU_QUICK:
  9550. ggml_vk_glu(ctx, compute_ctx, src0, src1, node, dryrun);
  9551. break;
  9552. default:
  9553. return false;
  9554. }
  9555. break;
  9556. case GGML_OP_DIAG_MASK_INF:
  9557. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node, dryrun);
  9558. break;
  9559. case GGML_OP_SOFT_MAX:
  9560. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  9561. break;
  9562. case GGML_OP_SOFT_MAX_BACK:
  9563. ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node, dryrun);
  9564. break;
  9565. case GGML_OP_ROPE:
  9566. ggml_vk_rope(ctx, compute_ctx, src0, src1, src2, node, false, dryrun);
  9567. break;
  9568. case GGML_OP_ROPE_BACK:
  9569. ggml_vk_rope(ctx, compute_ctx, src0, src1, src2, node, true, dryrun);
  9570. break;
  9571. case GGML_OP_ARGSORT:
  9572. ggml_vk_argsort(ctx, compute_ctx, src0, node, dryrun);
  9573. break;
  9574. case GGML_OP_SUM:
  9575. ggml_vk_sum(ctx, compute_ctx, src0, node, dryrun);
  9576. break;
  9577. case GGML_OP_SUM_ROWS:
  9578. ggml_vk_sum_rows(ctx, compute_ctx, src0, node, dryrun);
  9579. break;
  9580. case GGML_OP_MEAN:
  9581. ggml_vk_mean(ctx, compute_ctx, src0, node, dryrun);
  9582. break;
  9583. case GGML_OP_ARGMAX:
  9584. ggml_vk_argmax(ctx, compute_ctx, src0, node, dryrun);
  9585. break;
  9586. case GGML_OP_COUNT_EQUAL:
  9587. ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node, dryrun);
  9588. break;
  9589. case GGML_OP_IM2COL:
  9590. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node, dryrun);
  9591. break;
  9592. case GGML_OP_IM2COL_3D:
  9593. ggml_vk_im2col_3d(ctx, compute_ctx, src0, src1, node, dryrun);
  9594. break;
  9595. case GGML_OP_TIMESTEP_EMBEDDING:
  9596. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node, dryrun);
  9597. break;
  9598. case GGML_OP_CONV_TRANSPOSE_1D:
  9599. ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node, dryrun);
  9600. break;
  9601. case GGML_OP_POOL_2D:
  9602. ggml_vk_pool_2d(ctx, compute_ctx, src0, node, dryrun);
  9603. break;
  9604. case GGML_OP_CONV_2D:
  9605. ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node, dryrun);
  9606. break;
  9607. case GGML_OP_CONV_TRANSPOSE_2D:
  9608. ggml_vk_conv_transpose_2d(ctx, compute_ctx, src0, src1, node, dryrun);
  9609. break;
  9610. case GGML_OP_CONV_2D_DW:
  9611. ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node, dryrun);
  9612. break;
  9613. case GGML_OP_LEAKY_RELU:
  9614. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node, dryrun);
  9615. break;
  9616. case GGML_OP_MUL_MAT:
  9617. ggml_vk_mul_mat(ctx, compute_ctx, src0, src1, node, dryrun);
  9618. break;
  9619. case GGML_OP_MUL_MAT_ID:
  9620. ggml_vk_mul_mat_id(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  9621. break;
  9622. case GGML_OP_FLASH_ATTN_EXT:
  9623. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node, dryrun);
  9624. break;
  9625. case GGML_OP_RWKV_WKV6:
  9626. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node, dryrun);
  9627. break;
  9628. case GGML_OP_RWKV_WKV7:
  9629. ggml_vk_rwkv_wkv7(ctx, compute_ctx, node, dryrun);
  9630. break;
  9631. case GGML_OP_OPT_STEP_ADAMW:
  9632. ggml_vk_opt_step_adamw(ctx, compute_ctx, node, dryrun);
  9633. break;
  9634. case GGML_OP_OPT_STEP_SGD:
  9635. ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  9636. break;
  9637. default:
  9638. return false;
  9639. }
  9640. if (dryrun) {
  9641. return false;
  9642. }
  9643. ctx->tensor_ctxs[node_idx] = compute_ctx;
  9644. #if defined(GGML_VULKAN_CHECK_RESULTS)
  9645. // Force context reset on each node so that each tensor ends up in its own context
  9646. // and can be run and compared to its CPU equivalent separately
  9647. last_node = true;
  9648. #endif
  9649. if (submit || last_node) {
  9650. ggml_vk_ctx_end(compute_ctx);
  9651. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  9652. if (last_node) {
  9653. compute_ctx->exit_tensor_idx = node_idx_begin;
  9654. }
  9655. else {
  9656. compute_ctx->exit_tensor_idx = -1;
  9657. }
  9658. ctx->compute_ctx.reset();
  9659. bool ok = ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, false, almost_ready);
  9660. if (!ok) {
  9661. if (node->op == GGML_OP_UNARY) {
  9662. 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;
  9663. } else if (node->op == GGML_OP_GLU) {
  9664. std::cerr << __func__ << ": error: op not supported GLU " << node->name << " (" << ggml_glu_op_name(static_cast<ggml_glu_op>(node->op_params[0])) << ")" << std::endl;
  9665. } else {
  9666. std::cerr << __func__ << ": error: op not supported " << node->name << " (" << ggml_op_name(node->op) << ")" << std::endl;
  9667. }
  9668. }
  9669. }
  9670. return true;
  9671. }
  9672. static bool ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, ggml_tensor * tensor, int tensor_idx, bool use_fence = true, bool almost_ready = false) {
  9673. GGML_UNUSED(cgraph);
  9674. ggml_backend_buffer * buf = nullptr;
  9675. switch (tensor->op) {
  9676. case GGML_OP_ADD:
  9677. case GGML_OP_ACC:
  9678. case GGML_OP_GET_ROWS:
  9679. case GGML_OP_SUB:
  9680. case GGML_OP_MUL:
  9681. case GGML_OP_DIV:
  9682. case GGML_OP_ADD_ID:
  9683. case GGML_OP_CONCAT:
  9684. case GGML_OP_UPSCALE:
  9685. case GGML_OP_SCALE:
  9686. case GGML_OP_SQR:
  9687. case GGML_OP_SQRT:
  9688. case GGML_OP_SIN:
  9689. case GGML_OP_COS:
  9690. case GGML_OP_CLAMP:
  9691. case GGML_OP_PAD:
  9692. case GGML_OP_ROLL:
  9693. case GGML_OP_CPY:
  9694. case GGML_OP_SET_ROWS:
  9695. case GGML_OP_CONT:
  9696. case GGML_OP_DUP:
  9697. case GGML_OP_SILU_BACK:
  9698. case GGML_OP_NORM:
  9699. case GGML_OP_GROUP_NORM:
  9700. case GGML_OP_RMS_NORM:
  9701. case GGML_OP_RMS_NORM_BACK:
  9702. case GGML_OP_L2_NORM:
  9703. case GGML_OP_DIAG_MASK_INF:
  9704. case GGML_OP_SOFT_MAX:
  9705. case GGML_OP_SOFT_MAX_BACK:
  9706. case GGML_OP_ROPE:
  9707. case GGML_OP_ROPE_BACK:
  9708. case GGML_OP_RESHAPE:
  9709. case GGML_OP_VIEW:
  9710. case GGML_OP_PERMUTE:
  9711. case GGML_OP_TRANSPOSE:
  9712. case GGML_OP_NONE:
  9713. case GGML_OP_ARGSORT:
  9714. case GGML_OP_SUM:
  9715. case GGML_OP_SUM_ROWS:
  9716. case GGML_OP_MEAN:
  9717. case GGML_OP_ARGMAX:
  9718. case GGML_OP_COUNT_EQUAL:
  9719. case GGML_OP_IM2COL:
  9720. case GGML_OP_IM2COL_3D:
  9721. case GGML_OP_TIMESTEP_EMBEDDING:
  9722. case GGML_OP_CONV_TRANSPOSE_1D:
  9723. case GGML_OP_POOL_2D:
  9724. case GGML_OP_CONV_2D:
  9725. case GGML_OP_CONV_TRANSPOSE_2D:
  9726. case GGML_OP_CONV_2D_DW:
  9727. case GGML_OP_RWKV_WKV6:
  9728. case GGML_OP_RWKV_WKV7:
  9729. case GGML_OP_LEAKY_RELU:
  9730. case GGML_OP_REPEAT:
  9731. case GGML_OP_REPEAT_BACK:
  9732. case GGML_OP_OPT_STEP_ADAMW:
  9733. case GGML_OP_OPT_STEP_SGD:
  9734. buf = tensor->buffer;
  9735. break;
  9736. case GGML_OP_UNARY:
  9737. switch (ggml_get_unary_op(tensor)) {
  9738. case GGML_UNARY_OP_EXP:
  9739. case GGML_UNARY_OP_SILU:
  9740. case GGML_UNARY_OP_GELU:
  9741. case GGML_UNARY_OP_GELU_ERF:
  9742. case GGML_UNARY_OP_GELU_QUICK:
  9743. case GGML_UNARY_OP_RELU:
  9744. case GGML_UNARY_OP_TANH:
  9745. case GGML_UNARY_OP_SIGMOID:
  9746. case GGML_UNARY_OP_HARDSIGMOID:
  9747. case GGML_UNARY_OP_HARDSWISH:
  9748. buf = tensor->buffer;
  9749. break;
  9750. default:
  9751. return false;
  9752. }
  9753. break;
  9754. case GGML_OP_GLU:
  9755. switch (ggml_get_glu_op(tensor)) {
  9756. case GGML_GLU_OP_GEGLU:
  9757. case GGML_GLU_OP_REGLU:
  9758. case GGML_GLU_OP_SWIGLU:
  9759. case GGML_GLU_OP_SWIGLU_OAI:
  9760. case GGML_GLU_OP_GEGLU_ERF:
  9761. case GGML_GLU_OP_GEGLU_QUICK:
  9762. buf = tensor->buffer;
  9763. break;
  9764. default:
  9765. return false;
  9766. }
  9767. break;
  9768. case GGML_OP_MUL_MAT:
  9769. case GGML_OP_MUL_MAT_ID:
  9770. case GGML_OP_FLASH_ATTN_EXT:
  9771. buf = tensor->buffer;
  9772. break;
  9773. default:
  9774. return false;
  9775. }
  9776. if (buf == nullptr) {
  9777. return false;
  9778. }
  9779. 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 << ")");
  9780. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  9781. // always wait for the GPU work to be done for the last submit
  9782. if (tensor_idx == subctx->exit_tensor_idx) {
  9783. use_fence = true;
  9784. }
  9785. // Only run if ctx hasn't been submitted yet
  9786. if (!subctx->seqs.empty()) {
  9787. #ifdef GGML_VULKAN_CHECK_RESULTS
  9788. ggml_vk_check_results_0(ctx, cgraph, tensor_idx);
  9789. use_fence = true;
  9790. #endif
  9791. // Do staging buffer copies
  9792. for (auto& cpy : subctx->in_memcpys) {
  9793. memcpy(cpy.dst, cpy.src, cpy.n);
  9794. }
  9795. for (auto& mset : subctx->memsets) {
  9796. memset(mset.dst, mset.val, mset.n);
  9797. }
  9798. if (almost_ready && !ctx->almost_ready_fence_pending && !use_fence) {
  9799. ggml_vk_submit(subctx, ctx->almost_ready_fence);
  9800. ctx->almost_ready_fence_pending = true;
  9801. } else {
  9802. ggml_vk_submit(subctx, use_fence ? ctx->fence : vk::Fence{});
  9803. }
  9804. if (use_fence) {
  9805. ggml_vk_wait_for_fence(ctx);
  9806. }
  9807. #ifdef GGML_VULKAN_CHECK_RESULTS
  9808. ggml_vk_check_results_1(ctx, cgraph, tensor_idx);
  9809. #endif
  9810. }
  9811. if (tensor_idx == subctx->exit_tensor_idx) {
  9812. // Do staging buffer copies
  9813. for (auto& cpy : subctx->out_memcpys) {
  9814. memcpy(cpy.dst, cpy.src, cpy.n);
  9815. }
  9816. subctx->in_memcpys.clear();
  9817. subctx->out_memcpys.clear();
  9818. subctx->memsets.clear();
  9819. }
  9820. return true;
  9821. }
  9822. // Clean up after graph processing is done
  9823. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  9824. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  9825. for (auto& buffer : ctx->gc.temp_buffers) {
  9826. ggml_vk_pool_free(ctx, buffer);
  9827. }
  9828. ctx->gc.temp_buffers.clear();
  9829. ctx->prealloc_y_last_pipeline_used = {};
  9830. ctx->unsynced_nodes_written.clear();
  9831. ctx->unsynced_nodes_read.clear();
  9832. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  9833. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  9834. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  9835. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  9836. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  9837. }
  9838. ctx->gc.semaphores.clear();
  9839. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  9840. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  9841. }
  9842. ctx->gc.tl_semaphores.clear();
  9843. ctx->semaphore_idx = 0;
  9844. ctx->event_idx = 0;
  9845. for (auto& event : ctx->gc.events) {
  9846. ctx->device->device.resetEvent(event);
  9847. }
  9848. ctx->tensor_ctxs.clear();
  9849. ctx->gc.contexts.clear();
  9850. ctx->pipeline_descriptor_set_requirements = 0;
  9851. ctx->descriptor_set_idx = 0;
  9852. }
  9853. // Clean up on backend free
  9854. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  9855. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  9856. ggml_vk_graph_cleanup(ctx);
  9857. ggml_vk_destroy_buffer(ctx->prealloc_x);
  9858. ggml_vk_destroy_buffer(ctx->prealloc_y);
  9859. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9860. ctx->prealloc_y_last_pipeline_used = nullptr;
  9861. for (auto& buffer : ctx->buffer_pool) {
  9862. ggml_vk_destroy_buffer(buffer);
  9863. }
  9864. ctx->prealloc_size_x = 0;
  9865. ctx->prealloc_size_y = 0;
  9866. ctx->prealloc_size_split_k = 0;
  9867. for (auto& event : ctx->gc.events) {
  9868. ctx->device->device.destroyEvent(event);
  9869. }
  9870. ctx->gc.events.clear();
  9871. ctx->device->device.destroyFence(ctx->fence);
  9872. ctx->device->device.destroyFence(ctx->almost_ready_fence);
  9873. for (auto& pool : ctx->descriptor_pools) {
  9874. ctx->device->device.destroyDescriptorPool(pool);
  9875. }
  9876. ctx->descriptor_pools.clear();
  9877. ctx->descriptor_sets.clear();
  9878. ctx->compute_cmd_pool.destroy(ctx->device->device);
  9879. ctx->transfer_cmd_pool.destroy(ctx->device->device);
  9880. }
  9881. static int ggml_vk_get_device_count() {
  9882. ggml_vk_instance_init();
  9883. return vk_instance.device_indices.size();
  9884. }
  9885. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  9886. ggml_vk_instance_init();
  9887. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  9888. vk::PhysicalDeviceProperties props;
  9889. devices[device].getProperties(&props);
  9890. snprintf(description, description_size, "%s", props.deviceName.data());
  9891. }
  9892. // backend interface
  9893. #define UNUSED GGML_UNUSED
  9894. // device backend
  9895. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  9896. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  9897. }
  9898. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  9899. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  9900. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  9901. ggml_vk_destroy_buffer(ctx->dev_buffer);
  9902. delete ctx;
  9903. }
  9904. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  9905. return vk_ptr_base;
  9906. UNUSED(buffer);
  9907. }
  9908. static enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  9909. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  9910. if (tensor->view_src != nullptr) {
  9911. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  9912. }
  9913. return GGML_STATUS_SUCCESS;
  9914. }
  9915. static void ggml_backend_vk_buffer_memset_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) {
  9916. VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")");
  9917. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  9918. vk_buffer buf = buf_ctx->dev_buffer;
  9919. uint32_t val32 = (uint32_t)value * 0x01010101;
  9920. ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size);
  9921. }
  9922. 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) {
  9923. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  9924. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  9925. vk_buffer buf = buf_ctx->dev_buffer;
  9926. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  9927. }
  9928. 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) {
  9929. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  9930. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  9931. vk_buffer buf = buf_ctx->dev_buffer;
  9932. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  9933. }
  9934. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  9935. if (ggml_backend_buffer_is_vk(src->buffer)) {
  9936. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  9937. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  9938. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  9939. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  9940. 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));
  9941. return true;
  9942. }
  9943. return false;
  9944. UNUSED(buffer);
  9945. }
  9946. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  9947. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  9948. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  9949. }
  9950. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  9951. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  9952. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  9953. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  9954. /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor,
  9955. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  9956. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  9957. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  9958. /* .clear = */ ggml_backend_vk_buffer_clear,
  9959. /* .reset = */ NULL,
  9960. };
  9961. // vk buffer type
  9962. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  9963. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  9964. return ctx->name.c_str();
  9965. }
  9966. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  9967. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  9968. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  9969. vk_buffer dev_buffer = nullptr;
  9970. try {
  9971. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  9972. } catch (const vk::SystemError& e) {
  9973. return nullptr;
  9974. }
  9975. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  9976. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  9977. }
  9978. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  9979. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  9980. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  9981. }
  9982. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  9983. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  9984. return ctx->device->suballocation_block_size;
  9985. }
  9986. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  9987. return ggml_nbytes(tensor);
  9988. UNUSED(buft);
  9989. }
  9990. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  9991. ggml_vk_instance_init();
  9992. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  9993. vk_device dev = ggml_vk_get_device(dev_num);
  9994. return &dev->buffer_type;
  9995. }
  9996. // host buffer type
  9997. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  9998. return GGML_VK_NAME "_Host";
  9999. UNUSED(buft);
  10000. }
  10001. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  10002. return GGML_VK_NAME "_Host";
  10003. UNUSED(buffer);
  10004. }
  10005. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10006. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  10007. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  10008. }
  10009. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10010. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  10011. size += 32; // Behave like the CPU buffer type
  10012. void * ptr = nullptr;
  10013. try {
  10014. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  10015. } catch (vk::SystemError& e) {
  10016. GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory (%s)\n", e.what());
  10017. // fallback to cpu buffer
  10018. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  10019. }
  10020. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  10021. buffer->buft = buft;
  10022. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  10023. return buffer;
  10024. UNUSED(buft);
  10025. }
  10026. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10027. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  10028. UNUSED(buft);
  10029. }
  10030. static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10031. return vk_instance.devices[0]->suballocation_block_size;
  10032. UNUSED(buft);
  10033. }
  10034. // Should be changed to return device-specific host buffer type
  10035. // but that probably requires changes in llama.cpp
  10036. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  10037. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  10038. /* .iface = */ {
  10039. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  10040. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  10041. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  10042. /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size,
  10043. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  10044. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  10045. },
  10046. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  10047. /* .context = */ nullptr,
  10048. };
  10049. // Make sure device 0 is initialized
  10050. ggml_vk_instance_init();
  10051. ggml_vk_get_device(0);
  10052. return &ggml_backend_vk_buffer_type_host;
  10053. }
  10054. // backend
  10055. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  10056. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10057. return ctx->name.c_str();
  10058. }
  10059. static void ggml_backend_vk_free(ggml_backend_t backend) {
  10060. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10061. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  10062. ggml_vk_cleanup(ctx);
  10063. delete ctx;
  10064. delete backend;
  10065. }
  10066. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  10067. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10068. return &ctx->device->buffer_type;
  10069. }
  10070. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  10071. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  10072. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10073. 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");
  10074. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10075. vk_context transfer_ctx;
  10076. if (ctx->transfer_ctx.expired()) {
  10077. // Initialize new transfer context
  10078. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10079. ctx->transfer_ctx = transfer_ctx;
  10080. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10081. } else {
  10082. transfer_ctx = ctx->transfer_ctx.lock();
  10083. }
  10084. vk_buffer buf = buf_ctx->dev_buffer;
  10085. ggml_vk_buffer_write_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10086. }
  10087. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  10088. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  10089. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10090. 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");
  10091. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10092. vk_context transfer_ctx;
  10093. if (ctx->transfer_ctx.expired()) {
  10094. // Initialize new transfer context
  10095. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10096. ctx->transfer_ctx = transfer_ctx;
  10097. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10098. } else {
  10099. transfer_ctx = ctx->transfer_ctx.lock();
  10100. }
  10101. vk_buffer buf = buf_ctx->dev_buffer;
  10102. ggml_vk_buffer_read_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10103. }
  10104. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  10105. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  10106. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10107. 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)) {
  10108. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10109. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10110. vk_context transfer_ctx;
  10111. if (ctx->transfer_ctx.expired()) {
  10112. // Initialize new transfer context
  10113. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10114. ctx->transfer_ctx = transfer_ctx;
  10115. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10116. } else {
  10117. transfer_ctx = ctx->transfer_ctx.lock();
  10118. }
  10119. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10120. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10121. 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));
  10122. return true;
  10123. }
  10124. return false;
  10125. }
  10126. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  10127. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  10128. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10129. if(ctx->transfer_ctx.expired()) {
  10130. return;
  10131. }
  10132. vk_context transfer_ctx = ctx->transfer_ctx.lock();
  10133. ggml_vk_ctx_end(transfer_ctx);
  10134. for (auto& cpy : transfer_ctx->in_memcpys) {
  10135. memcpy(cpy.dst, cpy.src, cpy.n);
  10136. }
  10137. ggml_vk_submit(transfer_ctx, ctx->fence);
  10138. ggml_vk_wait_for_fence(ctx);
  10139. for (auto& cpy : transfer_ctx->out_memcpys) {
  10140. memcpy(cpy.dst, cpy.src, cpy.n);
  10141. }
  10142. ctx->transfer_ctx.reset();
  10143. }
  10144. static bool ggml_vk_is_empty(ggml_tensor * node) {
  10145. 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;
  10146. }
  10147. static bool ggml_vk_can_fuse(const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list<enum ggml_op> ops) {
  10148. if (!ggml_can_fuse(cgraph, node_idx, ops)) {
  10149. return false;
  10150. }
  10151. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
  10152. // additional constraints specific to this fusion
  10153. const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
  10154. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10155. GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
  10156. GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
  10157. // rms_norm only supports f32
  10158. if (mul->src[0]->type != GGML_TYPE_F32 ||
  10159. mul->src[1]->type != GGML_TYPE_F32 ||
  10160. mul->type != GGML_TYPE_F32) {
  10161. return false;
  10162. }
  10163. // if rms_norm is the B operand, then we don't handle broadcast
  10164. if (rms_norm == mul->src[1] &&
  10165. !ggml_are_same_shape(mul->src[0], rms_norm)) {
  10166. return false;
  10167. }
  10168. // rms_norm shader assumes contiguous rows
  10169. if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
  10170. return false;
  10171. }
  10172. }
  10173. return true;
  10174. }
  10175. static uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) {
  10176. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  10177. if (first_node->op != GGML_OP_ADD) {
  10178. return 0;
  10179. }
  10180. if (!ctx->device->multi_add) {
  10181. return 0;
  10182. }
  10183. int32_t num_adds = 1;
  10184. while (node_idx + num_adds < cgraph->n_nodes &&
  10185. cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD &&
  10186. num_adds < MAX_FUSED_ADDS) {
  10187. num_adds++;
  10188. }
  10189. // The shader currently requires same shapes (but different strides are allowed),
  10190. // everything f32, and no misalignment
  10191. for (int32_t i = 0; i < num_adds; ++i) {
  10192. const ggml_tensor *next_node = cgraph->nodes[node_idx + i];
  10193. if (!ggml_are_same_shape(first_node, next_node->src[0]) ||
  10194. !ggml_are_same_shape(first_node, next_node->src[1]) ||
  10195. next_node->type != GGML_TYPE_F32 ||
  10196. next_node->src[0]->type != GGML_TYPE_F32 ||
  10197. next_node->src[1]->type != GGML_TYPE_F32 ||
  10198. get_misalign_bytes(ctx, next_node) ||
  10199. get_misalign_bytes(ctx, next_node->src[0]) ||
  10200. get_misalign_bytes(ctx, next_node->src[1])) {
  10201. num_adds = i;
  10202. }
  10203. }
  10204. // Verify we can fuse these
  10205. ggml_op adds[MAX_FUSED_ADDS];
  10206. for (int32_t i = 0; i < num_adds; ++i) {
  10207. adds[i] = GGML_OP_ADD;
  10208. }
  10209. // decrease num_adds if they can't all be fused
  10210. while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) {
  10211. num_adds--;
  10212. }
  10213. // a single add is not "fused", so just return zero
  10214. if (num_adds == 1) {
  10215. return 0;
  10216. }
  10217. return num_adds;
  10218. }
  10219. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  10220. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  10221. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10222. if (vk_instance.debug_utils_support) {
  10223. vk::DebugUtilsLabelEXT dul = {};
  10224. dul.pLabelName = "ggml_backend_vk_graph_compute";
  10225. dul.color = std::array<float,4>{1.0f, 1.0f, 1.0f, 1.0f};
  10226. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(ctx->device->compute_queue.queue, reinterpret_cast<VkDebugUtilsLabelEXT*>(&dul));
  10227. }
  10228. ctx->prealloc_size_add_rms_partials = 0;
  10229. ctx->prealloc_size_add_rms_partials_offset = 0;
  10230. ctx->do_add_rms_partials = false;
  10231. uint64_t total_mat_mul_bytes = 0;
  10232. for (int i = 0; i < cgraph->n_nodes; i++) {
  10233. if (!ctx->device->disable_fusion) {
  10234. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  10235. if (num_adds) {
  10236. ctx->num_additional_fused_ops = num_adds - 1;
  10237. } else if (ggml_vk_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  10238. ctx->num_additional_fused_ops = 1;
  10239. }
  10240. }
  10241. ggml_vk_build_graph(ctx, cgraph, i, nullptr, 0, true, false, false, false);
  10242. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  10243. total_mat_mul_bytes += ggml_nbytes(cgraph->nodes[i]->src[0]);
  10244. } else if (cgraph->nodes[i]->op == GGML_OP_CONV_2D || cgraph->nodes[i]->op == GGML_OP_CONV_TRANSPOSE_2D) {
  10245. // Return CRSxNPQxsizeof(*) to account as many bytes as mul_mat has in im2col->mul_mat mode.
  10246. auto CRS_size =
  10247. cgraph->nodes[i]->src[0]->ne[0] * cgraph->nodes[i]->src[0]->ne[1] * cgraph->nodes[i]->src[1]->ne[2];
  10248. auto NPQ_size = cgraph->nodes[i]->ne[0] * cgraph->nodes[i]->ne[1] * cgraph->nodes[i]->ne[3];
  10249. total_mat_mul_bytes += NPQ_size * CRS_size * ggml_type_size(cgraph->nodes[i]->type);
  10250. }
  10251. i += ctx->num_additional_fused_ops;
  10252. ctx->num_additional_fused_ops = 0;
  10253. }
  10254. if (ctx->device->need_compiles) {
  10255. ggml_vk_load_shaders(ctx->device);
  10256. }
  10257. ggml_vk_preallocate_buffers(ctx);
  10258. ggml_pipeline_allocate_descriptor_sets(ctx);
  10259. int last_node = cgraph->n_nodes - 1;
  10260. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  10261. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  10262. last_node -= 1;
  10263. }
  10264. // Reserve tensor context space for all nodes
  10265. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  10266. bool first_node_in_batch = true; // true if next node will be first node in a batch
  10267. int submit_node_idx = 0; // index to first node in a batch
  10268. vk_context compute_ctx;
  10269. if (vk_perf_logger_enabled) {
  10270. // allocate/resize the query pool
  10271. if (ctx->device->num_queries < cgraph->n_nodes + 1) {
  10272. if (ctx->device->query_pool) {
  10273. ctx->device->device.destroyQueryPool(ctx->device->query_pool);
  10274. }
  10275. vk::QueryPoolCreateInfo query_create_info;
  10276. query_create_info.queryType = vk::QueryType::eTimestamp;
  10277. query_create_info.queryCount = cgraph->n_nodes + 100;
  10278. ctx->device->query_pool = ctx->device->device.createQueryPool(query_create_info);
  10279. ctx->device->num_queries = query_create_info.queryCount;
  10280. }
  10281. ctx->device->device.resetQueryPool(ctx->device->query_pool, 0, cgraph->n_nodes+1);
  10282. GGML_ASSERT(ctx->compute_ctx.expired());
  10283. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10284. ctx->compute_ctx = compute_ctx;
  10285. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10286. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, 0);
  10287. }
  10288. ctx->prealloc_y_last_pipeline_used = nullptr;
  10289. ctx->prealloc_y_last_tensor_used = nullptr;
  10290. if (ctx->prealloc_size_add_rms_partials) {
  10291. if (ctx->compute_ctx.expired()) {
  10292. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10293. ctx->compute_ctx = compute_ctx;
  10294. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10295. } else {
  10296. compute_ctx = ctx->compute_ctx.lock();
  10297. }
  10298. // initialize partial sums to zero.
  10299. ggml_vk_buffer_memset_async(compute_ctx, ctx->prealloc_add_rms_partials, 0, 0, ctx->prealloc_size_add_rms_partials);
  10300. ggml_vk_sync_buffers(ctx, compute_ctx);
  10301. }
  10302. // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution.
  10303. // Estimate the amount of matmul work by looking at the weight matrix size, and submit every 100MB
  10304. // (and scaled down based on model size, so smaller models submit earlier).
  10305. // Also submit at least every 100 nodes, in case there are workloads without as much matmul.
  10306. int nodes_per_submit = 100;
  10307. int submitted_nodes = 0;
  10308. int submit_count = 0;
  10309. uint64_t mul_mat_bytes = 0;
  10310. uint64_t mul_mat_bytes_per_submit = std::min(uint64_t(100*1000*1000), total_mat_mul_bytes / 40u);
  10311. for (int i = 0; i < cgraph->n_nodes; i++) {
  10312. if (first_node_in_batch) {
  10313. submit_node_idx = i;
  10314. }
  10315. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  10316. mul_mat_bytes += ggml_nbytes(cgraph->nodes[i]->src[0]);
  10317. }
  10318. if (!ctx->device->disable_fusion) {
  10319. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  10320. if (num_adds) {
  10321. ctx->num_additional_fused_ops = num_adds - 1;
  10322. } else if (ggml_vk_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  10323. ctx->num_additional_fused_ops = 1;
  10324. }
  10325. }
  10326. // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining)
  10327. bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5;
  10328. bool submit = (submitted_nodes >= nodes_per_submit) ||
  10329. (mul_mat_bytes >= mul_mat_bytes_per_submit) ||
  10330. (i + ctx->num_additional_fused_ops == last_node) ||
  10331. (almost_ready && !ctx->almost_ready_fence_pending);
  10332. bool enqueued = ggml_vk_build_graph(ctx, cgraph, i, cgraph->nodes[submit_node_idx], submit_node_idx, false, i + ctx->num_additional_fused_ops == last_node, almost_ready, submit);
  10333. if (vk_perf_logger_enabled) {
  10334. if (ctx->compute_ctx.expired()) {
  10335. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10336. ctx->compute_ctx = compute_ctx;
  10337. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10338. } else {
  10339. compute_ctx = ctx->compute_ctx.lock();
  10340. }
  10341. // If there are fused ops, just write out timestamps for all nodes to keep the accounting simple
  10342. for (int j = 0; j < ctx->num_additional_fused_ops + 1; ++j) {
  10343. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, i+j+1);
  10344. }
  10345. }
  10346. if (enqueued) {
  10347. ++submitted_nodes;
  10348. #ifndef GGML_VULKAN_CHECK_RESULTS
  10349. if (first_node_in_batch) {
  10350. first_node_in_batch = false;
  10351. }
  10352. #endif
  10353. }
  10354. if (submit && enqueued) {
  10355. first_node_in_batch = true;
  10356. submitted_nodes = 0;
  10357. mul_mat_bytes = 0;
  10358. if (submit_count < 3) {
  10359. mul_mat_bytes_per_submit *= 2;
  10360. }
  10361. submit_count++;
  10362. }
  10363. i += ctx->num_additional_fused_ops;
  10364. ctx->num_additional_fused_ops = 0;
  10365. }
  10366. if (vk_perf_logger_enabled) {
  10367. // End the command buffer and submit/wait
  10368. GGML_ASSERT(!ctx->compute_ctx.expired());
  10369. compute_ctx = ctx->compute_ctx.lock();
  10370. ggml_vk_ctx_end(compute_ctx);
  10371. ggml_vk_submit(compute_ctx, ctx->device->fence);
  10372. VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences");
  10373. ctx->device->device.resetFences({ ctx->device->fence });
  10374. // Get the results and pass them to the logger
  10375. std::vector<uint64_t> timestamps(cgraph->n_nodes + 1);
  10376. VK_CHECK(ctx->device->device.getQueryPoolResults(ctx->device->query_pool, 0, cgraph->n_nodes + 1, (cgraph->n_nodes + 1)*sizeof(uint64_t), timestamps.data(), sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait), "get timestamp results");
  10377. for (int i = 0; i < cgraph->n_nodes; i++) {
  10378. if (!ggml_vk_is_empty(cgraph->nodes[i])) {
  10379. ctx->device->perf_logger->log_timing(cgraph->nodes[i], uint64_t((timestamps[i+1] - timestamps[i]) * ctx->device->properties.limits.timestampPeriod));
  10380. }
  10381. }
  10382. ctx->device->perf_logger->print_timings();
  10383. }
  10384. ggml_vk_graph_cleanup(ctx);
  10385. return GGML_STATUS_SUCCESS;
  10386. UNUSED(backend);
  10387. }
  10388. // Sort the graph for improved parallelism.
  10389. static void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph)
  10390. {
  10391. VK_LOG_DEBUG("ggml_vk_graph_optimize(" << graph->n_nodes << " nodes)");
  10392. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10393. if (ctx->device->disable_graph_optimize) {
  10394. return;
  10395. }
  10396. auto const &is_empty = [](ggml_tensor * node) -> bool {
  10397. return node->op == GGML_OP_NONE || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE;
  10398. };
  10399. auto const &is_src_of = [](const ggml_tensor *dst, const ggml_tensor *src) -> bool {
  10400. for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) {
  10401. if (dst->src[s] == src) {
  10402. return true;
  10403. }
  10404. }
  10405. // implicit dependency if they view the same tensor
  10406. const ggml_tensor *dst2 = dst->view_src ? dst->view_src : dst;
  10407. const ggml_tensor *src2 = src->view_src ? src->view_src : src;
  10408. if (dst2 == src2) {
  10409. return true;
  10410. }
  10411. return false;
  10412. };
  10413. // This function tries to reorder the graph to allow nodes to run in parallel.
  10414. // This helps with small batches, but for large batches its a slowdown, probably
  10415. // due to cache contention. So only reorder if the majority of nodes have few rows.
  10416. int num_small_nodes = 0;
  10417. int num_counted_nodes = 0;
  10418. for (int i = 0; i < graph->n_nodes; ++i) {
  10419. if (!is_empty(graph->nodes[i]) &&
  10420. graph->nodes[i]->op != GGML_OP_SET_ROWS) {
  10421. if (ggml_nrows(graph->nodes[i]) <= 8) {
  10422. num_small_nodes++;
  10423. }
  10424. num_counted_nodes++;
  10425. }
  10426. }
  10427. if (num_small_nodes < num_counted_nodes / 2) {
  10428. return;
  10429. }
  10430. std::vector<ggml_tensor *> new_order;
  10431. std::vector<bool> used(graph->n_nodes, false);
  10432. int first_unused = 0;
  10433. while (first_unused < graph->n_nodes) {
  10434. std::vector<int> current_set;
  10435. // First, grab the next unused node.
  10436. current_set.push_back(first_unused);
  10437. // Loop through the next N nodes. Grab any that don't depend on other nodes that
  10438. // haven't already been run. Nodes that have already been run have used[i] set
  10439. // to true. Allow nodes that depend on the previous node if it's a fusion pattern
  10440. // that we support (e.g. RMS_NORM + MUL).
  10441. // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes.
  10442. // The goal is to not interleave real and view nodes in a way that breaks fusion.
  10443. const int NUM_TO_CHECK = 20;
  10444. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  10445. if (used[j]) {
  10446. continue;
  10447. }
  10448. if (is_empty(graph->nodes[j])) {
  10449. continue;
  10450. }
  10451. bool ok = true;
  10452. for (int c = first_unused; c < j; ++c) {
  10453. if (!used[c] &&
  10454. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  10455. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL)) {
  10456. ok = false;
  10457. break;
  10458. }
  10459. }
  10460. if (ok) {
  10461. current_set.push_back(j);
  10462. }
  10463. }
  10464. // Second pass grabs view nodes.
  10465. // Skip this if it would break a fusion optimization (don't split up add->rms_norm or add->add).
  10466. if (graph->nodes[current_set.back()]->op != GGML_OP_ADD) {
  10467. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  10468. if (used[j]) {
  10469. continue;
  10470. }
  10471. if (!is_empty(graph->nodes[j])) {
  10472. continue;
  10473. }
  10474. bool ok = true;
  10475. for (int c = first_unused; c < j; ++c) {
  10476. bool c_in_current_set = std::find(current_set.begin(), current_set.end(), c) != current_set.end();
  10477. // skip views whose srcs haven't been processed.
  10478. if (!used[c] &&
  10479. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  10480. !c_in_current_set) {
  10481. ok = false;
  10482. break;
  10483. }
  10484. }
  10485. if (ok) {
  10486. current_set.push_back(j);
  10487. }
  10488. }
  10489. }
  10490. // Push the current set into new_order
  10491. for (auto c : current_set) {
  10492. new_order.push_back(graph->nodes[c]);
  10493. used[c] = true;
  10494. }
  10495. while (first_unused < graph->n_nodes && used[first_unused]) {
  10496. first_unused++;
  10497. }
  10498. }
  10499. // Replace the graph with the new order.
  10500. for (int i = 0; i < graph->n_nodes; ++i) {
  10501. graph->nodes[i] = new_order[i];
  10502. }
  10503. }
  10504. // TODO: enable async and synchronize
  10505. static ggml_backend_i ggml_backend_vk_interface = {
  10506. /* .get_name = */ ggml_backend_vk_name,
  10507. /* .free = */ ggml_backend_vk_free,
  10508. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  10509. /* .get_tensor_async = */ NULL, // ggml_backend_vk_get_tensor_async,
  10510. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  10511. /* .synchronize = */ NULL, // ggml_backend_vk_synchronize,
  10512. /* .graph_plan_create = */ NULL,
  10513. /* .graph_plan_free = */ NULL,
  10514. /* .graph_plan_update = */ NULL,
  10515. /* .graph_plan_compute = */ NULL,
  10516. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  10517. /* .event_record = */ NULL,
  10518. /* .event_wait = */ NULL,
  10519. /* .graph_optimize = */ ggml_vk_graph_optimize,
  10520. };
  10521. static ggml_guid_t ggml_backend_vk_guid() {
  10522. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  10523. return &guid;
  10524. }
  10525. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  10526. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  10527. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  10528. ggml_vk_init(ctx, dev_num);
  10529. ggml_backend_t vk_backend = new ggml_backend {
  10530. /* .guid = */ ggml_backend_vk_guid(),
  10531. /* .iface = */ ggml_backend_vk_interface,
  10532. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  10533. /* .context = */ ctx,
  10534. };
  10535. return vk_backend;
  10536. }
  10537. bool ggml_backend_is_vk(ggml_backend_t backend) {
  10538. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  10539. }
  10540. int ggml_backend_vk_get_device_count() {
  10541. return ggml_vk_get_device_count();
  10542. }
  10543. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  10544. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  10545. int dev_idx = vk_instance.device_indices[device];
  10546. ggml_vk_get_device_description(dev_idx, description, description_size);
  10547. }
  10548. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  10549. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  10550. GGML_ASSERT(device < (int) vk_instance.device_supports_membudget.size());
  10551. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  10552. vk::PhysicalDeviceMemoryBudgetPropertiesEXT budgetprops;
  10553. vk::PhysicalDeviceMemoryProperties2 memprops = {};
  10554. bool membudget_supported = vk_instance.device_supports_membudget[device];
  10555. if (membudget_supported) {
  10556. memprops.pNext = &budgetprops;
  10557. }
  10558. vkdev.getMemoryProperties2(&memprops);
  10559. for (uint32_t i = 0; i < memprops.memoryProperties.memoryHeapCount; ++i) {
  10560. const vk::MemoryHeap & heap = memprops.memoryProperties.memoryHeaps[i];
  10561. if (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
  10562. *total = heap.size;
  10563. if (membudget_supported && i < budgetprops.heapUsage.size()) {
  10564. *free = budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
  10565. } else {
  10566. *free = heap.size;
  10567. }
  10568. break;
  10569. }
  10570. }
  10571. }
  10572. static vk::PhysicalDeviceType ggml_backend_vk_get_device_type(int device_idx) {
  10573. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  10574. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  10575. vk::PhysicalDeviceProperties2 props = {};
  10576. device.getProperties2(&props);
  10577. return props.properties.deviceType;
  10578. }
  10579. static std::string ggml_backend_vk_get_device_pci_id(int device_idx) {
  10580. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  10581. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  10582. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  10583. bool ext_support = false;
  10584. for (const auto& properties : ext_props) {
  10585. if (strcmp("VK_EXT_pci_bus_info", properties.extensionName) == 0) {
  10586. ext_support = true;
  10587. break;
  10588. }
  10589. }
  10590. if (!ext_support) {
  10591. return "";
  10592. }
  10593. vk::PhysicalDeviceProperties2 props = {};
  10594. vk::PhysicalDevicePCIBusInfoPropertiesEXT pci_bus_info = {};
  10595. props.pNext = &pci_bus_info;
  10596. device.getProperties2(&props);
  10597. const uint32_t pci_domain = pci_bus_info.pciDomain;
  10598. const uint32_t pci_bus = pci_bus_info.pciBus;
  10599. const uint32_t pci_device = pci_bus_info.pciDevice;
  10600. const uint8_t pci_function = (uint8_t) pci_bus_info.pciFunction; // pci function is between 0 and 7, prevent printf overflow warning
  10601. char pci_bus_id[16] = {};
  10602. snprintf(pci_bus_id, sizeof(pci_bus_id), "%04x:%02x:%02x.%x", pci_domain, pci_bus, pci_device, pci_function);
  10603. return std::string(pci_bus_id);
  10604. }
  10605. //////////////////////////
  10606. struct ggml_backend_vk_device_context {
  10607. size_t device;
  10608. std::string name;
  10609. std::string description;
  10610. bool is_integrated_gpu;
  10611. std::string pci_bus_id;
  10612. };
  10613. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  10614. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10615. return ctx->name.c_str();
  10616. }
  10617. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  10618. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10619. return ctx->description.c_str();
  10620. }
  10621. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  10622. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  10623. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  10624. }
  10625. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  10626. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10627. return ggml_backend_vk_buffer_type(ctx->device);
  10628. }
  10629. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  10630. UNUSED(dev);
  10631. return ggml_backend_vk_host_buffer_type();
  10632. }
  10633. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  10634. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10635. return ctx->is_integrated_gpu ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
  10636. }
  10637. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  10638. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10639. props->name = ggml_backend_vk_device_get_name(dev);
  10640. props->description = ggml_backend_vk_device_get_description(dev);
  10641. props->type = ggml_backend_vk_device_get_type(dev);
  10642. props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str();
  10643. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  10644. props->caps = {
  10645. /* .async = */ false,
  10646. /* .host_buffer = */ true,
  10647. /* .buffer_from_host_ptr = */ false,
  10648. /* .events = */ false,
  10649. };
  10650. }
  10651. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  10652. UNUSED(params);
  10653. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10654. return ggml_backend_vk_init(ctx->device);
  10655. }
  10656. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  10657. switch (op->op) {
  10658. case GGML_OP_UNARY:
  10659. switch (ggml_get_unary_op(op)) {
  10660. case GGML_UNARY_OP_EXP:
  10661. case GGML_UNARY_OP_GELU:
  10662. case GGML_UNARY_OP_GELU_ERF:
  10663. case GGML_UNARY_OP_GELU_QUICK:
  10664. case GGML_UNARY_OP_SILU:
  10665. case GGML_UNARY_OP_RELU:
  10666. case GGML_UNARY_OP_TANH:
  10667. case GGML_UNARY_OP_SIGMOID:
  10668. case GGML_UNARY_OP_HARDSIGMOID:
  10669. case GGML_UNARY_OP_HARDSWISH:
  10670. return ggml_is_contiguous(op->src[0]) &&
  10671. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  10672. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  10673. (op->src[0]->type == op->type);
  10674. default:
  10675. return false;
  10676. }
  10677. case GGML_OP_GLU:
  10678. switch (ggml_get_glu_op(op)) {
  10679. case GGML_GLU_OP_GEGLU:
  10680. case GGML_GLU_OP_REGLU:
  10681. case GGML_GLU_OP_SWIGLU:
  10682. case GGML_GLU_OP_SWIGLU_OAI:
  10683. case GGML_GLU_OP_GEGLU_ERF:
  10684. case GGML_GLU_OP_GEGLU_QUICK:
  10685. return ggml_is_contiguous(op->src[0]) &&
  10686. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  10687. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  10688. (op->src[0]->type == op->type);
  10689. default:
  10690. return false;
  10691. }
  10692. case GGML_OP_MUL_MAT:
  10693. case GGML_OP_MUL_MAT_ID:
  10694. {
  10695. ggml_type src0_type = op->src[0]->type;
  10696. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10697. const vk_device& device = ggml_vk_get_device(ctx->device);
  10698. if (op->op == GGML_OP_MUL_MAT_ID) {
  10699. if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) {
  10700. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  10701. return false;
  10702. }
  10703. }
  10704. switch (src0_type) {
  10705. case GGML_TYPE_F32:
  10706. case GGML_TYPE_F16:
  10707. case GGML_TYPE_BF16:
  10708. case GGML_TYPE_Q4_0:
  10709. case GGML_TYPE_Q4_1:
  10710. case GGML_TYPE_Q5_0:
  10711. case GGML_TYPE_Q5_1:
  10712. case GGML_TYPE_Q8_0:
  10713. case GGML_TYPE_Q2_K:
  10714. case GGML_TYPE_Q3_K:
  10715. case GGML_TYPE_Q4_K:
  10716. case GGML_TYPE_Q5_K:
  10717. case GGML_TYPE_Q6_K:
  10718. case GGML_TYPE_IQ1_S:
  10719. case GGML_TYPE_IQ1_M:
  10720. case GGML_TYPE_IQ2_XXS:
  10721. case GGML_TYPE_IQ2_XS:
  10722. case GGML_TYPE_IQ2_S:
  10723. case GGML_TYPE_IQ3_XXS:
  10724. case GGML_TYPE_IQ3_S:
  10725. case GGML_TYPE_IQ4_XS:
  10726. case GGML_TYPE_IQ4_NL:
  10727. case GGML_TYPE_MXFP4:
  10728. break;
  10729. default:
  10730. return false;
  10731. }
  10732. struct ggml_tensor * a;
  10733. struct ggml_tensor * b;
  10734. if (op->op == GGML_OP_MUL_MAT) {
  10735. a = op->src[0];
  10736. b = op->src[1];
  10737. } else {
  10738. a = op->src[2];
  10739. b = op->src[1];
  10740. }
  10741. if (a->ne[3] != b->ne[3]) {
  10742. return false;
  10743. }
  10744. if (!(ggml_vk_dim01_contiguous(op->src[0]) || op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16) ||
  10745. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  10746. return false;
  10747. }
  10748. if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) {
  10749. // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader.
  10750. // So don't support this combination for now.
  10751. return false;
  10752. }
  10753. return true;
  10754. }
  10755. case GGML_OP_FLASH_ATTN_EXT:
  10756. {
  10757. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10758. auto device = ggml_vk_get_device(ctx->device);
  10759. bool coopmat2 = device->coopmat2;
  10760. uint32_t HSK = op->src[1]->ne[0];
  10761. uint32_t HSV = op->src[2]->ne[0];
  10762. if ((HSK % 8) != 0 || (HSV % 8) != 0) {
  10763. return false;
  10764. }
  10765. if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) {
  10766. return false;
  10767. }
  10768. if (op->src[0]->type != GGML_TYPE_F32) {
  10769. return false;
  10770. }
  10771. if (op->type != GGML_TYPE_F32) {
  10772. return false;
  10773. }
  10774. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  10775. return false;
  10776. }
  10777. // It's straightforward to support different K/V dequant, but would
  10778. // significantly increase the number of pipelines
  10779. if (op->src[1]->type != op->src[2]->type) {
  10780. return false;
  10781. }
  10782. switch (op->src[1]->type) {
  10783. case GGML_TYPE_F16:
  10784. case GGML_TYPE_Q4_0:
  10785. case GGML_TYPE_Q8_0:
  10786. // supported in scalar and coopmat2 paths
  10787. break;
  10788. case GGML_TYPE_Q4_1:
  10789. case GGML_TYPE_Q5_0:
  10790. case GGML_TYPE_Q5_1:
  10791. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  10792. //case GGML_TYPE_Q2_K:
  10793. //case GGML_TYPE_Q3_K:
  10794. //case GGML_TYPE_Q4_K:
  10795. //case GGML_TYPE_Q5_K:
  10796. //case GGML_TYPE_Q6_K:
  10797. //case GGML_TYPE_IQ1_S:
  10798. //case GGML_TYPE_IQ1_M:
  10799. //case GGML_TYPE_IQ2_XXS:
  10800. //case GGML_TYPE_IQ2_XS:
  10801. //case GGML_TYPE_IQ2_S:
  10802. //case GGML_TYPE_IQ3_XXS:
  10803. //case GGML_TYPE_IQ3_S:
  10804. //case GGML_TYPE_IQ4_XS:
  10805. case GGML_TYPE_IQ4_NL:
  10806. // currently supported only in coopmat2 path
  10807. if (!coopmat2) {
  10808. return false;
  10809. }
  10810. break;
  10811. default:
  10812. return false;
  10813. }
  10814. if (!coopmat2 && !device->subgroup_shuffle) {
  10815. // scalar FA uses subgroupShuffle
  10816. return false;
  10817. }
  10818. return true;
  10819. }
  10820. case GGML_OP_GET_ROWS:
  10821. {
  10822. switch (op->src[0]->type) {
  10823. case GGML_TYPE_F32:
  10824. case GGML_TYPE_F16:
  10825. case GGML_TYPE_BF16:
  10826. case GGML_TYPE_Q4_0:
  10827. case GGML_TYPE_Q4_1:
  10828. case GGML_TYPE_Q5_0:
  10829. case GGML_TYPE_Q5_1:
  10830. case GGML_TYPE_Q8_0:
  10831. case GGML_TYPE_IQ1_S:
  10832. case GGML_TYPE_IQ1_M:
  10833. case GGML_TYPE_IQ2_XXS:
  10834. case GGML_TYPE_IQ2_XS:
  10835. case GGML_TYPE_IQ2_S:
  10836. case GGML_TYPE_IQ3_XXS:
  10837. case GGML_TYPE_IQ3_S:
  10838. case GGML_TYPE_IQ4_XS:
  10839. case GGML_TYPE_IQ4_NL:
  10840. case GGML_TYPE_MXFP4:
  10841. return true;
  10842. default:
  10843. return false;
  10844. }
  10845. }
  10846. case GGML_OP_SET_ROWS:
  10847. {
  10848. switch (op->type) {
  10849. case GGML_TYPE_F32:
  10850. case GGML_TYPE_F16:
  10851. case GGML_TYPE_BF16:
  10852. case GGML_TYPE_Q4_0:
  10853. case GGML_TYPE_Q4_1:
  10854. case GGML_TYPE_Q5_0:
  10855. case GGML_TYPE_Q5_1:
  10856. case GGML_TYPE_Q8_0:
  10857. case GGML_TYPE_IQ4_NL:
  10858. return true;
  10859. default:
  10860. return false;
  10861. }
  10862. }
  10863. case GGML_OP_CONT:
  10864. case GGML_OP_CPY:
  10865. case GGML_OP_DUP:
  10866. {
  10867. ggml_type src0_type = op->src[0]->type;
  10868. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  10869. if (src0_type == GGML_TYPE_F32) {
  10870. switch (src1_type) {
  10871. case GGML_TYPE_F32:
  10872. case GGML_TYPE_F16:
  10873. case GGML_TYPE_BF16:
  10874. case GGML_TYPE_Q4_0:
  10875. case GGML_TYPE_Q4_1:
  10876. case GGML_TYPE_Q5_0:
  10877. case GGML_TYPE_Q5_1:
  10878. case GGML_TYPE_Q8_0:
  10879. case GGML_TYPE_IQ4_NL:
  10880. return true;
  10881. default:
  10882. break;
  10883. }
  10884. }
  10885. if (src1_type == GGML_TYPE_F32) {
  10886. switch (src0_type) {
  10887. case GGML_TYPE_F16:
  10888. case GGML_TYPE_Q4_0:
  10889. case GGML_TYPE_Q4_1:
  10890. case GGML_TYPE_Q5_0:
  10891. case GGML_TYPE_Q5_1:
  10892. case GGML_TYPE_Q8_0:
  10893. case GGML_TYPE_IQ4_NL:
  10894. return true;
  10895. default:
  10896. break;
  10897. }
  10898. }
  10899. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  10900. return true;
  10901. }
  10902. if (
  10903. (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) ||
  10904. (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32)
  10905. ) {
  10906. return true;
  10907. }
  10908. // We can handle copying from a type to the same type if it's
  10909. // contiguous (memcpy). We use f16 or f32 shaders to do the copy,
  10910. // so the type/block size must be a multiple of 4.
  10911. if (src0_type == src1_type &&
  10912. ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op) &&
  10913. (ggml_type_size(src0_type) % 2) == 0) {
  10914. return true;
  10915. }
  10916. return false;
  10917. }
  10918. case GGML_OP_REPEAT:
  10919. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  10920. case GGML_OP_REPEAT_BACK:
  10921. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32;
  10922. case GGML_OP_ROPE:
  10923. case GGML_OP_ROPE_BACK:
  10924. case GGML_OP_NONE:
  10925. case GGML_OP_RESHAPE:
  10926. case GGML_OP_VIEW:
  10927. case GGML_OP_PERMUTE:
  10928. case GGML_OP_TRANSPOSE:
  10929. case GGML_OP_RMS_NORM:
  10930. return true;
  10931. case GGML_OP_NORM:
  10932. case GGML_OP_GROUP_NORM:
  10933. case GGML_OP_L2_NORM:
  10934. return ggml_is_contiguous(op->src[0]);
  10935. case GGML_OP_ADD:
  10936. case GGML_OP_SUB:
  10937. case GGML_OP_MUL:
  10938. case GGML_OP_DIV:
  10939. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  10940. (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
  10941. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  10942. case GGML_OP_ADD_ID:
  10943. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 &&
  10944. op->type == GGML_TYPE_F32;
  10945. case GGML_OP_SILU_BACK:
  10946. case GGML_OP_RMS_NORM_BACK:
  10947. case GGML_OP_SQR:
  10948. case GGML_OP_SQRT:
  10949. case GGML_OP_SIN:
  10950. case GGML_OP_COS:
  10951. case GGML_OP_CLAMP:
  10952. case GGML_OP_LEAKY_RELU:
  10953. case GGML_OP_OPT_STEP_ADAMW:
  10954. case GGML_OP_OPT_STEP_SGD:
  10955. return op->src[0]->type == GGML_TYPE_F32;
  10956. case GGML_OP_ARGSORT:
  10957. return op->ne[0] <= max_argsort_cols;
  10958. case GGML_OP_UPSCALE:
  10959. case GGML_OP_ACC:
  10960. case GGML_OP_CONCAT:
  10961. case GGML_OP_SCALE:
  10962. case GGML_OP_PAD:
  10963. case GGML_OP_ROLL:
  10964. case GGML_OP_DIAG_MASK_INF:
  10965. case GGML_OP_SOFT_MAX:
  10966. case GGML_OP_SOFT_MAX_BACK:
  10967. return true;
  10968. case GGML_OP_SUM:
  10969. case GGML_OP_SUM_ROWS:
  10970. case GGML_OP_MEAN:
  10971. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  10972. case GGML_OP_ARGMAX:
  10973. case GGML_OP_COUNT_EQUAL:
  10974. case GGML_OP_IM2COL:
  10975. case GGML_OP_IM2COL_3D:
  10976. case GGML_OP_TIMESTEP_EMBEDDING:
  10977. case GGML_OP_CONV_2D_DW:
  10978. case GGML_OP_POOL_2D:
  10979. case GGML_OP_RWKV_WKV6:
  10980. case GGML_OP_RWKV_WKV7:
  10981. return true;
  10982. case GGML_OP_CONV_TRANSPOSE_1D:
  10983. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  10984. case GGML_OP_CONV_2D:
  10985. case GGML_OP_CONV_TRANSPOSE_2D:
  10986. {
  10987. // Op is disabled for Apple because it segfaults at pipeline create time on MoltenVK
  10988. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10989. const vk_device& device = ggml_vk_get_device(ctx->device);
  10990. if (op->op == GGML_OP_CONV_TRANSPOSE_2D &&
  10991. device->properties.limits.maxPushConstantsSize < sizeof(vk_op_conv_transpose_2d_push_constants)) {
  10992. return false;
  10993. }
  10994. // Channel-contiguous format is not supported yet.
  10995. return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  10996. op->src[1]->type == GGML_TYPE_F32 &&
  10997. op->type == GGML_TYPE_F32 &&
  10998. ggml_is_contiguous(op->src[0]) &&
  10999. ggml_is_contiguous(op->src[1]) &&
  11000. ggml_is_contiguous(op));
  11001. }
  11002. default:
  11003. return false;
  11004. }
  11005. UNUSED(dev);
  11006. }
  11007. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  11008. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  11009. return false;
  11010. }
  11011. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11012. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  11013. return buft_ctx->device->idx == ctx->device;
  11014. }
  11015. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  11016. const int min_batch_size = 32;
  11017. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  11018. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  11019. UNUSED(dev);
  11020. }
  11021. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  11022. /* .get_name = */ ggml_backend_vk_device_get_name,
  11023. /* .get_description = */ ggml_backend_vk_device_get_description,
  11024. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  11025. /* .get_type = */ ggml_backend_vk_device_get_type,
  11026. /* .get_props = */ ggml_backend_vk_device_get_props,
  11027. /* .init_backend = */ ggml_backend_vk_device_init,
  11028. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  11029. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  11030. /* .buffer_from_host_ptr = */ NULL,
  11031. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  11032. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  11033. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  11034. /* .event_new = */ NULL,
  11035. /* .event_free = */ NULL,
  11036. /* .event_synchronize = */ NULL,
  11037. };
  11038. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  11039. UNUSED(reg);
  11040. return GGML_VK_NAME;
  11041. }
  11042. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  11043. UNUSED(reg);
  11044. return ggml_backend_vk_get_device_count();
  11045. }
  11046. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  11047. static std::vector<ggml_backend_dev_t> devices;
  11048. static bool initialized = false;
  11049. {
  11050. static std::mutex mutex;
  11051. std::lock_guard<std::mutex> lock(mutex);
  11052. if (!initialized) {
  11053. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  11054. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  11055. char desc[256];
  11056. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  11057. ctx->device = i;
  11058. ctx->name = GGML_VK_NAME + std::to_string(i);
  11059. ctx->description = desc;
  11060. ctx->is_integrated_gpu = ggml_backend_vk_get_device_type(i) == vk::PhysicalDeviceType::eIntegratedGpu;
  11061. ctx->pci_bus_id = ggml_backend_vk_get_device_pci_id(i);
  11062. devices.push_back(new ggml_backend_device {
  11063. /* .iface = */ ggml_backend_vk_device_i,
  11064. /* .reg = */ reg,
  11065. /* .context = */ ctx,
  11066. });
  11067. }
  11068. initialized = true;
  11069. }
  11070. }
  11071. GGML_ASSERT(device < devices.size());
  11072. return devices[device];
  11073. }
  11074. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  11075. /* .get_name = */ ggml_backend_vk_reg_get_name,
  11076. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  11077. /* .get_device = */ ggml_backend_vk_reg_get_device,
  11078. /* .get_proc_address = */ NULL,
  11079. };
  11080. ggml_backend_reg_t ggml_backend_vk_reg() {
  11081. static ggml_backend_reg reg = {
  11082. /* .api_version = */ GGML_BACKEND_API_VERSION,
  11083. /* .iface = */ ggml_backend_vk_reg_i,
  11084. /* .context = */ nullptr,
  11085. };
  11086. try {
  11087. ggml_vk_instance_init();
  11088. return &reg;
  11089. } catch (const vk::SystemError& e) {
  11090. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what());
  11091. return nullptr;
  11092. }
  11093. }
  11094. // Extension availability
  11095. static bool ggml_vk_instance_validation_ext_available() {
  11096. #ifdef GGML_VULKAN_VALIDATE
  11097. // Check if validation layer provides the extension
  11098. const std::string layer_name = "VK_LAYER_KHRONOS_validation";
  11099. for (const auto& layer : vk::enumerateInstanceLayerProperties()) {
  11100. if (layer_name == layer.layerName.data()) {
  11101. for (const auto& ext : vk::enumerateInstanceExtensionProperties(layer_name)) {
  11102. if (strcmp("VK_EXT_validation_features", ext.extensionName.data()) == 0) {
  11103. return true;
  11104. }
  11105. }
  11106. }
  11107. }
  11108. std::cerr << "ggml_vulkan: WARNING: Validation layer or layer extension VK_EXT_validation_features not found." << std::endl;
  11109. #endif
  11110. return false;
  11111. }
  11112. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  11113. #ifdef __APPLE__
  11114. // Check for portability enumeration extension for MoltenVK support
  11115. for (const auto& properties : instance_extensions) {
  11116. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  11117. return true;
  11118. }
  11119. }
  11120. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  11121. #endif
  11122. return false;
  11123. UNUSED(instance_extensions);
  11124. }
  11125. // Extension availability
  11126. static bool ggml_vk_instance_debug_utils_ext_available(
  11127. const std::vector<vk::ExtensionProperties> & instance_extensions) {
  11128. // Check for portability enumeration extension for MoltenVK support
  11129. for (const auto & properties : instance_extensions) {
  11130. if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) {
  11131. return true;
  11132. }
  11133. }
  11134. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl;
  11135. return false;
  11136. UNUSED(instance_extensions);
  11137. }
  11138. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev) {
  11139. VkPhysicalDeviceFeatures2 device_features2;
  11140. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  11141. VkPhysicalDeviceVulkan11Features vk11_features;
  11142. vk11_features.pNext = nullptr;
  11143. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  11144. device_features2.pNext = &vk11_features;
  11145. vkGetPhysicalDeviceFeatures2(vkdev, &device_features2);
  11146. return vk11_features.storageBuffer16BitAccess;
  11147. }
  11148. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) {
  11149. switch (props.vendorID) {
  11150. case VK_VENDOR_ID_INTEL:
  11151. // Only allowing Xe2 GPU at the moment since Xe2 GPU can gain significant performance boost,
  11152. // while some older hardware (ex. Arc A770) has performance regressions
  11153. return arch == vk_device_architecture::INTEL_XE2;
  11154. case VK_VENDOR_ID_AMD:
  11155. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  11156. // Workaround for AMD proprietary driver reporting support on all GPUs
  11157. return arch == vk_device_architecture::AMD_RDNA3;
  11158. }
  11159. return true;
  11160. default:
  11161. return true;
  11162. }
  11163. }
  11164. // checks
  11165. #ifdef GGML_VULKAN_CHECK_RESULTS
  11166. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  11167. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  11168. return;
  11169. }
  11170. for (int j = 0; j < level; j++) {
  11171. std::cerr << " ";
  11172. }
  11173. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  11174. done.push_back(tensor);
  11175. for (int i = 0; i < GGML_MAX_SRC; i++) {
  11176. if (tensor->src[i] != nullptr) {
  11177. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  11178. }
  11179. }
  11180. }
  11181. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  11182. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  11183. return;
  11184. }
  11185. i0 = std::max(i0, 5);
  11186. i1 = std::max(i1, 5);
  11187. i2 = std::max(i2, 0);
  11188. i3 = std::max(i3, 0);
  11189. fprintf(stderr, " ");
  11190. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  11191. fprintf(stderr, "%7d ", idx1);
  11192. }
  11193. fprintf(stderr, "\n");
  11194. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  11195. fprintf(stderr, "%7d: ", idx0);
  11196. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  11197. 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]) {
  11198. float val;
  11199. if (tensor->type == GGML_TYPE_F32) {
  11200. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  11201. } else if (tensor->type == GGML_TYPE_F16) {
  11202. 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]));
  11203. } else if (tensor->type == GGML_TYPE_I32) {
  11204. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  11205. } else {
  11206. GGML_ABORT("fatal error");
  11207. }
  11208. fprintf(stderr, "% 7.2f ", val);
  11209. } else {
  11210. fprintf(stderr, " ");
  11211. }
  11212. }
  11213. fprintf(stderr, "\n");
  11214. }
  11215. }
  11216. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  11217. void * tensor_data = tensor->data;
  11218. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  11219. if (is_gpu) {
  11220. const size_t tensor_size = ggml_nbytes(tensor);
  11221. tensor_data = malloc(tensor_size);
  11222. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  11223. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  11224. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  11225. }
  11226. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  11227. 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;
  11228. if (tensor->src[0] != nullptr) {
  11229. 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;
  11230. }
  11231. if (tensor->src[1] != nullptr) {
  11232. 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;
  11233. }
  11234. std::cerr << std::endl << "Result:" << std::endl;
  11235. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  11236. std::cerr << std::endl;
  11237. std::vector<const ggml_tensor *> done;
  11238. ggml_vk_print_graph_origin(tensor, done);
  11239. if (is_gpu) {
  11240. free(tensor_data);
  11241. }
  11242. }
  11243. void * comp_result;
  11244. size_t comp_size;
  11245. size_t comp_nb[GGML_MAX_DIMS];
  11246. size_t check_counter = 0;
  11247. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  11248. ggml_tensor * tensor = cgraph->nodes[tensor_idx];
  11249. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  11250. return;
  11251. }
  11252. bool fused_rms_norm_mul = false;
  11253. int rms_norm_idx = -1;
  11254. if (ctx->num_additional_fused_ops == 1 &&
  11255. tensor->op == GGML_OP_RMS_NORM &&
  11256. cgraph->nodes[tensor_idx + 1]->op == GGML_OP_MUL) {
  11257. fused_rms_norm_mul = true;
  11258. tensor = cgraph->nodes[tensor_idx + 1];
  11259. }
  11260. check_counter++;
  11261. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  11262. return;
  11263. }
  11264. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  11265. ggml_tensor * src0 = tensor->src[0];
  11266. ggml_tensor * src1 = tensor->src[1];
  11267. struct ggml_init_params iparams = {
  11268. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  11269. /*.mem_buffer =*/ NULL,
  11270. /*.no_alloc =*/ false,
  11271. };
  11272. struct ggml_context * ggml_ctx = ggml_init(iparams);
  11273. std::array<struct ggml_tensor *, 6> src_clone = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  11274. std::array<size_t, 6> src_size = {0, 0, 0, 0, 0, 0};
  11275. std::array<void *, 6> src_buffer = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  11276. const char * srci_name[6] = {"src0", "src1", "src2", "src3", "src4", "src5"};
  11277. struct ggml_tensor * tensor_clone = nullptr;
  11278. for (int i = 0; i < 6; i++) {
  11279. ggml_tensor * srci = tensor->src[i];
  11280. if (fused_rms_norm_mul) {
  11281. rms_norm_idx = tensor->src[0]->op == GGML_OP_RMS_NORM ? 0 : 1;
  11282. ggml_tensor *rms_norm = tensor->src[rms_norm_idx];
  11283. switch (i) {
  11284. case 0: srci = rms_norm->src[0]; break;
  11285. case 1: srci = tensor->src[1 - rms_norm_idx]; break;
  11286. default: continue;
  11287. }
  11288. }
  11289. if (srci == nullptr) {
  11290. continue;
  11291. }
  11292. ggml_tensor * srci_clone = ggml_dup_tensor(ggml_ctx, srci);
  11293. size_t srci_size = ggml_nbytes(srci);
  11294. src_clone[i] = srci_clone;
  11295. src_size[i] = ggml_nbytes(srci);
  11296. src_buffer[i] = malloc(srci_size);
  11297. srci_clone->data = src_buffer[i];
  11298. if (ggml_backend_buffer_is_host(srci->buffer)) {
  11299. memcpy(srci_clone->data, srci->data, srci_size);
  11300. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  11301. } else if (ggml_backend_buffer_is_vk(srci->buffer)) {
  11302. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)srci->buffer->context;
  11303. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  11304. uint64_t offset = vk_tensor_offset(srci) + srci->view_offs;
  11305. if (!ggml_is_contiguous(srci) && ggml_vk_dim01_contiguous(srci)) {
  11306. for (int i3 = 0; i3 < srci->ne[3]; i3++) {
  11307. for (int i2 = 0; i2 < srci->ne[2]; i2++) {
  11308. const int idx = i3*srci->ne[2] + i2;
  11309. ggml_vk_buffer_read(buffer_gpu, offset + idx * srci->nb[2], ((char *)srci_clone->data + idx * srci_clone->nb[2]), srci->ne[1] * srci->nb[1]);
  11310. }
  11311. }
  11312. srci_clone->nb[0] = srci->nb[0];
  11313. srci_clone->nb[1] = srci->nb[1];
  11314. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  11315. srci_clone->nb[i] = srci_clone->nb[i - 1]*srci_clone->ne[i - 1];
  11316. }
  11317. } else {
  11318. if (offset + srci_size >= buffer_gpu->size) {
  11319. srci_size = buffer_gpu->size - offset;
  11320. }
  11321. ggml_vk_buffer_read(buffer_gpu, offset, srci_clone->data, srci_size);
  11322. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  11323. }
  11324. } else {
  11325. GGML_ABORT("fatal error");
  11326. }
  11327. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  11328. ggml_vk_print_tensor(srci, srci_name[i]);
  11329. }
  11330. }
  11331. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  11332. const float * params = (const float *)tensor->op_params;
  11333. tensor_clone = ggml_flash_attn_ext(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3], params[0], params[1], params[2]);
  11334. if (src_clone[4]) {
  11335. ggml_flash_attn_ext_add_sinks(tensor_clone, src_clone[4]);
  11336. }
  11337. } else if (tensor->op == GGML_OP_MUL_MAT) {
  11338. tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
  11339. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  11340. tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  11341. } else if (tensor->op == GGML_OP_SUB) {
  11342. tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
  11343. } else if (tensor->op == GGML_OP_MUL) {
  11344. if (fused_rms_norm_mul) {
  11345. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->src[rms_norm_idx]->op_params);
  11346. tensor_clone = ggml_mul(ggml_ctx, tensor_clone, src_clone[1 - rms_norm_idx]);
  11347. } else {
  11348. tensor_clone = ggml_mul(ggml_ctx, src_clone[0], src_clone[1]);
  11349. }
  11350. } else if (tensor->op == GGML_OP_DIV) {
  11351. tensor_clone = ggml_div(ggml_ctx, src_clone[0], src_clone[1]);
  11352. } else if (tensor->op == GGML_OP_CONCAT) {
  11353. tensor_clone = ggml_concat(ggml_ctx, src_clone[0], src_clone[1], *(int *)tensor->op_params);
  11354. } else if (tensor->op == GGML_OP_UPSCALE) {
  11355. tensor_clone = ggml_interpolate(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3], (ggml_scale_mode) tensor->op_params[0]);
  11356. } else if (tensor->op == GGML_OP_SCALE) {
  11357. const float * params = (const float *)tensor->op_params;
  11358. tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]);
  11359. } else if (tensor->op == GGML_OP_SQR) {
  11360. tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]);
  11361. } else if (tensor->op == GGML_OP_SQRT) {
  11362. tensor_clone = ggml_sqrt(ggml_ctx, src_clone[0]);
  11363. } else if (tensor->op == GGML_OP_SIN) {
  11364. tensor_clone = ggml_sin(ggml_ctx, src_clone[0]);
  11365. } else if (tensor->op == GGML_OP_COS) {
  11366. tensor_clone = ggml_cos(ggml_ctx, src_clone[0]);
  11367. } else if (tensor->op == GGML_OP_CLAMP) {
  11368. const float * params = (const float *)tensor->op_params;
  11369. tensor_clone = ggml_clamp(ggml_ctx, src_clone[0], params[0], params[1]);
  11370. } else if (tensor->op == GGML_OP_PAD) {
  11371. tensor_clone = ggml_pad_ext(ggml_ctx, src_clone[0], tensor->op_params[0], tensor->op_params[1], tensor->op_params[2], tensor->op_params[3],
  11372. tensor->op_params[4], tensor->op_params[5], tensor->op_params[6], tensor->op_params[7]);
  11373. } else if (tensor->op == GGML_OP_REPEAT) {
  11374. tensor_clone = ggml_repeat(ggml_ctx, src_clone[0], tensor);
  11375. } else if (tensor->op == GGML_OP_REPEAT_BACK) {
  11376. tensor_clone = ggml_repeat_back(ggml_ctx, src_clone[0], tensor);
  11377. } else if (tensor->op == GGML_OP_ADD) {
  11378. tensor_clone = ggml_add(ggml_ctx, src_clone[0], src_clone[1]);
  11379. } else if (tensor->op == GGML_OP_ACC) {
  11380. tensor_clone = ggml_acc(ggml_ctx, src_clone[0], src_clone[1], tensor->op_params[0], tensor->op_params[1], tensor->op_params[2], tensor->op_params[3]);
  11381. } else if (tensor->op == GGML_OP_NORM) {
  11382. tensor_clone = ggml_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  11383. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  11384. const float * float_params = (const float *)tensor->op_params;
  11385. tensor_clone = ggml_group_norm(ggml_ctx, src_clone[0], tensor->op_params[0], float_params[1]);
  11386. } else if (tensor->op == GGML_OP_RMS_NORM) {
  11387. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  11388. } else if (tensor->op == GGML_OP_RMS_NORM_BACK) {
  11389. const float eps = ((float *) tensor->op_params)[0];
  11390. tensor_clone = ggml_rms_norm_back(ggml_ctx, src_clone[0], src_clone[1], eps);
  11391. } else if (tensor->op == GGML_OP_SILU_BACK) {
  11392. tensor_clone = ggml_silu_back(ggml_ctx, src_clone[0], src_clone[1]);
  11393. } else if (tensor->op == GGML_OP_L2_NORM) {
  11394. const float eps = ((float *) tensor->op_params)[0];
  11395. tensor_clone = ggml_l2_norm(ggml_ctx, src_clone[0], eps);
  11396. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  11397. if (src1 != nullptr) {
  11398. const float * params = (const float *)tensor->op_params;
  11399. tensor_clone = ggml_soft_max_ext(ggml_ctx, src_clone[0], src_clone[1], params[0], params[1]);
  11400. } else {
  11401. tensor_clone = ggml_soft_max(ggml_ctx, src_clone[0]);
  11402. }
  11403. } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) {
  11404. tensor_clone = ggml_soft_max_ext_back(ggml_ctx, src_clone[0], src_clone[1], ((float *)tensor->op_params)[0], ((float *)tensor->op_params)[1]);
  11405. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  11406. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]);
  11407. } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) {
  11408. const int n_dims = ((int32_t *) tensor->op_params)[1];
  11409. const int mode = ((int32_t *) tensor->op_params)[2];
  11410. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  11411. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  11412. const float freq_base = ((float *) tensor->op_params)[5];
  11413. const float freq_scale = ((float *) tensor->op_params)[6];
  11414. const float ext_factor = ((float *) tensor->op_params)[7];
  11415. const float attn_factor = ((float *) tensor->op_params)[8];
  11416. const float beta_fast = ((float *) tensor->op_params)[9];
  11417. const float beta_slow = ((float *) tensor->op_params)[10];
  11418. if (mode & GGML_ROPE_TYPE_MROPE) {
  11419. int32_t *sections = ((int32_t *) tensor->op_params) + 11;
  11420. if (tensor->op == GGML_OP_ROPE) {
  11421. tensor_clone = ggml_rope_multi(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, sections, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  11422. } else {
  11423. tensor_clone = ggml_rope_multi_back(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, sections, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  11424. }
  11425. } else {
  11426. if (tensor->op == GGML_OP_ROPE) {
  11427. tensor_clone = ggml_rope_ext(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  11428. } else {
  11429. tensor_clone = ggml_rope_ext_back(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], n_dims, mode, n_ctx_orig_ggml, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
  11430. }
  11431. }
  11432. } else if (tensor->op == GGML_OP_UNARY) {
  11433. switch (ggml_get_unary_op(tensor)) {
  11434. case GGML_UNARY_OP_EXP:
  11435. tensor_clone = ggml_exp(ggml_ctx, src_clone[0]);
  11436. break;
  11437. case GGML_UNARY_OP_SILU:
  11438. tensor_clone = ggml_silu(ggml_ctx, src_clone[0]);
  11439. break;
  11440. case GGML_UNARY_OP_GELU:
  11441. tensor_clone = ggml_gelu(ggml_ctx, src_clone[0]);
  11442. break;
  11443. case GGML_UNARY_OP_GELU_ERF:
  11444. tensor_clone = ggml_gelu_erf(ggml_ctx, src_clone[0]);
  11445. break;
  11446. case GGML_UNARY_OP_GELU_QUICK:
  11447. tensor_clone = ggml_gelu_quick(ggml_ctx, src_clone[0]);
  11448. break;
  11449. case GGML_UNARY_OP_RELU:
  11450. tensor_clone = ggml_relu(ggml_ctx, src_clone[0]);
  11451. break;
  11452. case GGML_UNARY_OP_TANH:
  11453. tensor_clone = ggml_tanh(ggml_ctx, src_clone[0]);
  11454. break;
  11455. case GGML_UNARY_OP_SIGMOID:
  11456. tensor_clone = ggml_sigmoid(ggml_ctx, src_clone[0]);
  11457. break;
  11458. case GGML_UNARY_OP_HARDSIGMOID:
  11459. tensor_clone = ggml_hardsigmoid(ggml_ctx, src_clone[0]);
  11460. break;
  11461. case GGML_UNARY_OP_HARDSWISH:
  11462. tensor_clone = ggml_hardswish(ggml_ctx, src_clone[0]);
  11463. break;
  11464. default:
  11465. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  11466. GGML_ABORT("fatal error");
  11467. }
  11468. } else if (tensor->op == GGML_OP_GLU) {
  11469. if (src_clone[1] == nullptr) {
  11470. tensor_clone = ggml_glu(ggml_ctx, src_clone[0], (ggml_glu_op) tensor->op_params[0], tensor->op_params[1]);
  11471. } else {
  11472. tensor_clone = ggml_glu_split(ggml_ctx, src_clone[0], src_clone[1], (ggml_glu_op) tensor->op_params[0]);
  11473. }
  11474. ggml_set_op_params_i32(tensor_clone, 2, ggml_get_op_params_i32(tensor, 2));
  11475. ggml_set_op_params_i32(tensor_clone, 3, ggml_get_op_params_i32(tensor, 3));
  11476. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  11477. if (src1 == nullptr) {
  11478. tensor_clone = ggml_dup(ggml_ctx, src_clone[0]);
  11479. tensor_clone->type = tensor->type;
  11480. } else {
  11481. tensor_clone = ggml_cpy(ggml_ctx, src_clone[0], src_clone[1]);
  11482. }
  11483. } else if (tensor->op == GGML_OP_CONT) {
  11484. tensor_clone = ggml_cont_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  11485. } else if (tensor->op == GGML_OP_RESHAPE) {
  11486. tensor_clone = ggml_reshape_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  11487. } else if (tensor->op == GGML_OP_VIEW) {
  11488. tensor_clone = ggml_view_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3], tensor->nb[1], tensor->nb[2], tensor->nb[3], ((int32_t *) tensor->op_params)[0]);
  11489. } else if (tensor->op == GGML_OP_PERMUTE) {
  11490. int32_t * params = (int32_t *)tensor->op_params;
  11491. tensor_clone = ggml_permute(ggml_ctx, src_clone[0], params[0], params[1], params[2], params[3]);
  11492. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  11493. tensor_clone = ggml_transpose(ggml_ctx, src_clone[0]);
  11494. } else if (tensor->op == GGML_OP_GET_ROWS) {
  11495. tensor_clone = ggml_get_rows(ggml_ctx, src_clone[0], src_clone[1]);
  11496. } else if (tensor->op == GGML_OP_ARGSORT) {
  11497. tensor_clone = ggml_argsort(ggml_ctx, src_clone[0], (ggml_sort_order) *(int *)tensor->op_params);
  11498. } else if (tensor->op == GGML_OP_SUM) {
  11499. tensor_clone = ggml_sum(ggml_ctx, src_clone[0]);
  11500. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  11501. tensor_clone = ggml_sum_rows(ggml_ctx, src_clone[0]);
  11502. } else if (tensor->op == GGML_OP_MEAN) {
  11503. tensor_clone = ggml_mean(ggml_ctx, src_clone[0]);
  11504. } else if (tensor->op == GGML_OP_ARGMAX) {
  11505. tensor_clone = ggml_argmax(ggml_ctx, src_clone[0]);
  11506. } else if (tensor->op == GGML_OP_COUNT_EQUAL) {
  11507. tensor_clone = ggml_count_equal(ggml_ctx, src_clone[0], src_clone[1]);
  11508. } else if (tensor->op == GGML_OP_IM2COL) {
  11509. const int32_t s0 = tensor->op_params[0];
  11510. const int32_t s1 = tensor->op_params[1];
  11511. const int32_t p0 = tensor->op_params[2];
  11512. const int32_t p1 = tensor->op_params[3];
  11513. const int32_t d0 = tensor->op_params[4];
  11514. const int32_t d1 = tensor->op_params[5];
  11515. const bool is_2D = tensor->op_params[6] == 1;
  11516. tensor_clone = ggml_im2col(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  11517. } else if (tensor->op == GGML_OP_IM2COL_3D) {
  11518. const int32_t s0 = tensor->op_params[0];
  11519. const int32_t s1 = tensor->op_params[1];
  11520. const int32_t s2 = tensor->op_params[2];
  11521. const int32_t p0 = tensor->op_params[3];
  11522. const int32_t p1 = tensor->op_params[4];
  11523. const int32_t p2 = tensor->op_params[5];
  11524. const int32_t d0 = tensor->op_params[6];
  11525. const int32_t d1 = tensor->op_params[7];
  11526. const int32_t d2 = tensor->op_params[8];
  11527. const int32_t IC = tensor->op_params[9];
  11528. tensor_clone = ggml_im2col_3d(ggml_ctx, src_clone[0], src_clone[1], IC, s0, s1, s2, p0, p1, p2, d0, d1, d2, tensor->type);
  11529. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  11530. const int32_t dim = tensor->op_params[0];
  11531. const int32_t max_period = tensor->op_params[1];
  11532. tensor_clone = ggml_timestep_embedding(ggml_ctx, src_clone[0], dim, max_period);
  11533. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_1D){
  11534. const int32_t s0 = tensor->op_params[0];
  11535. const int32_t p0 = tensor->op_params[1];
  11536. const int32_t d0 = tensor->op_params[2];
  11537. tensor_clone = ggml_conv_transpose_1d(ggml_ctx, src_clone[0], src_clone[1], s0, p0, d0);
  11538. } else if (tensor->op == GGML_OP_POOL_2D) {
  11539. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  11540. const int32_t k0 = tensor->op_params[1];
  11541. const int32_t k1 = tensor->op_params[2];
  11542. const int32_t s0 = tensor->op_params[3];
  11543. const int32_t s1 = tensor->op_params[4];
  11544. const int32_t p0 = tensor->op_params[5];
  11545. const int32_t p1 = tensor->op_params[6];
  11546. tensor_clone = ggml_pool_2d(ggml_ctx, src_clone[0], op, k0, k1, s0, s1, p0, p1);
  11547. } else if (tensor->op == GGML_OP_CONV_2D) {
  11548. const int32_t s0 = tensor->op_params[0];
  11549. const int32_t s1 = tensor->op_params[1];
  11550. const int32_t p0 = tensor->op_params[2];
  11551. const int32_t p1 = tensor->op_params[3];
  11552. const int32_t d0 = tensor->op_params[4];
  11553. const int32_t d1 = tensor->op_params[5];
  11554. tensor_clone = ggml_conv_2d(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  11555. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_2D) {
  11556. const int32_t s = tensor->op_params[0];
  11557. tensor_clone = ggml_conv_transpose_2d_p0(ggml_ctx, src_clone[0], src_clone[1], s);
  11558. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  11559. const float * op_params = (const float *)tensor->op_params;
  11560. tensor_clone = ggml_leaky_relu(ggml_ctx, src_clone[0], op_params[0], false);
  11561. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  11562. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, src_clone[0], src_clone[1],
  11563. src_clone[2], src_clone[3], src_clone[4], src_clone[5]);
  11564. } else if (tensor->op == GGML_OP_RWKV_WKV7) {
  11565. tensor_clone = ggml_rwkv_wkv7(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3],
  11566. src_clone[4], src_clone[5], src_clone[6]);
  11567. } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
  11568. src_clone[0]->flags = src0->flags;
  11569. tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
  11570. src_clone[2], src_clone[3], src_clone[4]);
  11571. } else if (tensor->op == GGML_OP_OPT_STEP_SGD) {
  11572. src_clone[0]->flags = src0->flags;
  11573. tensor_clone = ggml_opt_step_sgd(ggml_ctx, src_clone[0], src_clone[1],
  11574. src_clone[2]);
  11575. } else if (tensor->op == GGML_OP_ADD_ID) {
  11576. tensor_clone = ggml_add_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  11577. }
  11578. else {
  11579. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  11580. GGML_ABORT("fatal error");
  11581. }
  11582. ggml_cgraph * cgraph_cpu = ggml_new_graph(ggml_ctx);
  11583. ggml_build_forward_expand(cgraph_cpu, tensor_clone);
  11584. ggml_graph_compute_with_ctx(ggml_ctx, cgraph_cpu, 8);
  11585. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  11586. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  11587. }
  11588. comp_size = ggml_nbytes(tensor_clone);
  11589. comp_result = malloc(comp_size);
  11590. memcpy(comp_result, tensor_clone->data, comp_size);
  11591. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  11592. for (int i = 0; i < 6; i++) {
  11593. if (src_buffer[i] != nullptr) {
  11594. free(src_buffer[i]);
  11595. }
  11596. }
  11597. ggml_free(ggml_ctx);
  11598. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  11599. }
  11600. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  11601. ggml_tensor * tensor = cgraph->nodes[tensor_idx];
  11602. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  11603. return;
  11604. }
  11605. if (ctx->num_additional_fused_ops == 1 &&
  11606. tensor->op == GGML_OP_RMS_NORM &&
  11607. cgraph->nodes[tensor_idx + 1]->op == GGML_OP_MUL) {
  11608. tensor = cgraph->nodes[tensor_idx + 1];
  11609. }
  11610. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  11611. return;
  11612. }
  11613. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  11614. ggml_tensor * src0 = tensor->src[0];
  11615. ggml_tensor * src1 = tensor->src[1];
  11616. ggml_tensor * src2 = tensor->src[2];
  11617. ggml_tensor * src3 = tensor->src[3];
  11618. void * tensor_data = tensor->data;
  11619. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  11620. size_t tensor_size = ggml_nbytes(tensor);
  11621. tensor_data = malloc(tensor_size);
  11622. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  11623. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  11624. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  11625. if (offset + tensor_size >= buffer_gpu->size) {
  11626. tensor_size = buffer_gpu->size - offset;
  11627. }
  11628. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  11629. }
  11630. float first_error_result = -1.0f;
  11631. float first_error_correct = -1.0f;
  11632. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  11633. double avg_err = 0.0;
  11634. size_t counter = 0;
  11635. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  11636. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  11637. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  11638. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  11639. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  11640. float correct = 0.0f;
  11641. float result = 0.0f;
  11642. if (buffer_size_fit) {
  11643. if (tensor->type == GGML_TYPE_F32) {
  11644. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  11645. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  11646. } else if (tensor->type == GGML_TYPE_F16) {
  11647. 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]));
  11648. 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]));
  11649. } else if (tensor->type == GGML_TYPE_BF16) {
  11650. correct = ggml_bf16_to_fp32(*(ggml_bf16_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]));
  11651. result = ggml_bf16_to_fp32(*(ggml_bf16_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]));
  11652. } else if (tensor->type == GGML_TYPE_I32) {
  11653. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  11654. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  11655. } else if (tensor->type == GGML_TYPE_I64) {
  11656. correct = *(int64_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  11657. result = *(int64_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  11658. } else {
  11659. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  11660. }
  11661. } else {
  11662. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  11663. GGML_ABORT("fatal error");
  11664. }
  11665. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  11666. 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;
  11667. 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;
  11668. if (src0 != nullptr) {
  11669. 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;
  11670. }
  11671. if (src1 != nullptr) {
  11672. 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;
  11673. }
  11674. if (src2 != nullptr) {
  11675. 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;
  11676. }
  11677. if (src3 != nullptr) {
  11678. 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;
  11679. }
  11680. 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;
  11681. std::cerr << std::endl << "Result:" << std::endl;
  11682. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  11683. std::cerr << std::endl << "Correct:" << std::endl;
  11684. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  11685. std::cerr << std::endl;
  11686. std::vector<const ggml_tensor *> done;
  11687. ggml_vk_print_graph_origin(tensor, done);
  11688. GGML_ABORT("fatal error");
  11689. }
  11690. const double denom = std::fabs(correct) > 1.0f ? (std::fabs(correct) > 1e-8 ? std::fabs(correct) : 1e-8) : 1.0f;
  11691. if (first_error[0] == -1 && std::fabs(correct - result) / denom > 0.5) {
  11692. first_error[0] = i0;
  11693. first_error[1] = i1;
  11694. first_error[2] = i2;
  11695. first_error[3] = i3;
  11696. first_error_result = result;
  11697. first_error_correct = correct;
  11698. }
  11699. // Special case, value is infinite, avoid NaN result in avg_err
  11700. // NaN also appears in results, if both are nan error is 0
  11701. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  11702. avg_err += std::fabs(correct - result) / denom;
  11703. }
  11704. counter++;
  11705. }
  11706. }
  11707. }
  11708. }
  11709. avg_err /= counter;
  11710. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  11711. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  11712. 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;
  11713. if (src0 != nullptr) {
  11714. 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;
  11715. }
  11716. if (src1 != nullptr) {
  11717. 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;
  11718. }
  11719. if (src2 != nullptr) {
  11720. 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;
  11721. }
  11722. if (src3 != nullptr) {
  11723. 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;
  11724. }
  11725. 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;
  11726. std::cerr << std::endl << "Result:" << std::endl;
  11727. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  11728. std::cerr << std::endl << "Correct:" << std::endl;
  11729. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  11730. std::cerr << std::endl;
  11731. std::vector<const ggml_tensor *> done;
  11732. ggml_vk_print_graph_origin(tensor, done);
  11733. }
  11734. if (avg_err > 0.5 || std::isnan(avg_err)) {
  11735. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  11736. 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;
  11737. if (src0 != nullptr) {
  11738. 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;
  11739. }
  11740. if (src1 != nullptr) {
  11741. 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;
  11742. }
  11743. if (src2 != nullptr) {
  11744. 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;
  11745. }
  11746. if (src3 != nullptr) {
  11747. 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;
  11748. }
  11749. 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;
  11750. std::cerr << std::endl << "Result:" << std::endl;
  11751. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  11752. std::cerr << std::endl << "Correct:" << std::endl;
  11753. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  11754. std::cerr << std::endl;
  11755. std::vector<const ggml_tensor *> done;
  11756. ggml_vk_print_graph_origin(tensor, done);
  11757. GGML_ABORT("fatal error");
  11758. } else {
  11759. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  11760. }
  11761. free(comp_result);
  11762. comp_result = nullptr;
  11763. comp_size = 0;
  11764. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  11765. free(tensor_data);
  11766. }
  11767. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  11768. }
  11769. #endif
  11770. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)