ggml-vulkan.cpp 681 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753
  1. #include "ggml-vulkan.h"
  2. #include <vulkan/vulkan_core.h>
  3. #if defined(GGML_VULKAN_RUN_TESTS) || defined(GGML_VULKAN_CHECK_RESULTS)
  4. #include <chrono>
  5. #include "ggml-cpu.h"
  6. #endif
  7. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  8. #define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
  9. // We use VULKAN_HPP_DEFAULT_DISPATCHER, but not VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
  10. // to avoid conflicts with applications or other libraries who might use it.
  11. namespace vk::detail { class DispatchLoaderDynamic; }
  12. vk::detail::DispatchLoaderDynamic & ggml_vk_default_dispatcher();
  13. #define VULKAN_HPP_DEFAULT_DISPATCHER ggml_vk_default_dispatcher()
  14. #include <vulkan/vulkan.hpp>
  15. #include <algorithm>
  16. #include <cmath>
  17. #include <iomanip>
  18. #include <iostream>
  19. #include <tuple>
  20. #include <vector>
  21. #include <sstream>
  22. #include <utility>
  23. #include <memory>
  24. #include <limits>
  25. #include <map>
  26. #include <unordered_map>
  27. #include <memory>
  28. #include <mutex>
  29. #include <future>
  30. #include <thread>
  31. #if defined(_MSC_VER)
  32. # define NOMINMAX 1
  33. # include <windows.h>
  34. # define YIELD() YieldProcessor()
  35. #elif defined(__clang__) || defined(__GNUC__)
  36. # if defined(__x86_64__) ||defined(__i386__)
  37. # include <immintrin.h>
  38. # define YIELD() _mm_pause()
  39. # elif defined(__arm__) || defined(__aarch64__)
  40. # if defined(__clang__)
  41. # include <arm_acle.h>
  42. # define YIELD() __yield()
  43. # else
  44. # define YIELD() asm volatile("yield")
  45. # endif
  46. # endif
  47. #endif
  48. #if !defined(YIELD)
  49. #define YIELD()
  50. #endif
  51. #include "ggml-impl.h"
  52. #include "ggml-backend-impl.h"
  53. #include "ggml-vulkan-shaders.hpp"
  54. // remove this once it's more widely available in the SDK
  55. #if !defined(VK_KHR_shader_bfloat16)
  56. #define VK_KHR_shader_bfloat16 1
  57. #define VK_KHR_SHADER_BFLOAT16_SPEC_VERSION 1
  58. #define VK_KHR_SHADER_BFLOAT16_EXTENSION_NAME "VK_KHR_shader_bfloat16"
  59. #define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR ((VkStructureType)1000141000)
  60. #define VK_COMPONENT_TYPE_BFLOAT16_KHR ((VkComponentTypeKHR)1000141000)
  61. typedef struct VkPhysicalDeviceShaderBfloat16FeaturesKHR {
  62. VkStructureType sType;
  63. void* pNext;
  64. VkBool32 shaderBFloat16Type;
  65. VkBool32 shaderBFloat16DotProduct;
  66. VkBool32 shaderBFloat16CooperativeMatrix;
  67. } VkPhysicalDeviceShaderBfloat16FeaturesKHR;
  68. #endif
  69. #define ROUNDUP_POW2(M, N) (((M) + (N) - 1) & ~((N) - 1))
  70. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  71. static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; }
  72. #define VK_VENDOR_ID_AMD 0x1002
  73. #define VK_VENDOR_ID_APPLE 0x106b
  74. #define VK_VENDOR_ID_INTEL 0x8086
  75. #define VK_VENDOR_ID_NVIDIA 0x10de
  76. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 256
  77. #define GGML_VK_MAX_NODES 8192
  78. #define MAX_VK_BUFFERS 256
  79. #define VK_CHECK(err, msg) \
  80. do { \
  81. vk::Result err_ = (err); \
  82. if (err_ != vk::Result::eSuccess) { \
  83. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  84. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  85. exit(1); \
  86. } \
  87. } while (0)
  88. #ifdef GGML_VULKAN_DEBUG
  89. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  90. #else
  91. #define VK_LOG_DEBUG(msg) ((void) 0)
  92. #endif // GGML_VULKAN_DEBUG
  93. struct ggml_backend_vk_context;
  94. #define MAX_PARAMETER_COUNT 12
  95. // Max number of adds that can be fused without exceeding MAX_PARAMETER_COUNT.
  96. #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3)
  97. struct vk_pipeline_struct {
  98. std::string name;
  99. vk::ShaderModule shader_module;
  100. vk::PipelineLayout layout;
  101. vk::Pipeline pipeline;
  102. uint32_t push_constant_size;
  103. uint32_t parameter_count;
  104. std::array<uint32_t, 3> wg_denoms;
  105. uint32_t align;
  106. // true if fields have been set by ggml_vk_create_pipeline
  107. bool initialized {};
  108. // set to true to request the pipeline is compiled after the dryrun
  109. bool needed {};
  110. // set to true when the shader has been compiled
  111. bool compiled {};
  112. // number of registers used, extracted from pipeline executable properties
  113. uint32_t register_count {};
  114. };
  115. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  116. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  117. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  118. struct vk_matmul_pipeline_struct {
  119. vk_pipeline l, m, s;
  120. vk_pipeline a_l, a_m, a_s;
  121. };
  122. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  123. struct vk_matmul_pipeline2 {
  124. vk_matmul_pipeline2() {
  125. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  126. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  127. }
  128. vk_matmul_pipeline f32acc;
  129. vk_matmul_pipeline f16acc;
  130. };
  131. struct vk_device_struct;
  132. typedef std::shared_ptr<vk_device_struct> vk_device;
  133. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  134. struct vk_buffer_struct;
  135. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  136. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  137. struct ggml_backend_vk_buffer_type_context {
  138. std::string name;
  139. vk_device device;
  140. };
  141. struct vk_queue;
  142. // Stores command pool/buffers. There's an instance of this
  143. // for each (context,queue) pair and for each (device,queue) pair.
  144. struct vk_command_pool {
  145. void init(vk_device& device, vk_queue *q_);
  146. void destroy(vk::Device& device);
  147. vk::CommandPool pool;
  148. uint32_t cmd_buffer_idx;
  149. std::vector<vk::CommandBuffer> cmd_buffers;
  150. vk_queue *q;
  151. };
  152. // Prevent simultaneous submissions to the same queue.
  153. // This could be per vk_queue if we stopped having two vk_queue structures
  154. // sharing the same vk::Queue.
  155. static std::mutex queue_mutex;
  156. struct vk_queue {
  157. uint32_t queue_family_index;
  158. vk::Queue queue;
  159. vk_command_pool cmd_pool;
  160. vk::PipelineStageFlags stage_flags;
  161. bool transfer_only;
  162. // copy everything except the cmd_pool
  163. void copyFrom(vk_queue &other) {
  164. queue_family_index = other.queue_family_index;
  165. queue = other.queue;
  166. stage_flags = other.stage_flags;
  167. transfer_only = other.transfer_only;
  168. }
  169. };
  170. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  171. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  172. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  173. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  174. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  175. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  176. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  177. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  178. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  179. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  180. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  181. /* .is_host = */ NULL,
  182. };
  183. #ifdef GGML_VULKAN_MEMORY_DEBUG
  184. class vk_memory_logger;
  185. #endif
  186. class vk_perf_logger;
  187. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  188. static constexpr uint32_t mul_mat_vec_max_cols = 8;
  189. static constexpr uint32_t p021_max_gqa_ratio = 8;
  190. enum vk_device_architecture {
  191. OTHER,
  192. AMD_GCN,
  193. AMD_RDNA1,
  194. AMD_RDNA2,
  195. AMD_RDNA3,
  196. INTEL_XE2,
  197. NVIDIA_PRE_TURING,
  198. };
  199. static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) {
  200. vk::PhysicalDeviceProperties props = device.getProperties();
  201. if (props.vendorID == VK_VENDOR_ID_AMD) {
  202. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  203. bool amd_shader_core_properties = false;
  204. bool integer_dot_product = false;
  205. bool subgroup_size_control = false;
  206. for (const auto& properties : ext_props) {
  207. if (strcmp("VK_AMD_shader_core_properties", properties.extensionName) == 0) {
  208. amd_shader_core_properties = true;
  209. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0) {
  210. integer_dot_product = true;
  211. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  212. subgroup_size_control = true;
  213. }
  214. }
  215. if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) {
  216. return vk_device_architecture::OTHER;
  217. }
  218. vk::PhysicalDeviceProperties2 props2;
  219. vk::PhysicalDeviceShaderCorePropertiesAMD shader_core_props_amd;
  220. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR integer_dot_props;
  221. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  222. props2.pNext = &shader_core_props_amd;
  223. shader_core_props_amd.pNext = &integer_dot_props;
  224. integer_dot_props.pNext = &subgroup_size_control_props;
  225. device.getProperties2(&props2);
  226. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 64) {
  227. return vk_device_architecture::AMD_GCN;
  228. }
  229. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 32) {
  230. // RDNA
  231. if (shader_core_props_amd.wavefrontsPerSimd == 20) {
  232. return vk_device_architecture::AMD_RDNA1;
  233. }
  234. if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
  235. return vk_device_architecture::AMD_RDNA3;
  236. }
  237. return vk_device_architecture::AMD_RDNA2;
  238. }
  239. } else if (props.vendorID == VK_VENDOR_ID_INTEL) {
  240. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  241. bool subgroup_size_control = false;
  242. for (const auto& properties : ext_props) {
  243. if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  244. subgroup_size_control = true;
  245. }
  246. }
  247. if (!subgroup_size_control) {
  248. return vk_device_architecture::OTHER;
  249. }
  250. vk::PhysicalDeviceProperties2 props2;
  251. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  252. props2.pNext = &subgroup_size_control_props;
  253. device.getProperties2(&props2);
  254. if (subgroup_size_control_props.minSubgroupSize == 16) {
  255. // Xe2 architecture uses SIMD16 while previous Xe and Gen architecture uses SIMD8.
  256. // Minimum subgroup size matches the SIMD width so we distinguish architecture by checking this value.
  257. // https://www.intel.com/content/www/us/en/content-details/824434/2024-intel-tech-tour-xe2-and-lunar-lake-s-gpu.html
  258. // https://www.intel.com/content/www/us/en/docs/oneapi/optimization-guide-gpu/2025-0/intel-xe-gpu-architecture.html
  259. return vk_device_architecture::INTEL_XE2;
  260. }
  261. } else if (props.vendorID == VK_VENDOR_ID_NVIDIA) {
  262. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  263. bool cooperative_matrix = false;
  264. // Detect "pre-turing" based on lack of coopmat support.
  265. for (const auto& properties : ext_props) {
  266. if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0) {
  267. cooperative_matrix = true;
  268. break;
  269. }
  270. }
  271. if (!cooperative_matrix) {
  272. return vk_device_architecture::NVIDIA_PRE_TURING;
  273. }
  274. }
  275. return vk_device_architecture::OTHER;
  276. }
  277. enum vk_conv_shapes {
  278. CONV_SHAPE_128x128,
  279. CONV_SHAPE_64x32,
  280. CONV_SHAPE_32x256,
  281. CONV_SHAPE_COUNT,
  282. };
  283. enum dmmv_wg_sizes {
  284. DMMV_WG_SIZE_SUBGROUP,
  285. DMMV_WG_SIZE_LARGE,
  286. DMMV_WG_SIZE_COUNT,
  287. };
  288. enum FaCodePath {
  289. FA_SCALAR,
  290. FA_COOPMAT1,
  291. FA_COOPMAT2,
  292. };
  293. struct vk_fa_pipeline_state {
  294. vk_fa_pipeline_state(uint32_t HSK, uint32_t HSV, bool small_rows, FaCodePath path, bool aligned, bool f32acc)
  295. : HSK(HSK), HSV(HSV), small_rows(small_rows), path(path), aligned(aligned), f32acc(f32acc) {}
  296. uint32_t HSK, HSV;
  297. bool small_rows;
  298. FaCodePath path;
  299. bool aligned;
  300. bool f32acc;
  301. bool operator<(const vk_fa_pipeline_state &b) const {
  302. return std::tie(HSK, HSV, small_rows, path, aligned, f32acc) <
  303. std::tie(b.HSK, b.HSV, b.small_rows, b.path, b.aligned, b.f32acc);
  304. }
  305. };
  306. enum shader_reduction_mode {
  307. SHADER_REDUCTION_MODE_SHMEM,
  308. SHADER_REDUCTION_MODE_HYBRID,
  309. SHADER_REDUCTION_MODE_SUBGROUP,
  310. SHADER_REDUCTION_MODE_COUNT,
  311. };
  312. static constexpr uint32_t num_argsort_pipelines = 11;
  313. static constexpr uint32_t max_argsort_cols = 1 << (num_argsort_pipelines-1);
  314. struct vk_device_struct {
  315. std::recursive_mutex mutex;
  316. vk::PhysicalDevice physical_device;
  317. vk::PhysicalDeviceProperties properties;
  318. std::string name;
  319. uint64_t max_memory_allocation_size;
  320. uint64_t suballocation_block_size;
  321. bool fp16;
  322. bool bf16;
  323. bool pipeline_robustness;
  324. vk::Device device;
  325. uint32_t vendor_id;
  326. vk::DriverId driver_id;
  327. vk_device_architecture architecture;
  328. vk_queue compute_queue;
  329. vk_queue transfer_queue;
  330. bool single_queue;
  331. uint32_t subgroup_size;
  332. uint32_t shader_core_count;
  333. bool uma;
  334. bool prefer_host_memory;
  335. bool float_controls_rte_fp16;
  336. bool subgroup_arithmetic;
  337. bool subgroup_shuffle;
  338. bool subgroup_ballot;
  339. bool subgroup_clustered;
  340. bool multi_add;
  341. bool shader_int64;
  342. bool buffer_device_address;
  343. bool add_rms_fusion;
  344. uint32_t partials_binding_alignment;
  345. bool integer_dot_product;
  346. // 0: default, 1: force mmvq, -1: disable mmvq
  347. int32_t mmvq_mode;
  348. bool subgroup_size_control;
  349. uint32_t subgroup_min_size;
  350. uint32_t subgroup_max_size;
  351. bool subgroup_require_full_support;
  352. bool coopmat_support;
  353. bool coopmat_acc_f32_support {};
  354. bool coopmat_acc_f16_support {};
  355. bool coopmat_bf16_support {};
  356. bool coopmat_support_16x16x16_f16acc {};
  357. bool coopmat_support_16x16x16_f32acc {};
  358. bool coopmat1_fa_support {};
  359. uint32_t coopmat_m;
  360. uint32_t coopmat_n;
  361. uint32_t coopmat_k;
  362. bool coopmat_int_support;
  363. uint32_t coopmat_int_m;
  364. uint32_t coopmat_int_n;
  365. uint32_t coopmat_int_k;
  366. bool coopmat2;
  367. bool pipeline_executable_properties_support {};
  368. size_t idx;
  369. bool mul_mat_l[GGML_TYPE_COUNT];
  370. bool mul_mat_m[GGML_TYPE_COUNT];
  371. bool mul_mat_s[GGML_TYPE_COUNT];
  372. bool mul_mat_id_l[GGML_TYPE_COUNT];
  373. bool mul_mat_id_m[GGML_TYPE_COUNT];
  374. bool mul_mat_id_s[GGML_TYPE_COUNT];
  375. // set to true to indicate that some shaders need to be compiled after the dryrun
  376. bool need_compiles {};
  377. vk::DescriptorSetLayout dsl;
  378. vk_matmul_pipeline pipeline_matmul_f32 {};
  379. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  380. vk_matmul_pipeline pipeline_matmul_bf16 {};
  381. vk_matmul_pipeline2 pipeline_matmul_f16;
  382. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  383. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  384. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  385. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_COUNT];
  386. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  387. vk_matmul_pipeline pipeline_matmul_id_bf16 {};
  388. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  389. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  390. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  391. vk_pipeline pipeline_matmul_split_k_reduce;
  392. vk_pipeline pipeline_quantize_q8_1;
  393. vk_pipeline pipeline_quantize_q8_1_x4;
  394. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  395. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  396. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  397. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_COUNT];
  398. vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  399. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio];
  400. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  401. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  402. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  403. vk_pipeline pipeline_acc_f32;
  404. // [src0 0=fp32,1=fp16][src1 0=fp32,1=fp16][dst 0=fp32,1=fp16]
  405. vk_pipeline pipeline_add[2][2][2];
  406. vk_pipeline pipeline_add_norepeat[2][2][2];
  407. vk_pipeline pipeline_sub[2][2][2];
  408. vk_pipeline pipeline_sub_norepeat[2][2][2];
  409. vk_pipeline pipeline_mul[2][2][2];
  410. vk_pipeline pipeline_mul_norepeat[2][2][2];
  411. vk_pipeline pipeline_div[2][2][2];
  412. vk_pipeline pipeline_div_norepeat[2][2][2];
  413. vk_pipeline pipeline_add_rms[2][2][2];
  414. vk_pipeline pipeline_add_rms_norepeat[2][2][2];
  415. // indexed by num_additional_fused_ops == num_adds - 1
  416. vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS];
  417. vk_pipeline pipeline_multi_add_rms[MAX_FUSED_ADDS];
  418. vk_pipeline pipeline_add_id_f32;
  419. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  420. vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32, pipeline_upscale_bilinear_ac_f32;
  421. vk_pipeline pipeline_scale_f32;
  422. vk_pipeline pipeline_sqr_f32;
  423. vk_pipeline pipeline_sqrt_f32;
  424. vk_pipeline pipeline_sin_f32;
  425. vk_pipeline pipeline_cos_f32;
  426. vk_pipeline pipeline_clamp_f32;
  427. vk_pipeline pipeline_pad_f32;
  428. vk_pipeline pipeline_roll_f32;
  429. vk_pipeline pipeline_repeat_f32, pipeline_repeat_back_f32;
  430. 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;
  431. 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;
  432. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  433. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  434. vk_pipeline pipeline_set_rows_i32[GGML_TYPE_COUNT];
  435. vk_pipeline pipeline_set_rows_i64[GGML_TYPE_COUNT];
  436. vk_pipeline pipeline_norm_f32;
  437. vk_pipeline pipeline_group_norm_f32;
  438. vk_pipeline pipeline_rms_norm_f32;
  439. vk_pipeline pipeline_rms_norm_mul_f32;
  440. vk_pipeline pipeline_rms_norm_partials_f32;
  441. vk_pipeline pipeline_rms_norm_mul_partials_f32;
  442. vk_pipeline pipeline_rms_norm_back_f32;
  443. vk_pipeline pipeline_l2_norm_f32;
  444. // [src/dst 0=fp32,1=fp16]
  445. vk_pipeline pipeline_exp[2];
  446. vk_pipeline pipeline_gelu[2];
  447. vk_pipeline pipeline_gelu_erf[2];
  448. vk_pipeline pipeline_gelu_quick[2];
  449. vk_pipeline pipeline_silu[2];
  450. vk_pipeline pipeline_relu[2];
  451. vk_pipeline pipeline_tanh[2];
  452. vk_pipeline pipeline_sigmoid[2];
  453. vk_pipeline pipeline_hardsigmoid[2];
  454. vk_pipeline pipeline_hardswish[2];
  455. vk_pipeline pipeline_geglu[2];
  456. vk_pipeline pipeline_reglu[2];
  457. vk_pipeline pipeline_swiglu[2];
  458. vk_pipeline pipeline_swiglu_oai[2];
  459. vk_pipeline pipeline_geglu_erf[2];
  460. vk_pipeline pipeline_geglu_quick[2];
  461. vk_pipeline pipeline_leaky_relu_f32;
  462. vk_pipeline pipeline_silu_back_f32;
  463. vk_pipeline pipeline_diag_mask_inf_f32;
  464. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  465. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  466. vk_pipeline pipeline_soft_max_back_f32;
  467. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16;
  468. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16;
  469. vk_pipeline pipeline_rope_multi_f32, pipeline_rope_multi_f16;
  470. vk_pipeline pipeline_rope_vision_f32, pipeline_rope_vision_f16;
  471. vk_pipeline pipeline_argsort_f32[num_argsort_pipelines];
  472. vk_pipeline pipeline_sum_rows_f32;
  473. vk_pipeline pipeline_argmax_f32;
  474. vk_pipeline pipeline_count_equal_i32;
  475. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  476. vk_pipeline pipeline_im2col_3d_f32, pipeline_im2col_3d_f32_f16;
  477. vk_pipeline pipeline_timestep_embedding_f32;
  478. vk_pipeline pipeline_conv_transpose_1d_f32;
  479. vk_pipeline pipeline_pool2d_f32;
  480. vk_pipeline pipeline_rwkv_wkv6_f32;
  481. vk_pipeline pipeline_rwkv_wkv7_f32;
  482. vk_pipeline pipeline_opt_step_adamw_f32;
  483. vk_pipeline pipeline_opt_step_sgd_f32;
  484. vk_pipeline pipeline_conv2d_f32[CONV_SHAPE_COUNT];
  485. vk_pipeline pipeline_conv2d_f16_f32[CONV_SHAPE_COUNT];
  486. vk_pipeline pipeline_conv_transpose_2d_f32[CONV_SHAPE_COUNT];
  487. vk_pipeline pipeline_conv_transpose_2d_f16_f32[CONV_SHAPE_COUNT];
  488. vk_pipeline pipeline_conv2d_dw_whcn_f32, pipeline_conv2d_dw_whcn_f16_f32;
  489. vk_pipeline pipeline_conv2d_dw_cwhn_f32, pipeline_conv2d_dw_cwhn_f16_f32;
  490. std::map<vk_fa_pipeline_state, vk_pipeline> pipeline_flash_attn_f32_f16[GGML_TYPE_COUNT];
  491. vk_pipeline pipeline_flash_attn_split_k_reduce;
  492. std::vector<vk_pipeline_ref> all_pipelines;
  493. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  494. vk::Fence fence;
  495. vk_buffer sync_staging;
  496. ggml_backend_buffer_type buffer_type;
  497. bool disable_fusion;
  498. bool disable_host_visible_vidmem;
  499. bool allow_sysmem_fallback;
  500. bool disable_graph_optimize;
  501. #ifdef GGML_VULKAN_MEMORY_DEBUG
  502. std::unique_ptr<vk_memory_logger> memory_logger;
  503. #endif
  504. // for GGML_VK_PERF_LOGGER
  505. std::unique_ptr<vk_perf_logger> perf_logger;
  506. vk::QueryPool query_pool;
  507. int32_t num_queries;
  508. ~vk_device_struct() {
  509. VK_LOG_DEBUG("destroy device " << name);
  510. device.destroyFence(fence);
  511. ggml_vk_destroy_buffer(sync_staging);
  512. compute_queue.cmd_pool.destroy(device);
  513. transfer_queue.cmd_pool.destroy(device);
  514. for (auto& pipeline : all_pipelines) {
  515. if (pipeline.expired()) {
  516. continue;
  517. }
  518. vk_pipeline pl = pipeline.lock();
  519. ggml_vk_destroy_pipeline(device, pl);
  520. }
  521. all_pipelines.clear();
  522. device.destroyDescriptorSetLayout(dsl);
  523. device.destroy();
  524. }
  525. };
  526. void vk_command_pool::init(vk_device& device, vk_queue *q_) {
  527. cmd_buffer_idx = 0;
  528. q = q_;
  529. vk::CommandPoolCreateInfo command_pool_create_info(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), q->queue_family_index);
  530. pool = device->device.createCommandPool(command_pool_create_info);
  531. }
  532. void vk_command_pool::destroy(vk::Device& device) {
  533. device.destroyCommandPool(pool);
  534. pool = nullptr;
  535. cmd_buffers.clear();
  536. }
  537. struct vk_buffer_struct {
  538. vk::Buffer buffer = VK_NULL_HANDLE;
  539. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  540. vk::MemoryPropertyFlags memory_property_flags;
  541. void * ptr;
  542. size_t size = 0;
  543. vk::DeviceAddress bda_addr {};
  544. vk_device device;
  545. ~vk_buffer_struct() {
  546. if (size == 0) {
  547. return;
  548. }
  549. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  550. device->device.freeMemory(device_memory);
  551. device->device.destroyBuffer(buffer);
  552. }
  553. };
  554. struct vk_subbuffer {
  555. vk_buffer buffer;
  556. uint64_t offset;
  557. uint64_t size;
  558. operator vk::DescriptorBufferInfo() const {
  559. return { buffer->buffer, offset, size };
  560. }
  561. };
  562. struct vk_semaphore {
  563. vk::Semaphore s;
  564. uint64_t value;
  565. };
  566. struct vk_submission {
  567. vk::CommandBuffer buffer;
  568. std::vector<vk_semaphore> wait_semaphores;
  569. std::vector<vk_semaphore> signal_semaphores;
  570. };
  571. typedef std::vector<vk_submission> vk_sequence;
  572. struct vk_mat_mat_push_constants {
  573. uint32_t M; uint32_t N; uint32_t K;
  574. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  575. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  576. uint32_t k_split;
  577. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  578. uint32_t padded_N;
  579. };
  580. struct vk_mat_vec_push_constants {
  581. uint32_t ncols; 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 ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  584. };
  585. struct vk_mat_mat_id_push_constants {
  586. uint32_t M; uint32_t N; uint32_t K;
  587. 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 nei1; uint32_t nbi1; uint32_t ne11;
  590. uint32_t padded_N;
  591. };
  592. struct vk_mat_vec_id_push_constants {
  593. uint32_t ncols; uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  594. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  595. uint32_t nei0; uint32_t ne11;
  596. };
  597. struct vk_flash_attn_push_constants {
  598. uint32_t N;
  599. uint32_t KV;
  600. uint32_t ne1;
  601. uint32_t ne2;
  602. uint32_t ne3;
  603. uint32_t neq2;
  604. uint32_t neq3;
  605. uint32_t nek2;
  606. uint32_t nek3;
  607. uint32_t nev2;
  608. uint32_t nev3;
  609. uint32_t nem1;
  610. uint32_t nem2;
  611. uint32_t nem3;
  612. uint32_t nb01;
  613. uint32_t nb02;
  614. uint32_t nb03;
  615. uint32_t nb11;
  616. uint32_t nb12;
  617. uint32_t nb13;
  618. uint32_t nb21;
  619. uint32_t nb22;
  620. uint32_t nb23;
  621. float scale;
  622. float max_bias;
  623. float logit_softcap;
  624. uint32_t mask_n_head_log2;
  625. float m0;
  626. float m1;
  627. uint32_t gqa_ratio;
  628. uint32_t split_kv;
  629. uint32_t k_num;
  630. };
  631. static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128");
  632. struct vk_op_push_constants {
  633. uint32_t KX;
  634. uint32_t KY;
  635. float param1;
  636. float param2;
  637. };
  638. struct vk_op_glu_push_constants {
  639. uint32_t N;
  640. uint32_t ne00;
  641. uint32_t ne20;
  642. uint32_t mode; // 0: default, 1: swapped, 2: split
  643. float alpha; // for swiglu_oai
  644. float limit;
  645. };
  646. struct vk_op_unary_push_constants {
  647. uint32_t ne;
  648. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  649. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  650. uint32_t misalign_offsets;
  651. float param1; float param2;
  652. uint32_t ne0_012mp; uint32_t ne0_012L;
  653. uint32_t ne0_01mp; uint32_t ne0_01L;
  654. uint32_t ne0_0mp; uint32_t ne0_0L;
  655. uint32_t ne1_012mp; uint32_t ne1_012L;
  656. uint32_t ne1_01mp; uint32_t ne1_01L;
  657. uint32_t ne1_0mp; uint32_t ne1_0L;
  658. };
  659. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  660. static vk_op_unary_push_constants vk_op_unary_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst, int64_t ne = 0) {
  661. GGML_ASSERT(ne != 0 || (ggml_nelements(src0) == ggml_nelements(dst)));
  662. ne = ne != 0 ? ne : ggml_nelements(dst);
  663. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  664. vk_op_unary_push_constants p{};
  665. p.ne = (uint32_t)ne;
  666. size_t src0_tsize = ggml_type_size(src0->type);
  667. p.ne00 = (uint32_t)src0->ne[0];
  668. p.ne01 = (uint32_t)src0->ne[1];
  669. p.ne02 = (uint32_t)src0->ne[2];
  670. p.ne03 = (uint32_t)src0->ne[3];
  671. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  672. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  673. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  674. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  675. size_t dst_tsize = ggml_type_size(dst->type);
  676. p.ne10 = (uint32_t)dst->ne[0];
  677. p.ne11 = (uint32_t)dst->ne[1];
  678. p.ne12 = (uint32_t)dst->ne[2];
  679. p.ne13 = (uint32_t)dst->ne[3];
  680. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  681. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  682. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  683. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  684. return p; // offsets are initialized later in ggml_vk_op
  685. }
  686. struct vk_op_pad_push_constants {
  687. uint32_t ne;
  688. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  689. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  690. uint32_t misalign_offsets;
  691. uint32_t lp0; uint32_t rp0;
  692. uint32_t lp1; uint32_t rp1;
  693. uint32_t lp2; uint32_t rp2;
  694. uint32_t lp3; uint32_t rp3;
  695. };
  696. static vk_op_pad_push_constants vk_op_pad_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst) {
  697. int64_t ne = ggml_nelements(dst);
  698. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  699. vk_op_pad_push_constants p{};
  700. p.ne = (uint32_t)ne;
  701. size_t src0_tsize = ggml_type_size(src0->type);
  702. p.ne00 = (uint32_t)src0->ne[0];
  703. p.ne01 = (uint32_t)src0->ne[1];
  704. p.ne02 = (uint32_t)src0->ne[2];
  705. p.ne03 = (uint32_t)src0->ne[3];
  706. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  707. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  708. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  709. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  710. size_t dst_tsize = ggml_type_size(dst->type);
  711. p.ne10 = (uint32_t)dst->ne[0];
  712. p.ne11 = (uint32_t)dst->ne[1];
  713. p.ne12 = (uint32_t)dst->ne[2];
  714. p.ne13 = (uint32_t)dst->ne[3];
  715. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  716. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  717. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  718. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  719. p.lp0 = dst->op_params[0];
  720. p.rp0 = dst->op_params[1];
  721. p.lp1 = dst->op_params[2];
  722. p.rp1 = dst->op_params[3];
  723. p.lp2 = dst->op_params[4];
  724. p.rp2 = dst->op_params[5];
  725. p.lp3 = dst->op_params[6];
  726. p.rp3 = dst->op_params[7];
  727. return p; // fastdiv values and offsets are initialized later in ggml_vk_op
  728. }
  729. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  730. // Precompute mp (m' in the paper) and L such that division
  731. // can be computed using a multiply (high 32b of 64b result)
  732. // and a shift:
  733. //
  734. // n/d = (mulhi(n, mp) + n) >> L;
  735. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  736. {
  737. // compute L = ceil(log2(d));
  738. L = 0;
  739. while (L < 32 && (uint32_t{1} << L) < d) {
  740. L++;
  741. }
  742. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  743. }
  744. template <typename T> void init_pushconst_fastdiv(T &p) {
  745. GGML_UNUSED(p);
  746. static_assert(!std::is_const<T>::value, "unexpected type");
  747. }
  748. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  749. // Compute magic values to divide by these six numbers.
  750. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  751. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  752. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  753. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  754. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  755. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  756. }
  757. struct vk_op_binary_push_constants {
  758. uint32_t ne;
  759. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  760. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  761. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  762. uint32_t misalign_offsets;
  763. float param1; float param2; int32_t param3;
  764. };
  765. struct vk_op_multi_add_push_constants {
  766. // shape for dst
  767. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23;
  768. // strides for srcs+dst
  769. uint32_t nb[MAX_PARAMETER_COUNT][4];
  770. uint32_t rms_partials;
  771. };
  772. // update multi_add.comp if this changes
  773. static_assert(MAX_PARAMETER_COUNT == 12);
  774. static_assert(sizeof(vk_op_multi_add_push_constants) <= 256);
  775. struct vk_op_add_id_push_constants {
  776. uint32_t ne0;
  777. uint32_t ne1;
  778. uint32_t s01;
  779. uint32_t s02;
  780. uint32_t s11;
  781. uint32_t s21;
  782. };
  783. struct vk_op_diag_mask_push_constants {
  784. uint32_t ncols;
  785. uint32_t rows_per_channel;
  786. int32_t n_past;
  787. };
  788. struct vk_op_rope_push_constants {
  789. uint32_t ncols;
  790. uint32_t n_dims;
  791. float freq_scale;
  792. uint32_t p_delta_rows;
  793. float freq_base;
  794. float ext_factor;
  795. float attn_factor;
  796. float corr_dims[2];
  797. float theta_scale;
  798. uint32_t has_ff;
  799. uint32_t ne02;
  800. uint32_t s1;
  801. uint32_t s2;
  802. int32_t sections[4];
  803. uint32_t is_back;
  804. };
  805. struct vk_op_soft_max_push_constants {
  806. uint32_t KX;
  807. uint32_t KY;
  808. uint32_t ne00;
  809. uint32_t ne01;
  810. uint32_t ne02;
  811. uint32_t ne12;
  812. uint32_t ne13;
  813. uint32_t nb11;
  814. uint32_t nb12;
  815. uint32_t nb13;
  816. float scale;
  817. float max_bias;
  818. float m0;
  819. float m1;
  820. uint32_t n_head_log2;
  821. uint32_t nrows_x;
  822. uint32_t has_sinks;
  823. };
  824. struct vk_op_argsort_push_constants {
  825. uint32_t ncols;
  826. int32_t order;
  827. };
  828. struct vk_op_im2col_push_constants {
  829. uint64_t dst_addr;
  830. uint32_t batch_offset; uint32_t offset_delta;
  831. uint32_t IC;
  832. uint32_t IW; uint32_t IH;
  833. uint32_t OW; uint32_t OH;
  834. uint32_t KW; uint32_t KH;
  835. uint32_t pelements;
  836. uint32_t CHW;
  837. int32_t s0; int32_t s1;
  838. int32_t p0; int32_t p1;
  839. int32_t d0; int32_t d1;
  840. };
  841. struct vk_op_im2col_3d_push_constants {
  842. uint64_t dst_addr;
  843. uint32_t nb10;
  844. uint32_t nb11;
  845. uint32_t nb12;
  846. uint32_t nb13;
  847. uint32_t s0;
  848. uint32_t s1;
  849. uint32_t s2;
  850. uint32_t p0;
  851. uint32_t p1;
  852. uint32_t p2;
  853. uint32_t d0;
  854. uint32_t d1;
  855. uint32_t d2;
  856. uint32_t IW;
  857. uint32_t IH;
  858. uint32_t ID;
  859. uint32_t IC;
  860. uint32_t KW;
  861. uint32_t OH;
  862. uint32_t KD_KH_KW;
  863. uint32_t KH_KW;
  864. uint32_t IC_KD_KH_KW;
  865. uint32_t N_OD_OH;
  866. uint32_t OD_OH;
  867. uint32_t OD_OH_OW_IC_KD_KH_KW;
  868. uint32_t OH_OW_IC_KD_KH_KW;
  869. uint32_t OW_IC_KD_KH_KW;
  870. uint32_t misalign_offsets;
  871. };
  872. struct vk_op_timestep_embedding_push_constants {
  873. uint32_t nb1;
  874. uint32_t dim;
  875. uint32_t max_period;
  876. };
  877. struct vk_op_conv_transpose_1d_push_constants {
  878. uint32_t Cout;
  879. uint32_t Cin;
  880. uint32_t K;
  881. uint32_t L;
  882. uint32_t KL;
  883. uint32_t nb01;
  884. uint32_t nb02;
  885. uint32_t nb11;
  886. uint32_t nb1;
  887. int32_t s0;
  888. };
  889. struct vk_op_pool2d_push_constants {
  890. uint32_t IW; uint32_t IH;
  891. uint32_t OW; uint32_t OH;
  892. uint32_t OC;
  893. uint32_t pelements;
  894. uint32_t op;
  895. int32_t k0; int32_t k1;
  896. int32_t s0; int32_t s1;
  897. int32_t p0; int32_t p1;
  898. };
  899. struct vk_op_rwkv_wkv6_push_constants {
  900. uint32_t B;
  901. uint32_t T;
  902. uint32_t C;
  903. uint32_t H;
  904. };
  905. struct vk_op_rwkv_wkv7_push_constants {
  906. uint32_t B;
  907. uint32_t T;
  908. uint32_t C;
  909. uint32_t H;
  910. };
  911. struct vk_op_conv2d_push_constants {
  912. uint32_t Cout;
  913. uint32_t Cin;
  914. uint32_t N;
  915. uint32_t KW;
  916. uint32_t KH;
  917. uint32_t W;
  918. uint32_t H;
  919. uint32_t OW;
  920. uint32_t OH;
  921. uint32_t s0;
  922. uint32_t s1;
  923. uint32_t p0;
  924. uint32_t p1;
  925. uint32_t d0;
  926. uint32_t d1;
  927. uint32_t nb01;
  928. uint32_t nb02;
  929. uint32_t nb03;
  930. uint32_t nb11;
  931. uint32_t nb12;
  932. uint32_t nb13;
  933. uint32_t nb1;
  934. uint32_t nb2;
  935. uint32_t nb3;
  936. // init_fastdiv_values constants for dividing by KW, KW*KH, OW, OW*OH
  937. uint32_t KWmp; uint32_t KWL;
  938. uint32_t KWKHmp; uint32_t KWKHL;
  939. uint32_t OWmp; uint32_t OWL;
  940. uint32_t OWOHmp; uint32_t OWOHL;
  941. };
  942. template <> void init_pushconst_fastdiv(vk_op_conv2d_push_constants &p) {
  943. // Compute magic values to divide by KW, KW*KH, OW, OW*OH
  944. init_fastdiv_values(p.KW, p.KWmp, p.KWL);
  945. init_fastdiv_values(p.KW*p.KH, p.KWKHmp, p.KWKHL);
  946. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  947. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  948. }
  949. struct vk_op_conv_transpose_2d_push_constants {
  950. uint32_t Cout;
  951. uint32_t Cin;
  952. uint32_t N;
  953. uint32_t KW;
  954. uint32_t KH;
  955. uint32_t W;
  956. uint32_t H;
  957. uint32_t OW;
  958. uint32_t OH;
  959. uint32_t s0;
  960. uint32_t s1;
  961. uint32_t p0;
  962. uint32_t p1;
  963. uint32_t d0;
  964. uint32_t d1;
  965. uint32_t nb01;
  966. uint32_t nb02;
  967. uint32_t nb03;
  968. uint32_t nb11;
  969. uint32_t nb12;
  970. uint32_t nb13;
  971. uint32_t nb1;
  972. uint32_t nb2;
  973. uint32_t nb3;
  974. // init_fastdiv_values constants for dividing by KW, KW*KH, OW, OW*OH, s0, s1
  975. uint32_t KWmp; uint32_t KWL;
  976. uint32_t KWKHmp; uint32_t KWKHL;
  977. uint32_t OWmp; uint32_t OWL;
  978. uint32_t OWOHmp; uint32_t OWOHL;
  979. uint32_t s0mp; uint32_t s0L;
  980. uint32_t s1mp; uint32_t s1L;
  981. };
  982. template <> void init_pushconst_fastdiv(vk_op_conv_transpose_2d_push_constants &p) {
  983. // Compute magic values to divide by KW, KW*KH, OW, OW*OH, s0, s1
  984. init_fastdiv_values(p.KW, p.KWmp, p.KWL);
  985. init_fastdiv_values(p.KW*p.KH, p.KWKHmp, p.KWKHL);
  986. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  987. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  988. init_fastdiv_values(p.s0, p.s0mp, p.s0L);
  989. init_fastdiv_values(p.s1, p.s1mp, p.s1L);
  990. }
  991. struct vk_op_conv2d_dw_push_constants {
  992. uint32_t ne;
  993. uint32_t batches;
  994. uint32_t channels;
  995. uint32_t dst_w;
  996. uint32_t dst_h;
  997. uint32_t src_w;
  998. uint32_t src_h;
  999. uint32_t knl_w;
  1000. uint32_t knl_h;
  1001. int32_t stride_x;
  1002. int32_t stride_y;
  1003. int32_t pad_x;
  1004. int32_t pad_y;
  1005. int32_t dilation_x;
  1006. int32_t dilation_y;
  1007. };
  1008. struct vk_op_upscale_push_constants {
  1009. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  1010. uint32_t ne00; uint32_t ne01;
  1011. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1012. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  1013. float sf0; float sf1; float sf2; float sf3;
  1014. };
  1015. struct vk_op_sum_rows_push_constants
  1016. {
  1017. uint32_t n_cols;
  1018. uint32_t ne01, ne02;
  1019. uint32_t nb01, nb02, nb03;
  1020. uint32_t nb11, nb12, nb13;
  1021. float weight;
  1022. uint32_t misalign_offsets;
  1023. uint32_t ne0_12mp, ne0_12L;
  1024. uint32_t ne0_1mp, ne0_1L;
  1025. };
  1026. 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) {
  1027. uint32_t type_size = (uint32_t)ggml_type_size(src->type);
  1028. vk_op_sum_rows_push_constants p = {};
  1029. p.n_cols = (uint32_t)n_cols;
  1030. p.ne01 = (uint32_t)src->ne[1];
  1031. p.ne02 = (uint32_t)src->ne[2];
  1032. p.nb01 = (uint32_t)src->nb[1] / type_size;
  1033. p.nb02 = (uint32_t)src->nb[2] / type_size;
  1034. p.nb03 = (uint32_t)src->nb[3] / type_size;
  1035. p.nb11 = (uint32_t)dst->nb[1] / type_size;
  1036. p.nb12 = (uint32_t)dst->nb[2] / type_size;
  1037. p.nb13 = (uint32_t)dst->nb[3] / type_size;
  1038. p.weight = 1.0f;
  1039. return p;
  1040. }
  1041. template <> void init_pushconst_fastdiv(vk_op_sum_rows_push_constants &p) {
  1042. init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L);
  1043. init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L);
  1044. }
  1045. // Allow pre-recording command buffers
  1046. struct vk_staging_memcpy {
  1047. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  1048. void * dst;
  1049. const void * src;
  1050. size_t n;
  1051. };
  1052. struct vk_staging_memset {
  1053. vk_staging_memset(void * _dst, uint32_t _val, size_t _n) : dst(_dst), val(_val), n(_n) {}
  1054. void * dst;
  1055. uint32_t val;
  1056. size_t n;
  1057. };
  1058. struct vk_context_struct {
  1059. vk_submission * s;
  1060. std::vector<vk_sequence> seqs;
  1061. int exit_tensor_idx;
  1062. std::vector<vk_staging_memcpy> in_memcpys;
  1063. std::vector<vk_staging_memcpy> out_memcpys;
  1064. std::vector<vk_staging_memset> memsets;
  1065. vk_command_pool * p {};
  1066. };
  1067. typedef std::shared_ptr<vk_context_struct> vk_context;
  1068. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  1069. struct ggml_vk_garbage_collector {
  1070. std::vector<vk_semaphore> tl_semaphores;
  1071. std::vector<vk_semaphore> semaphores;
  1072. std::vector<vk::Event> events;
  1073. std::vector<vk_buffer> temp_buffers;
  1074. std::vector<vk_context> contexts;
  1075. };
  1076. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  1077. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  1078. static std::string format_size(size_t size) {
  1079. const size_t kib = 1024;
  1080. const size_t mib = kib * 1024;
  1081. const size_t gib = mib * 1024;
  1082. std::ostringstream oss;
  1083. oss << std::fixed << std::setprecision(2);
  1084. if (size >= gib) {
  1085. oss << static_cast<double>(size) / gib << " GiB";
  1086. } else if (size >= mib) {
  1087. oss << static_cast<double>(size) / mib << " MiB";
  1088. } else if (size >= kib) {
  1089. oss << static_cast<double>(size) / kib << " KiB";
  1090. } else {
  1091. oss << size << " B";
  1092. }
  1093. return oss.str();
  1094. }
  1095. class vk_memory_logger {
  1096. public:
  1097. vk_memory_logger(): total_device(0), total_host(0) {}
  1098. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  1099. void log_deallocation(vk_buffer_ref buf_ref);
  1100. private:
  1101. std::map<vk::Buffer, size_t> allocations; // Track allocations
  1102. size_t total_device;
  1103. size_t total_host;
  1104. };
  1105. #else
  1106. #define VK_LOG_MEMORY(msg) ((void) 0)
  1107. #endif // GGML_VULKAN_MEMORY_DEBUG
  1108. class vk_perf_logger {
  1109. public:
  1110. void print_timings() {
  1111. if (timings.empty()) {
  1112. return;
  1113. }
  1114. uint64_t total_all_op_times = 0;
  1115. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  1116. for (const auto & t : timings) {
  1117. uint64_t total_op_times = 0;
  1118. for (const auto & time : t.second) {
  1119. total_op_times += time;
  1120. }
  1121. std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0)
  1122. << " us";
  1123. // If we have as many flops entries as timing entries for the op, then compute and log the flops/S.
  1124. auto it = flops.find(t.first);
  1125. if (it != flops.end() && (it->second).size() == t.second.size()) {
  1126. uint64_t total_op_flops = 0;
  1127. for (const auto & elem : it->second) {
  1128. total_op_flops += elem;
  1129. }
  1130. std::cerr << " ("
  1131. << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) /
  1132. (double(total_op_times) / (1000.0 * 1000.0 * 1000.0))
  1133. << " GFLOPS/s)";
  1134. }
  1135. total_all_op_times += total_op_times;
  1136. std::cerr << std::endl;
  1137. }
  1138. if (timings.size() > 0) {
  1139. std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl;
  1140. }
  1141. timings.clear();
  1142. flops.clear();
  1143. }
  1144. void log_timing(const ggml_tensor * node, uint64_t time) {
  1145. if (node->op == GGML_OP_UNARY) {
  1146. timings[ggml_unary_op_name(ggml_get_unary_op(node))].push_back(time);
  1147. return;
  1148. }
  1149. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  1150. const uint64_t m = node->src[0]->ne[1];
  1151. const uint64_t n = node->ne[1];
  1152. const uint64_t k = node->src[1]->ne[0];
  1153. const uint64_t batch = node->src[1]->ne[2] * node->src[1]->ne[3];
  1154. std::string name = ggml_op_name(node->op);
  1155. if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) ||
  1156. (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) {
  1157. name += "_VEC";
  1158. }
  1159. name += " ";
  1160. name += ggml_type_name(node->src[0]->type);
  1161. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  1162. if (batch > 1) {
  1163. name += " batch=" + std::to_string(batch);
  1164. }
  1165. timings[name].push_back(time);
  1166. flops[name].push_back(m * n * (k + (k - 1)) * batch);
  1167. return;
  1168. }
  1169. if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) {
  1170. std::string name = ggml_op_name(node->op);
  1171. ggml_tensor * knl = node->src[0];
  1172. uint64_t OW = node->ne[0];
  1173. uint64_t OH = node->ne[1];
  1174. uint64_t N = node->ne[3];
  1175. uint64_t Cout = node->ne[2];
  1176. uint64_t KW = knl->ne[0];
  1177. uint64_t KH = knl->ne[1];
  1178. uint64_t Cin = node->src[1]->ne[2];
  1179. // KxCRS @ CRSxNPQ = KxNPQ -> M=K, K=CRS, N=NPQ
  1180. uint64_t size_M = Cout;
  1181. uint64_t size_K = Cin * KW * KH;
  1182. uint64_t size_N = N * OW * OH;
  1183. uint64_t n_flops = size_M * size_N * (size_K + (size_K - 1));
  1184. name += " M=Cout=" + std::to_string(size_M) + ", K=Cin*KW*KH=" + std::to_string(size_K) +
  1185. ", N=N*OW*OH=" + std::to_string(size_N);
  1186. flops[name].push_back(n_flops);
  1187. timings[name].push_back(time);
  1188. return;
  1189. }
  1190. if (node->op == GGML_OP_RMS_NORM) {
  1191. std::string name = ggml_op_name(node->op);
  1192. 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]) + ")";
  1193. timings[name].push_back(time);
  1194. return;
  1195. }
  1196. timings[ggml_op_name(node->op)].push_back(time);
  1197. }
  1198. private:
  1199. std::map<std::string, std::vector<uint64_t>> timings;
  1200. std::map<std::string, std::vector<uint64_t>> flops;
  1201. };
  1202. struct ggml_backend_vk_context {
  1203. std::string name;
  1204. vk_device device;
  1205. size_t semaphore_idx, event_idx;
  1206. ggml_vk_garbage_collector gc;
  1207. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset;
  1208. vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials;
  1209. vk::Fence fence, almost_ready_fence;
  1210. bool almost_ready_fence_pending {};
  1211. // Set before op_add and unset after op_rms_norm to indicate that the add should
  1212. // write partial sums to accumulate the square of the vector components
  1213. bool do_add_rms_partials;
  1214. // Cache most recent tensor that was converted into prealloc_y, and what pipeline it used to convert.
  1215. vk_pipeline_struct * prealloc_y_last_pipeline_used {};
  1216. const ggml_tensor * prealloc_y_last_tensor_used {};
  1217. // Track which nodes have been used since the last sync, and whether they were written to
  1218. std::vector<const ggml_tensor *> unsynced_nodes_written;
  1219. std::vector<const ggml_tensor *> unsynced_nodes_read;
  1220. // Track which prealloc buffers have pending reads that need to be synchronized.
  1221. // These are checked before writing to the buffer (and call ggml_vk_sync_buffers if set),
  1222. // and set to true after the buffer contents are consumed.
  1223. bool prealloc_x_need_sync, prealloc_y_need_sync, prealloc_split_k_need_sync;
  1224. vk_buffer buffer_pool[MAX_VK_BUFFERS];
  1225. vk_context_ref compute_ctx;
  1226. vk_context_ref transfer_ctx;
  1227. std::vector<vk_context_ref> tensor_ctxs;
  1228. std::vector<vk::DescriptorPool> descriptor_pools;
  1229. std::vector<vk::DescriptorSet> descriptor_sets;
  1230. uint32_t descriptor_set_idx {};
  1231. uint32_t pipeline_descriptor_set_requirements {};
  1232. vk_command_pool compute_cmd_pool;
  1233. vk_command_pool transfer_cmd_pool;
  1234. // number of additional consecutive nodes that are being fused with the
  1235. // node currently being processed
  1236. int num_additional_fused_ops {};
  1237. };
  1238. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  1239. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  1240. if (tensor->view_src) {
  1241. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  1242. }
  1243. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  1244. }
  1245. struct ggml_backend_vk_buffer_context {
  1246. vk_device_ref device;
  1247. vk_buffer dev_buffer;
  1248. std::string name;
  1249. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  1250. device(device),
  1251. dev_buffer(dev_buffer),
  1252. name(name) {
  1253. }
  1254. ~ggml_backend_vk_buffer_context() {
  1255. ggml_vk_destroy_buffer(dev_buffer);
  1256. }
  1257. };
  1258. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1259. static std::mutex log_mutex;
  1260. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  1261. std::lock_guard<std::mutex> guard(log_mutex);
  1262. vk_buffer buf = buf_ref.lock();
  1263. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1264. const std::string type = device ? "device" : "host";
  1265. allocations[buf->buffer] = size;
  1266. total_device += device ? size : 0;
  1267. total_host += device ? 0 : size;
  1268. 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));
  1269. }
  1270. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  1271. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  1272. return;
  1273. }
  1274. std::lock_guard<std::mutex> guard(log_mutex);
  1275. vk_buffer buf = buf_ref.lock();
  1276. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1277. std::string type = device ? "device" : "host";
  1278. auto it = allocations.find(buf->buffer);
  1279. total_device -= device ? it->second : 0;
  1280. total_host -= device ? 0 : it->second;
  1281. if (it != allocations.end()) {
  1282. 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));
  1283. allocations.erase(it);
  1284. } else {
  1285. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  1286. }
  1287. }
  1288. #endif // GGML_VULKAN_MEMORY_DEBUG
  1289. struct vk_instance_t {
  1290. vk::Instance instance;
  1291. bool debug_utils_support = false; // VK_EXT_debug_utils enabled
  1292. PFN_vkSetDebugUtilsObjectNameEXT pfn_vkSetDebugUtilsObjectNameEXT = {};
  1293. PFN_vkQueueBeginDebugUtilsLabelEXT pfn_vkQueueBeginDebugUtilsLabelEXT = {};
  1294. PFN_vkQueueEndDebugUtilsLabelEXT pfn_vkQueueEndDebugUtilsLabelEXT = {};
  1295. PFN_vkCmdBeginDebugUtilsLabelEXT pfn_vkCmdBeginDebugUtilsLabelEXT = {};
  1296. PFN_vkCmdEndDebugUtilsLabelEXT pfn_vkCmdEndDebugUtilsLabelEXT = {};
  1297. PFN_vkCmdInsertDebugUtilsLabelEXT pfn_vkCmdInsertDebugUtilsLabelEXT = {};
  1298. std::vector<size_t> device_indices;
  1299. std::vector<bool> device_supports_membudget;
  1300. vk_device devices[GGML_VK_MAX_DEVICES];
  1301. };
  1302. static bool vk_instance_initialized = false;
  1303. static vk_instance_t vk_instance;
  1304. static bool vk_perf_logger_enabled = false;
  1305. #ifdef GGML_VULKAN_CHECK_RESULTS
  1306. static size_t vk_skip_checks;
  1307. static size_t vk_output_tensor;
  1308. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  1309. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1310. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1311. #endif
  1312. 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);
  1313. static void ggml_backend_vk_free(ggml_backend_t backend);
  1314. // Wait for ctx->fence to be signaled.
  1315. static void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) {
  1316. // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep
  1317. // during this wait.
  1318. if (ctx->almost_ready_fence_pending) {
  1319. VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence");
  1320. ctx->device->device.resetFences({ ctx->almost_ready_fence });
  1321. ctx->almost_ready_fence_pending = false;
  1322. }
  1323. // Spin (w/pause) waiting for the graph to finish executing.
  1324. vk::Result result;
  1325. while ((result = ctx->device->device.getFenceStatus(ctx->fence)) != vk::Result::eSuccess) {
  1326. if (result != vk::Result::eNotReady) {
  1327. fprintf(stderr, "ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__);
  1328. exit(1);
  1329. }
  1330. for (uint32_t i = 0; i < 100; ++i) {
  1331. YIELD();
  1332. YIELD();
  1333. YIELD();
  1334. YIELD();
  1335. YIELD();
  1336. YIELD();
  1337. YIELD();
  1338. YIELD();
  1339. YIELD();
  1340. YIELD();
  1341. }
  1342. }
  1343. ctx->device->device.resetFences({ ctx->fence });
  1344. }
  1345. // variables to track number of compiles in progress
  1346. static uint32_t compile_count = 0;
  1347. static std::mutex compile_count_mutex;
  1348. static std::condition_variable compile_count_cond;
  1349. 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,
  1350. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  1351. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  1352. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  1353. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  1354. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  1355. GGML_ASSERT(parameter_count > 0);
  1356. GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT);
  1357. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  1358. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  1359. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  1360. vk::PushConstantRange pcr(
  1361. vk::ShaderStageFlagBits::eCompute,
  1362. 0,
  1363. pipeline->push_constant_size
  1364. );
  1365. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr);
  1366. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  1367. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  1368. for (size_t i = 0; i < specialization_constants.size(); i++) {
  1369. specialization_entries[i].constantID = i;
  1370. specialization_entries[i].offset = i * sizeof(uint32_t);
  1371. specialization_entries[i].size = sizeof(uint32_t);
  1372. }
  1373. vk::SpecializationInfo specialization_info(
  1374. specialization_entries.size(),
  1375. specialization_entries.data(),
  1376. specialization_constants.size() * sizeof(uint32_t),
  1377. specialization_constants.data()
  1378. );
  1379. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  1380. if (device->subgroup_require_full_support && require_full_subgroups) {
  1381. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  1382. }
  1383. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  1384. pipeline_shader_stage_create_flags,
  1385. vk::ShaderStageFlagBits::eCompute,
  1386. pipeline->shader_module,
  1387. entrypoint.c_str(),
  1388. &specialization_info);
  1389. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  1390. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  1391. if (device->subgroup_size_control && required_subgroup_size > 0) {
  1392. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  1393. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  1394. }
  1395. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  1396. device->pipeline_executable_properties_support ?
  1397. vk::PipelineCreateFlagBits::eCaptureStatisticsKHR :
  1398. vk::PipelineCreateFlags{},
  1399. pipeline_shader_create_info,
  1400. pipeline->layout);
  1401. vk::PipelineRobustnessCreateInfoEXT rci;
  1402. if (device->pipeline_robustness && disable_robustness) {
  1403. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1404. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1405. compute_pipeline_create_info.setPNext(&rci);
  1406. }
  1407. try {
  1408. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  1409. } catch (const vk::SystemError& e) {
  1410. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  1411. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1412. throw e;
  1413. }
  1414. pipeline->compiled = true;
  1415. if (vk_instance.debug_utils_support) {
  1416. vk::DebugUtilsObjectNameInfoEXT duoni;
  1417. duoni.objectType = vk::ObjectType::ePipeline;
  1418. duoni.pObjectName = pipeline->name.c_str();
  1419. duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast<VkPipeline>(pipeline->pipeline));
  1420. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast<VkDebugUtilsObjectNameInfoEXT &>(duoni));
  1421. }
  1422. if (device->pipeline_executable_properties_support) {
  1423. vk::PipelineExecutableInfoKHR executableInfo;
  1424. executableInfo.pipeline = pipeline->pipeline;
  1425. auto statistics = device->device.getPipelineExecutableStatisticsKHR(executableInfo);
  1426. for (auto & s : statistics) {
  1427. // "Register Count" is reported by NVIDIA drivers.
  1428. if (strcmp(s.name, "Register Count") == 0) {
  1429. VK_LOG_DEBUG(pipeline->name << " " << s.name << ": " << s.value.u64 << " registers");
  1430. pipeline->register_count = (uint32_t)s.value.u64;
  1431. }
  1432. }
  1433. }
  1434. {
  1435. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1436. device->all_pipelines.push_back(pipeline);
  1437. }
  1438. {
  1439. std::lock_guard<std::mutex> guard(compile_count_mutex);
  1440. assert(compile_count > 0);
  1441. compile_count--;
  1442. }
  1443. compile_count_cond.notify_all();
  1444. }
  1445. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  1446. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  1447. device.destroyPipelineLayout(pipeline->layout);
  1448. device.destroyShaderModule(pipeline->shader_module);
  1449. device.destroyPipeline(pipeline->pipeline);
  1450. }
  1451. static void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) {
  1452. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  1453. ctx->pipeline_descriptor_set_requirements += n;
  1454. if (!pipeline->compiled) {
  1455. pipeline->needed = true;
  1456. ctx->device->need_compiles = true;
  1457. }
  1458. }
  1459. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
  1460. if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) {
  1461. // Enough descriptors are available
  1462. return;
  1463. }
  1464. vk_device& device = ctx->device;
  1465. uint32_t to_alloc = ctx->pipeline_descriptor_set_requirements - ctx->descriptor_sets.size();
  1466. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1467. uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1468. while (to_alloc > 0) {
  1469. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  1470. to_alloc -= alloc_count;
  1471. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1472. if (pool_idx >= ctx->descriptor_pools.size()) {
  1473. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  1474. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  1475. ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  1476. }
  1477. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  1478. for (uint32_t i = 0; i < alloc_count; i++) {
  1479. layouts[i] = device->dsl;
  1480. }
  1481. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
  1482. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  1483. ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
  1484. pool_idx++;
  1485. }
  1486. }
  1487. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) {
  1488. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  1489. if (p.cmd_buffers.size() > p.cmd_buffer_idx) {
  1490. // Reuse command buffer
  1491. return p.cmd_buffers[p.cmd_buffer_idx++];
  1492. }
  1493. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  1494. p.pool,
  1495. vk::CommandBufferLevel::ePrimary,
  1496. 1);
  1497. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  1498. auto buf = cmd_buffers.front();
  1499. p.cmd_buffers.push_back(buf);
  1500. p.cmd_buffer_idx++;
  1501. return buf;
  1502. }
  1503. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  1504. if (ctx->seqs.empty()) {
  1505. if (fence) {
  1506. std::lock_guard<std::mutex> guard(queue_mutex);
  1507. ctx->p->q->queue.submit({}, fence);
  1508. }
  1509. return;
  1510. }
  1511. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  1512. std::vector<std::vector<uint64_t>> tl_wait_vals;
  1513. std::vector<std::vector<uint64_t>> tl_signal_vals;
  1514. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  1515. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  1516. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  1517. std::vector<vk::SubmitInfo> submit_infos;
  1518. int idx = -1;
  1519. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  1520. size_t reserve = 0;
  1521. for (const auto& sequence : ctx->seqs) {
  1522. reserve += sequence.size();
  1523. }
  1524. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  1525. tl_wait_semaphores.reserve(reserve);
  1526. tl_wait_vals.reserve(reserve);
  1527. tl_signal_semaphores.reserve(reserve);
  1528. tl_signal_vals.reserve(reserve);
  1529. tl_submit_infos.reserve(reserve);
  1530. submit_infos.reserve(reserve);
  1531. stage_flags.reserve(reserve);
  1532. for (const auto& sequence : ctx->seqs) {
  1533. for (const auto& submission : sequence) {
  1534. stage_flags.push_back({});
  1535. idx++;
  1536. tl_wait_vals.push_back({});
  1537. tl_wait_semaphores.push_back({});
  1538. tl_signal_vals.push_back({});
  1539. tl_signal_semaphores.push_back({});
  1540. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  1541. stage_flags[idx].push_back(ctx->p->q->stage_flags);
  1542. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  1543. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  1544. }
  1545. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  1546. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  1547. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  1548. }
  1549. tl_submit_infos.push_back({
  1550. (uint32_t) submission.wait_semaphores.size(),
  1551. tl_wait_vals[idx].data(),
  1552. (uint32_t) submission.signal_semaphores.size(),
  1553. tl_signal_vals[idx].data(),
  1554. });
  1555. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  1556. tl_submit_infos[idx].pNext = nullptr;
  1557. vk::SubmitInfo si{
  1558. (uint32_t) submission.wait_semaphores.size(),
  1559. tl_wait_semaphores[idx].data(),
  1560. stage_flags[idx].data(),
  1561. 1,
  1562. &submission.buffer,
  1563. (uint32_t) submission.signal_semaphores.size(),
  1564. tl_signal_semaphores[idx].data(),
  1565. };
  1566. si.setPNext(&tl_submit_infos[idx]);
  1567. submit_infos.push_back(si);
  1568. }
  1569. }
  1570. std::lock_guard<std::mutex> guard(queue_mutex);
  1571. ctx->p->q->queue.submit(submit_infos, fence);
  1572. ctx->seqs.clear();
  1573. }
  1574. 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) {
  1575. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  1576. const uint32_t qfsize = queue_family_props.size();
  1577. // Try with avoid preferences first
  1578. for (uint32_t i = 0; i < qfsize; i++) {
  1579. 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)) {
  1580. return i;
  1581. }
  1582. }
  1583. // Fall back to only required
  1584. for (size_t i = 0; i < qfsize; i++) {
  1585. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  1586. return i;
  1587. }
  1588. }
  1589. // Fall back to reusing compute queue
  1590. for (size_t i = 0; i < qfsize; i++) {
  1591. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  1592. return i;
  1593. }
  1594. }
  1595. // Fall back to ignoring min_num_queries
  1596. for (size_t i = 0; i < qfsize; i++) {
  1597. if (queue_family_props[i].queueFlags & required) {
  1598. return i;
  1599. }
  1600. }
  1601. // 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.
  1602. // 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.
  1603. if (compute_index >= 0) {
  1604. return compute_index;
  1605. }
  1606. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  1607. for(auto &q_family : queue_family_props) {
  1608. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  1609. }
  1610. abort();
  1611. }
  1612. 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) {
  1613. VK_LOG_DEBUG("ggml_vk_create_queue()");
  1614. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1615. q.queue_family_index = queue_family_index;
  1616. q.transfer_only = transfer_only;
  1617. q.cmd_pool.init(device, &q);
  1618. q.queue = device->device.getQueue(queue_family_index, queue_index);
  1619. q.stage_flags = stage_flags;
  1620. }
  1621. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) {
  1622. vk_context result = std::make_shared<vk_context_struct>();
  1623. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  1624. ctx->gc.contexts.emplace_back(result);
  1625. result->p = &p;
  1626. return result;
  1627. }
  1628. static vk_context ggml_vk_create_temporary_context(vk_command_pool& p) {
  1629. vk_context result = std::make_shared<vk_context_struct>();
  1630. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  1631. result->p = &p;
  1632. return result;
  1633. }
  1634. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  1635. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1636. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  1637. vk::SemaphoreCreateInfo ci{};
  1638. ci.setPNext(&tci);
  1639. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1640. ctx->gc.semaphores.push_back({ semaphore, 0 });
  1641. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  1642. }
  1643. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  1644. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1645. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  1646. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  1647. vk::SemaphoreCreateInfo ci{};
  1648. ci.setPNext(&tci);
  1649. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1650. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  1651. }
  1652. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  1653. }
  1654. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  1655. if (ctx->event_idx >= ctx->gc.events.size()) {
  1656. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  1657. }
  1658. return ctx->gc.events[ctx->event_idx++];
  1659. }
  1660. static void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) {
  1661. VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()");
  1662. // Requires command buffers to be done
  1663. device->device.resetCommandPool(p.pool);
  1664. p.cmd_buffer_idx = 0;
  1665. }
  1666. static void ggml_vk_queue_command_pools_cleanup(vk_device& device) {
  1667. VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()");
  1668. // Arbitrary frequency to cleanup/reuse command buffers
  1669. static constexpr uint32_t cleanup_frequency = 10;
  1670. if (device->compute_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1671. ggml_vk_command_pool_cleanup(device, device->compute_queue.cmd_pool);
  1672. }
  1673. if (device->transfer_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1674. ggml_vk_command_pool_cleanup(device, device->transfer_queue.cmd_pool);
  1675. }
  1676. }
  1677. static uint32_t find_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  1678. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  1679. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  1680. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  1681. (flags & memory_type.propertyFlags) == flags &&
  1682. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  1683. return static_cast<int32_t>(i);
  1684. }
  1685. }
  1686. return UINT32_MAX;
  1687. }
  1688. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, const std::initializer_list<vk::MemoryPropertyFlags> & req_flags_list) {
  1689. 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]) << ")");
  1690. if (size > device->max_memory_allocation_size) {
  1691. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device memory allocation limit");
  1692. }
  1693. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  1694. if (size == 0) {
  1695. buf->size = 0;
  1696. return buf;
  1697. }
  1698. vk::BufferUsageFlags usage_flags = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst;
  1699. vk::MemoryAllocateFlags mem_flags {};
  1700. if (device->buffer_device_address) {
  1701. usage_flags |= vk::BufferUsageFlagBits::eShaderDeviceAddress;
  1702. mem_flags |= vk::MemoryAllocateFlagBits::eDeviceAddress;
  1703. }
  1704. vk::BufferCreateInfo buffer_create_info{
  1705. vk::BufferCreateFlags(),
  1706. size,
  1707. usage_flags,
  1708. vk::SharingMode::eExclusive,
  1709. 0,
  1710. nullptr,
  1711. };
  1712. buf->buffer = device->device.createBuffer(buffer_create_info);
  1713. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  1714. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  1715. const vk::MemoryAllocateFlagsInfo mem_flags_info { mem_flags };
  1716. for (auto it = req_flags_list.begin(); it != req_flags_list.end(); it++) {
  1717. const auto & req_flags = *it;
  1718. uint32_t memory_type_index = find_properties(&mem_props, &mem_req, req_flags);
  1719. if (memory_type_index == UINT32_MAX) {
  1720. continue;
  1721. }
  1722. buf->memory_property_flags = req_flags;
  1723. try {
  1724. buf->device_memory = device->device.allocateMemory({ mem_req.size, memory_type_index, &mem_flags_info });
  1725. break;
  1726. } catch (const vk::SystemError& e) {
  1727. // loop and retry
  1728. // during last attempt throw the exception
  1729. if (it + 1 == req_flags_list.end()) {
  1730. device->device.destroyBuffer(buf->buffer);
  1731. throw e;
  1732. }
  1733. }
  1734. }
  1735. if (!buf->device_memory) {
  1736. device->device.destroyBuffer(buf->buffer);
  1737. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  1738. }
  1739. buf->ptr = nullptr;
  1740. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1741. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  1742. }
  1743. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  1744. buf->device = device;
  1745. buf->size = size;
  1746. if (device->buffer_device_address) {
  1747. const vk::BufferDeviceAddressInfo addressInfo(buf->buffer);
  1748. buf->bda_addr = device->device.getBufferAddress(addressInfo);
  1749. }
  1750. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1751. device->memory_logger->log_allocation(buf, size);
  1752. #endif
  1753. return buf;
  1754. }
  1755. 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)) {
  1756. try {
  1757. return ggml_vk_create_buffer(device, size, {req_flags, fallback_flags});
  1758. } catch (const vk::SystemError& e) {
  1759. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  1760. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1761. throw e;
  1762. }
  1763. }
  1764. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  1765. vk_buffer buf;
  1766. try {
  1767. if (device->prefer_host_memory) {
  1768. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1769. vk::MemoryPropertyFlagBits::eDeviceLocal});
  1770. } else if (device->uma) {
  1771. // Fall back to host memory type
  1772. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  1773. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1774. } else if (device->disable_host_visible_vidmem) {
  1775. if (device->allow_sysmem_fallback) {
  1776. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  1777. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1778. } else {
  1779. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  1780. }
  1781. } else {
  1782. // use rebar if available, otherwise fallback to device only visible memory
  1783. if (device->allow_sysmem_fallback) {
  1784. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1785. vk::MemoryPropertyFlagBits::eDeviceLocal,
  1786. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  1787. } else {
  1788. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  1789. vk::MemoryPropertyFlagBits::eDeviceLocal});
  1790. }
  1791. }
  1792. } catch (const vk::SystemError& e) {
  1793. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  1794. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1795. throw e;
  1796. }
  1797. return buf;
  1798. }
  1799. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  1800. if (buf == nullptr) {
  1801. return;
  1802. }
  1803. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1804. if (buf->device != nullptr) {
  1805. buf->device->memory_logger->log_deallocation(buf);
  1806. }
  1807. #endif
  1808. buf.reset();
  1809. }
  1810. static vk_subbuffer ggml_vk_subbuffer(vk_buffer& buf) {
  1811. return { buf, 0, VK_WHOLE_SIZE };
  1812. }
  1813. static void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) {
  1814. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  1815. const bool transfer_queue = subctx->p->q->transfer_only;
  1816. if (ctx) {
  1817. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  1818. }
  1819. subctx->s->buffer.pipelineBarrier(
  1820. subctx->p->q->stage_flags,
  1821. subctx->p->q->stage_flags,
  1822. {},
  1823. { {
  1824. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  1825. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  1826. } },
  1827. {},
  1828. {}
  1829. );
  1830. }
  1831. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  1832. VK_LOG_DEBUG("ggml_vk_wait_events()");
  1833. if (events.empty()) {
  1834. return;
  1835. }
  1836. ctx->s->buffer.waitEvents(
  1837. events,
  1838. ctx->p->q->stage_flags,
  1839. ctx->p->q->stage_flags,
  1840. {},
  1841. {},
  1842. {}
  1843. );
  1844. }
  1845. // number of rows/cols for flash attention shader
  1846. static constexpr uint32_t flash_attention_num_small_rows = 32;
  1847. static constexpr uint32_t scalar_flash_attention_num_small_rows = 1;
  1848. static uint32_t get_fa_scalar_num_large_rows(uint32_t hsv) {
  1849. if (hsv >= 192) {
  1850. return 2;
  1851. } else {
  1852. return 8;
  1853. }
  1854. }
  1855. // The FA coopmat1 shader assumes 16x16x16 matrix multiply support.
  1856. // 128 threads split into four subgroups, each subgroup does 1/4
  1857. // of the Bc dimension.
  1858. static constexpr uint32_t coopmat1_flash_attention_num_large_rows = 16;
  1859. static constexpr uint32_t scalar_flash_attention_Bc = 64;
  1860. static constexpr uint32_t scalar_flash_attention_workgroup_size = 128;
  1861. static uint32_t get_fa_num_small_rows(FaCodePath path) {
  1862. if (path == FA_COOPMAT2) {
  1863. return flash_attention_num_small_rows;
  1864. } else {
  1865. return scalar_flash_attention_num_small_rows;
  1866. }
  1867. }
  1868. 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) {
  1869. GGML_UNUSED(clamp);
  1870. GGML_UNUSED(hsv);
  1871. if (path == FA_SCALAR) {
  1872. if (small_rows) {
  1873. return {scalar_flash_attention_num_small_rows, 64};
  1874. } else {
  1875. if ((hsv | hsk) & 8) {
  1876. // HSV/HSK not being a multiple of 16 makes D_split smaller, which makes cols_per_iter
  1877. // larger, and Bc needs to be >= cols_per_thread. 64 is large enough, 32 is not.
  1878. return {get_fa_scalar_num_large_rows(hsv), 64};
  1879. } else {
  1880. return {get_fa_scalar_num_large_rows(hsv), 32};
  1881. }
  1882. }
  1883. }
  1884. if (path == FA_COOPMAT1) {
  1885. if (small_rows) {
  1886. return {scalar_flash_attention_num_small_rows, scalar_flash_attention_Bc};
  1887. } else {
  1888. return {coopmat1_flash_attention_num_large_rows, scalar_flash_attention_Bc};
  1889. }
  1890. }
  1891. // small rows, large cols
  1892. if (small_rows) {
  1893. return {get_fa_num_small_rows(FA_COOPMAT2), 32};
  1894. }
  1895. // small cols to reduce register count
  1896. if (ggml_is_quantized(type) || hsk >= 256 || hsv >= 256) {
  1897. if (hsk >= 512 || hsv >= 512) {
  1898. return {32, 32};
  1899. } else {
  1900. return {64, 32};
  1901. }
  1902. }
  1903. return {64, 64};
  1904. }
  1905. static uint32_t fa_align(FaCodePath path, uint32_t hsk, uint32_t hsv, ggml_type type, bool small_rows) {
  1906. return fa_rows_cols(path, hsk, hsv, 0, type, small_rows)[1];
  1907. }
  1908. 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) {
  1909. uint32_t lut_size = 0;
  1910. switch (src0_type) {
  1911. case GGML_TYPE_IQ1_S:
  1912. case GGML_TYPE_IQ1_M:
  1913. lut_size = 2*2048;
  1914. break;
  1915. case GGML_TYPE_IQ2_XXS:
  1916. lut_size = 8*256;
  1917. break;
  1918. case GGML_TYPE_IQ2_XS:
  1919. lut_size = 8*512;
  1920. break;
  1921. case GGML_TYPE_IQ2_S:
  1922. lut_size = 8*1024;
  1923. break;
  1924. case GGML_TYPE_IQ3_XXS:
  1925. lut_size = 4*256;
  1926. break;
  1927. case GGML_TYPE_IQ3_S:
  1928. lut_size = 4*512;
  1929. break;
  1930. case GGML_TYPE_IQ4_NL:
  1931. case GGML_TYPE_IQ4_XS:
  1932. case GGML_TYPE_MXFP4:
  1933. lut_size = 4*16;
  1934. break;
  1935. default:
  1936. break;
  1937. }
  1938. // Needs to be kept up to date on shader changes
  1939. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  1940. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  1941. const uint32_t warps = warptile[0] / warptile[10];
  1942. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  1943. const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0;
  1944. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  1945. const uint32_t ballots_sh = mul_mat_id ? (warps * 4 * sizeof(uint32_t)) : 0;
  1946. const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size + ballots_sh;
  1947. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  1948. VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), "
  1949. "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported);
  1950. return supported;
  1951. }
  1952. struct GpuPipelineConfig {
  1953. // GPU architecture identifier.
  1954. // Example: vk_device_architecture::AMD_GCN
  1955. vk_device_architecture arch;
  1956. // Mapping of pipeline names to their specific subgroup sizes.
  1957. // Example: {"soft_max_f32", 64}
  1958. std::unordered_map<std::string, uint32_t> pipelines;
  1959. // Default subgroup size for this GPU.
  1960. // Defaults to 0 if not explicitly provided.
  1961. uint32_t default_subgroup_size = 0;
  1962. };
  1963. // Pipeline configuration for RDNA1 GPUs.
  1964. static const std::unordered_map<std::string, uint32_t> rdna1_pipelines = {
  1965. {"soft_max", 64}, {"im2col", 64},
  1966. {"argmax", 64}, {"mul_mat_vec", 64},
  1967. {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32}
  1968. };
  1969. // Pipeline configuration for RDNA2 GPUs.
  1970. static const std::unordered_map<std::string, uint32_t> rdna2_pipelines = {
  1971. {"soft_max", 64}, {"im2col", 64},
  1972. };
  1973. static constexpr uint32_t RDNA_DEFAULT_SUBGROUP_SIZE = 32;
  1974. // Define configurations for different GPUs.
  1975. static std::vector<GpuPipelineConfig> gpu_pipeline_configs = {
  1976. {
  1977. vk_device_architecture::AMD_RDNA1,
  1978. {
  1979. rdna1_pipelines,
  1980. },
  1981. RDNA_DEFAULT_SUBGROUP_SIZE
  1982. },
  1983. {
  1984. vk_device_architecture::AMD_RDNA2,
  1985. {
  1986. rdna2_pipelines,
  1987. },
  1988. RDNA_DEFAULT_SUBGROUP_SIZE
  1989. },
  1990. };
  1991. static uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) {
  1992. for (const auto &config : gpu_pipeline_configs) {
  1993. if (config.arch == arch) {
  1994. auto pipIt = config.pipelines.find(pipeline_name);
  1995. if (pipIt != config.pipelines.end()) {
  1996. return pipIt->second;
  1997. }
  1998. std::vector<std::pair<std::string, uint32_t>> sorted_pipelines(config.pipelines.begin(), config.pipelines.end());
  1999. std::sort(sorted_pipelines.begin(), sorted_pipelines.end(),
  2000. [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
  2001. for (const auto &entry : sorted_pipelines) {
  2002. if (pipeline_name.find(entry.first) != std::string::npos) {
  2003. return entry.second;
  2004. }
  2005. }
  2006. return config.default_subgroup_size;
  2007. }
  2008. }
  2009. return 0; // If no matching configuration is found
  2010. }
  2011. static void ggml_vk_load_shaders(vk_device& device) {
  2012. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  2013. // some shaders have a minimum subgroup size
  2014. const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u);
  2015. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  2016. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  2017. 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;
  2018. const uint32_t mul_mat_subgroup_size_8 = std::max(mul_mat_subgroup_size, 8u);
  2019. const uint32_t mul_mat_subgroup_size_16 = std::max(mul_mat_subgroup_size, 16u);
  2020. const uint32_t mul_mat_subgroup_size_32 = std::max(mul_mat_subgroup_size, 32u);
  2021. const bool subgroup_min_size_16 = (!device->subgroup_size_control && device->subgroup_size >= 16) ||
  2022. (device->subgroup_size_control && device->subgroup_max_size >= 16);
  2023. // mulmat
  2024. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  2025. l_warptile_id, m_warptile_id, s_warptile_id,
  2026. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  2027. l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int,
  2028. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  2029. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid;
  2030. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  2031. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  2032. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  2033. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  2034. uint32_t l_align, m_align, s_align;
  2035. if (device->coopmat2) {
  2036. // spec constants and tile sizes for non-quant matmul/matmul_id
  2037. l_warptile = { 256, 128, 256, 64, 1 };
  2038. m_warptile = { 256, 128, 128, 64, 0 };
  2039. s_warptile = { 128, 64, 64, 64, 0 };
  2040. l_wg_denoms = {128, 256, 1 };
  2041. m_wg_denoms = {128, 128, 1 };
  2042. s_wg_denoms = { 64, 64, 1 };
  2043. // spec constants and tile sizes for quant matmul (non-Qi_K)
  2044. l_warptile_mmq = { 256, 128, 256, 64, 1 };
  2045. m_warptile_mmq = { 256, 128, 128, 64, 1 };
  2046. s_warptile_mmq = { 256, 32, 64, 128, 0 };
  2047. l_mmq_wg_denoms = { 128, 256, 1 };
  2048. m_mmq_wg_denoms = { 128, 128, 1 };
  2049. s_mmq_wg_denoms = { 32, 64, 1 };
  2050. // spec constants and tile sizes for quant matmul (Qi_K)
  2051. l_warptile_mmq_k = { 256, 128, 256, 64, 1 };
  2052. m_warptile_mmq_k = { 256, 128, 128, 64, 1 };
  2053. s_warptile_mmq_k = { 256, 32, 64, 128, 0 };
  2054. l_mmq_wg_denoms_k = { 128, 256, 1 };
  2055. m_mmq_wg_denoms_k = { 128, 128, 1 };
  2056. s_mmq_wg_denoms_k = { 32, 64, 1 };
  2057. // spec constants and tile sizes for quant matmul_id
  2058. l_warptile_mmqid = { 256, 128, 128, 16, 1, device->subgroup_size };
  2059. m_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2060. s_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2061. l_mmqid_wg_denoms = { 128, 128, 1 };
  2062. m_mmqid_wg_denoms = { 128, 64, 1 };
  2063. s_mmqid_wg_denoms = { 128, 64, 1 };
  2064. l_align = 128;
  2065. m_align = 64;
  2066. s_align = 32;
  2067. } else {
  2068. // Matrix cores require different warp group sizes
  2069. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  2070. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  2071. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  2072. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  2073. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  2074. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  2075. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  2076. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  2077. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  2078. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2079. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2080. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2081. l_warptile_mmq = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2082. m_warptile_mmq = { 128, 64, 64, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2083. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2084. l_warptile_mmq_int = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2085. m_warptile_mmq_int = { 128, 64, 64, 32, subgroup_size_8, 32, 2, 2, 2, 1, subgroup_size_8 };
  2086. s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, subgroup_size_8 };
  2087. 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 };
  2088. 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 };
  2089. 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 };
  2090. 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 };
  2091. 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 };
  2092. 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 };
  2093. // chip specific tuning
  2094. if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) {
  2095. m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2096. m_warptile_mmqid = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2097. }
  2098. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  2099. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  2100. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  2101. l_align = 128;
  2102. m_align = 64;
  2103. s_align = 32;
  2104. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  2105. ggml_type t = (ggml_type)i;
  2106. // Disable medium and large matrix multiplication if not enough shared memory is available
  2107. // Check mmq warptiles as the largest configuration
  2108. // Throw an error if not enough for any matrix multiplication is available
  2109. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) {
  2110. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  2111. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  2112. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) {
  2113. device->mul_mat_m[i] = false;
  2114. device->mul_mat_l[i] = false;
  2115. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) {
  2116. device->mul_mat_l[i] = false;
  2117. }
  2118. // Disable mul_mat_id if not enough shared memory is available
  2119. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmqid, true, t)) {
  2120. device->mul_mat_id_s[i] = false;
  2121. device->mul_mat_id_m[i] = false;
  2122. device->mul_mat_id_l[i] = false;
  2123. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmqid, true, t)) {
  2124. device->mul_mat_id_m[i] = false;
  2125. device->mul_mat_id_l[i] = false;
  2126. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmqid, true, t)) {
  2127. device->mul_mat_id_l[i] = false;
  2128. }
  2129. }
  2130. }
  2131. if (!device->pipeline_matmul_f32) {
  2132. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2133. }
  2134. if (!device->pipeline_matmul_f32_f16) {
  2135. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  2136. }
  2137. if (!device->pipeline_matmul_id_f32) {
  2138. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2139. }
  2140. if (!device->pipeline_matmul_bf16) {
  2141. device->pipeline_matmul_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2142. }
  2143. if (!device->pipeline_matmul_id_bf16) {
  2144. device->pipeline_matmul_id_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2145. }
  2146. std::vector<std::future<void>> compiles;
  2147. 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,
  2148. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2149. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2150. if (!require_full_subgroups && required_subgroup_size == 0) {
  2151. required_subgroup_size = get_subgroup_size(name, device->architecture);
  2152. }
  2153. if (!pipeline) {
  2154. pipeline = std::make_shared<vk_pipeline_struct>();
  2155. }
  2156. if (!pipeline->initialized) {
  2157. pipeline->name = name;
  2158. pipeline->parameter_count = parameter_count;
  2159. pipeline->push_constant_size = push_constant_size;
  2160. pipeline->wg_denoms = wg_denoms;
  2161. pipeline->align = align;
  2162. pipeline->initialized = true;
  2163. }
  2164. if (!pipeline->needed || pipeline->compiled) {
  2165. return;
  2166. }
  2167. {
  2168. // wait until fewer than N compiles are in progress
  2169. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  2170. std::unique_lock<std::mutex> guard(compile_count_mutex);
  2171. while (compile_count >= N) {
  2172. compile_count_cond.wait(guard);
  2173. }
  2174. compile_count++;
  2175. }
  2176. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  2177. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  2178. };
  2179. 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,
  2180. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2181. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2182. return ggml_vk_create_pipeline(device, pipeline, name.c_str(), spv_size, spv_data, entrypoint,
  2183. parameter_count, push_constant_size, wg_denoms, specialization_constants,
  2184. align, disable_robustness, require_full_subgroups, required_subgroup_size);
  2185. };
  2186. 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> {
  2187. return {fa_rows_cols(path, hsk, hsv, clamp, type, small_rows)[0], 1, 1};
  2188. };
  2189. 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> {
  2190. // For large number of rows, 128 invocations seems to work best.
  2191. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  2192. // can't use 256 for D==80.
  2193. // For scalar, use 128 (arbitrary)
  2194. // The same D_split value is used for both HSK and HSV, so just base it on the union of the LSBs.
  2195. const uint32_t D = (hsk|hsv);
  2196. uint32_t wg_size = (path == FA_SCALAR || path == FA_COOPMAT1)
  2197. ? scalar_flash_attention_workgroup_size
  2198. : ((small_rows && (D % 32) == 0) ? 256 : 128);
  2199. auto rows_cols = fa_rows_cols(path, hsk, hsv, clamp, type, small_rows);
  2200. // D_split can't be larger than a subgroup because we use subgroupShuffle to reduce it.
  2201. // D_split can't be larger than the LSB of D divided by 4 due to vectorization in the shader.
  2202. const uint32_t D_lsb = D ^ (D & (D-1));
  2203. uint32_t D_split = std::min(std::min(device->subgroup_size, 8u), D_lsb / 4);
  2204. // mask dim1 is padded to 64, we rely on this to avoid clamping mask loads
  2205. GGML_ASSERT((GGML_KQ_MASK_PAD % rows_cols[0]) == 0);
  2206. return {wg_size, rows_cols[0], rows_cols[1], hsk, hsv, clamp, D_split};
  2207. };
  2208. #define CREATE_FA(TYPE, NAMELC, FAPATH, SUFFIX) \
  2209. for (auto &fa : device->pipeline_flash_attn_f32_f16[TYPE]) { \
  2210. uint32_t HSK = fa.first.HSK; \
  2211. uint32_t HSV = fa.first.HSV; \
  2212. bool small_rows = fa.first.small_rows; \
  2213. FaCodePath path = fa.first.path; \
  2214. bool aligned = fa.first.aligned; \
  2215. bool f32acc = fa.first.f32acc; \
  2216. if (path == FAPATH) { \
  2217. if (aligned) { \
  2218. if (f32acc) { \
  2219. 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)); \
  2220. } else { \
  2221. 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)); \
  2222. } \
  2223. } else { \
  2224. if (f32acc) { \
  2225. 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)); \
  2226. } else { \
  2227. 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)); \
  2228. } \
  2229. } \
  2230. } \
  2231. }
  2232. CREATE_FA(GGML_TYPE_F16, f16, FA_SCALAR, )
  2233. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_SCALAR, )
  2234. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_SCALAR, )
  2235. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2236. if (device->coopmat1_fa_support) {
  2237. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT1, _cm1)
  2238. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT1, _cm1)
  2239. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT1, _cm1)
  2240. }
  2241. #endif
  2242. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2243. if (device->coopmat2) {
  2244. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT2, _cm2)
  2245. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT2, _cm2)
  2246. CREATE_FA(GGML_TYPE_Q4_1, q4_1, FA_COOPMAT2, _cm2)
  2247. CREATE_FA(GGML_TYPE_Q5_0, q5_0, FA_COOPMAT2, _cm2)
  2248. CREATE_FA(GGML_TYPE_Q5_1, q5_1, FA_COOPMAT2, _cm2)
  2249. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT2, _cm2)
  2250. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl, FA_COOPMAT2, _cm2)
  2251. }
  2252. #endif
  2253. #undef CREATE_FA
  2254. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2255. if (device->coopmat2) {
  2256. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2257. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2258. 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); \
  2259. 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); \
  2260. 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); \
  2261. 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); \
  2262. 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); \
  2263. 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); \
  2264. // Create 2 variants, {f16,f32} accumulator
  2265. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2266. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2267. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2268. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2269. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2270. if (device->coopmat_bf16_support) {
  2271. CREATE_MM(pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2272. }
  2273. #endif
  2274. 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)
  2275. 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)
  2276. 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)
  2277. 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)
  2278. 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)
  2279. 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)
  2280. 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)
  2281. 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)
  2282. 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)
  2283. 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)
  2284. 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)
  2285. 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)
  2286. 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)
  2287. 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)
  2288. 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)
  2289. 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)
  2290. 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)
  2291. 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)
  2292. 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)
  2293. 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)
  2294. GGML_ASSERT(device->subgroup_ballot);
  2295. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2296. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2297. if (device->coopmat_bf16_support) {
  2298. CREATE_MM(pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2299. }
  2300. #endif
  2301. 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)
  2302. 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)
  2303. 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)
  2304. 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)
  2305. 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)
  2306. 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)
  2307. 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)
  2308. 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)
  2309. 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)
  2310. 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)
  2311. 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)
  2312. 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)
  2313. 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)
  2314. 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)
  2315. 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)
  2316. 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)
  2317. 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)
  2318. 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)
  2319. 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)
  2320. 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)
  2321. #undef CREATE_MM
  2322. #undef CREATE_MM2
  2323. } else
  2324. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2325. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2326. if (device->coopmat_support) {
  2327. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2328. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2329. if (device->mul_mat ## ID ## _l[TYPE]) \
  2330. 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); \
  2331. if (device->mul_mat ## ID ## _m[TYPE]) \
  2332. 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); \
  2333. if (device->mul_mat ## ID ## _s[TYPE]) \
  2334. 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); \
  2335. if (device->mul_mat ## ID ## _l[TYPE]) \
  2336. 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); \
  2337. if (device->mul_mat ## ID ## _m[TYPE]) \
  2338. 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); \
  2339. if (device->mul_mat ## ID ## _s[TYPE]) \
  2340. 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); \
  2341. // Create 2 variants, {f16,f32} accumulator
  2342. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2343. if (device->coopmat_acc_f16_support) { \
  2344. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2345. } \
  2346. if (device->coopmat_acc_f32_support) { \
  2347. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2348. } \
  2349. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2350. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2351. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2352. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2353. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2354. if (device->coopmat_bf16_support) {
  2355. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, )
  2356. }
  2357. #endif
  2358. if (device->coopmat_acc_f16_support) {
  2359. 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, );
  2360. 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, );
  2361. 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, );
  2362. 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, );
  2363. 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, );
  2364. 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, );
  2365. 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, );
  2366. 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, );
  2367. 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, );
  2368. 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, );
  2369. 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, );
  2370. 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, );
  2371. 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, );
  2372. 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, );
  2373. 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, );
  2374. 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, );
  2375. 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, );
  2376. 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, );
  2377. 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, );
  2378. 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, );
  2379. } else {
  2380. 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, );
  2381. 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, );
  2382. 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, );
  2383. 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, );
  2384. 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, );
  2385. 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, );
  2386. 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, );
  2387. 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, );
  2388. 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, );
  2389. 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, );
  2390. 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, );
  2391. 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, );
  2392. 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, );
  2393. 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, );
  2394. 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, );
  2395. 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, );
  2396. 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, );
  2397. 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, );
  2398. 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, );
  2399. 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, );
  2400. }
  2401. GGML_ASSERT(device->subgroup_ballot);
  2402. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2403. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2404. 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);
  2405. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2406. if (device->coopmat_bf16_support) {
  2407. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2408. }
  2409. #endif
  2410. 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);
  2411. 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);
  2412. 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);
  2413. 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);
  2414. 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);
  2415. 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);
  2416. 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);
  2417. 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);
  2418. 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);
  2419. 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);
  2420. 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);
  2421. 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);
  2422. 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);
  2423. 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);
  2424. 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);
  2425. 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);
  2426. 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);
  2427. 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);
  2428. 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);
  2429. 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);
  2430. #undef CREATE_MM2
  2431. #undef CREATE_MM
  2432. } else
  2433. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2434. if (device->fp16) {
  2435. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2436. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2437. if (device->mul_mat ## ID ## _l[TYPE]) \
  2438. 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); \
  2439. if (device->mul_mat ## ID ## _m[TYPE]) \
  2440. 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); \
  2441. if (device->mul_mat ## ID ## _s[TYPE]) \
  2442. 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); \
  2443. if (device->mul_mat ## ID ## _l[TYPE]) \
  2444. 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); \
  2445. if (device->mul_mat ## ID ## _m[TYPE]) \
  2446. 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); \
  2447. if (device->mul_mat ## ID ## _s[TYPE]) \
  2448. 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); \
  2449. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2450. if (device->mul_mat ## ID ## _l[TYPE]) { \
  2451. 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); \
  2452. 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); \
  2453. } \
  2454. if (device->mul_mat ## ID ## _m[TYPE]) { \
  2455. 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); \
  2456. 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); \
  2457. } \
  2458. if (device->mul_mat ## ID ## _s[TYPE]) { \
  2459. 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); \
  2460. 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); \
  2461. } \
  2462. // Create 2 variants, {f16,f32} accumulator
  2463. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2464. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2465. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2466. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2467. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2468. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2469. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2470. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2471. 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);
  2472. 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);
  2473. 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);
  2474. 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);
  2475. 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);
  2476. 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);
  2477. 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);
  2478. 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);
  2479. 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);
  2480. 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);
  2481. 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);
  2482. 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);
  2483. 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);
  2484. 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);
  2485. 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);
  2486. 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);
  2487. 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);
  2488. 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);
  2489. 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);
  2490. 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);
  2491. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2492. if (device->integer_dot_product) {
  2493. 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, );
  2494. 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, );
  2495. 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, );
  2496. 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, );
  2497. 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, );
  2498. }
  2499. #endif
  2500. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2501. 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);
  2502. 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);
  2503. 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);
  2504. 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);
  2505. 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);
  2506. 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);
  2507. 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);
  2508. 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);
  2509. 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);
  2510. 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);
  2511. 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);
  2512. 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);
  2513. 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);
  2514. 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);
  2515. 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);
  2516. 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);
  2517. 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);
  2518. 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);
  2519. 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);
  2520. 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);
  2521. 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);
  2522. 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);
  2523. 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);
  2524. 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);
  2525. } else {
  2526. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2527. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2528. 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);
  2529. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2530. 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);
  2531. 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);
  2532. 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);
  2533. 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);
  2534. 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);
  2535. 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);
  2536. 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);
  2537. 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);
  2538. 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);
  2539. 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);
  2540. 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);
  2541. 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);
  2542. 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);
  2543. 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);
  2544. 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);
  2545. 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);
  2546. 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);
  2547. 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);
  2548. 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);
  2549. 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);
  2550. }
  2551. #undef CREATE_MM2
  2552. #undef CREATE_MMQ
  2553. #undef CREATE_MM
  2554. } else {
  2555. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2556. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2557. if (device->mul_mat ## ID ## _l[TYPE]) \
  2558. 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); \
  2559. if (device->mul_mat ## ID ## _m[TYPE]) \
  2560. 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); \
  2561. if (device->mul_mat ## ID ## _s[TYPE]) \
  2562. 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); \
  2563. if (device->mul_mat ## ID ## _l[TYPE]) \
  2564. 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); \
  2565. if (device->mul_mat ## ID ## _m[TYPE]) \
  2566. 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); \
  2567. if (device->mul_mat ## ID ## _s[TYPE]) \
  2568. 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); \
  2569. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2570. if (device->mul_mat ## ID ## _l[TYPE]) \
  2571. 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); \
  2572. if (device->mul_mat ## ID ## _m[TYPE]) \
  2573. 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); \
  2574. if (device->mul_mat ## ID ## _s[TYPE]) \
  2575. 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); \
  2576. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2577. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2578. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2579. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2580. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2581. 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);
  2582. 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);
  2583. 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);
  2584. 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);
  2585. 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);
  2586. 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);
  2587. 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);
  2588. 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);
  2589. 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);
  2590. 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);
  2591. 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);
  2592. 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);
  2593. 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);
  2594. 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);
  2595. 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);
  2596. 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);
  2597. 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);
  2598. 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);
  2599. 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);
  2600. 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);
  2601. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2602. if (device->integer_dot_product) {
  2603. 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, );
  2604. 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, );
  2605. 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, );
  2606. 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, );
  2607. 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, );
  2608. }
  2609. #endif
  2610. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2611. 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);
  2612. 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);
  2613. 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);
  2614. 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);
  2615. 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);
  2616. 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);
  2617. 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);
  2618. 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);
  2619. 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);
  2620. 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);
  2621. 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);
  2622. 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);
  2623. 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);
  2624. 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);
  2625. 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);
  2626. 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);
  2627. 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);
  2628. 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);
  2629. 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);
  2630. 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);
  2631. 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);
  2632. 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);
  2633. 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);
  2634. 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);
  2635. } else {
  2636. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2637. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2638. 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);
  2639. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2640. 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);
  2641. 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);
  2642. 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);
  2643. 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);
  2644. 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);
  2645. 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);
  2646. 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);
  2647. 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);
  2648. 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);
  2649. 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);
  2650. 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);
  2651. 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);
  2652. 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);
  2653. 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);
  2654. 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);
  2655. 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);
  2656. 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);
  2657. 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);
  2658. 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);
  2659. 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);
  2660. }
  2661. }
  2662. // reusing CREATE_MM from the fp32 path
  2663. if ((device->coopmat2 || device->coopmat_support)
  2664. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2665. && !device->coopmat_bf16_support
  2666. #endif
  2667. ) {
  2668. // use scalar tile sizes
  2669. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2670. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, 4, 2, 1, subgroup_size_8 };
  2671. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, 2, 2, 1, subgroup_size_8 };
  2672. l_wg_denoms = {128, 128, 1 };
  2673. m_wg_denoms = { 64, 64, 1 };
  2674. s_wg_denoms = { 32, 32, 1 };
  2675. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2676. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2677. }
  2678. #undef CREATE_MM
  2679. // mul mat vec
  2680. // the number of rows computed per shader depends on GPU model and quant
  2681. uint32_t rm_stdq = 1;
  2682. uint32_t rm_kq = 2;
  2683. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  2684. if (device->architecture == AMD_GCN) {
  2685. rm_stdq = 2;
  2686. rm_kq = 4;
  2687. }
  2688. } else if (device->vendor_id == VK_VENDOR_ID_INTEL)
  2689. rm_stdq = 2;
  2690. uint32_t rm_iq = 2 * rm_kq;
  2691. const bool use_subgroups = device->subgroup_arithmetic && device->architecture != vk_device_architecture::AMD_GCN;
  2692. // Ensure a subgroup size >= 16 is available
  2693. const bool use_subgroups16 = use_subgroups && subgroup_min_size_16;
  2694. 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;
  2695. const uint32_t subgroup_size16 = std::max(subgroup_size, 16u);
  2696. const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0;
  2697. const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0;
  2698. for (uint32_t w = 0; w < DMMV_WG_SIZE_COUNT; ++w) {
  2699. const uint32_t wg_size_subgroup = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size : (subgroup_size * 4);
  2700. const uint32_t wg_size_subgroup16 = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size16 : (subgroup_size16 * 4);
  2701. const shader_reduction_mode reduc = (use_subgroups && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  2702. (use_subgroups && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  2703. SHADER_REDUCTION_MODE_SHMEM;
  2704. const shader_reduction_mode reduc16 = (use_subgroups16 && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  2705. (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  2706. SHADER_REDUCTION_MODE_SHMEM;
  2707. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  2708. 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);
  2709. 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);
  2710. 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);
  2711. 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);
  2712. 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);
  2713. 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);
  2714. 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);
  2715. 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);
  2716. 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);
  2717. 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);
  2718. 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);
  2719. 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);
  2720. 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);
  2721. 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);
  2722. 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);
  2723. 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);
  2724. 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);
  2725. 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);
  2726. 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);
  2727. 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);
  2728. 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);
  2729. 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);
  2730. 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);
  2731. 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);
  2732. 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);
  2733. 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);
  2734. 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);
  2735. 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);
  2736. 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);
  2737. 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);
  2738. 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);
  2739. 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);
  2740. 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);
  2741. 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);
  2742. 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);
  2743. 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);
  2744. 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);
  2745. 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);
  2746. 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);
  2747. 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);
  2748. 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);
  2749. 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);
  2750. 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);
  2751. 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);
  2752. 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);
  2753. 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);
  2754. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2755. if (device->integer_dot_product) {
  2756. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  2757. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  2758. 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);
  2759. 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);
  2760. 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);
  2761. 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);
  2762. 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);
  2763. }
  2764. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  2765. }
  2766. }
  2767. 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);
  2768. 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);
  2769. 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);
  2770. 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);
  2771. 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);
  2772. 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);
  2773. 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);
  2774. 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);
  2775. 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);
  2776. 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);
  2777. 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);
  2778. 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);
  2779. 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);
  2780. 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);
  2781. 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);
  2782. 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);
  2783. 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);
  2784. 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);
  2785. 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);
  2786. 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);
  2787. 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);
  2788. 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);
  2789. 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);
  2790. // dequant shaders
  2791. 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);
  2792. 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);
  2793. 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);
  2794. 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);
  2795. 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);
  2796. 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);
  2797. 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);
  2798. 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);
  2799. 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);
  2800. 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);
  2801. 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);
  2802. 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);
  2803. 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);
  2804. 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);
  2805. 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);
  2806. 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);
  2807. 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);
  2808. 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);
  2809. 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);
  2810. 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);
  2811. 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);
  2812. // get_rows
  2813. 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);
  2814. 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);
  2815. 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);
  2816. 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);
  2817. 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);
  2818. 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);
  2819. 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);
  2820. 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);
  2821. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q2_K], "get_rows_q2_k", get_rows_q2_k_len, get_rows_q2_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2822. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q3_K], "get_rows_q3_k", get_rows_q3_k_len, get_rows_q3_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2823. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_K], "get_rows_q4_k", get_rows_q4_k_len, get_rows_q4_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2824. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_K], "get_rows_q5_k", get_rows_q5_k_len, get_rows_q5_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2825. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q6_K], "get_rows_q6_k", get_rows_q6_k_len, get_rows_q6_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2826. 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);
  2827. 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);
  2828. 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);
  2829. 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);
  2830. 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);
  2831. 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);
  2832. 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);
  2833. 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);
  2834. 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);
  2835. 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);
  2836. 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);
  2837. 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);
  2838. 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);
  2839. 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);
  2840. 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);
  2841. 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);
  2842. 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);
  2843. 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);
  2844. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q2_K], "get_rows_q2_k_f32", get_rows_q2_k_f32_len, get_rows_q2_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2845. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q3_K], "get_rows_q3_k_f32", get_rows_q3_k_f32_len, get_rows_q3_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2846. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q4_K], "get_rows_q4_k_f32", get_rows_q4_k_f32_len, get_rows_q4_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2847. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q5_K], "get_rows_q5_k_f32", get_rows_q5_k_f32_len, get_rows_q5_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2848. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q6_K], "get_rows_q6_k_f32", get_rows_q6_k_f32_len, get_rows_q6_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  2849. 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);
  2850. 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);
  2851. 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);
  2852. 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);
  2853. 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);
  2854. 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);
  2855. 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);
  2856. 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);
  2857. 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);
  2858. 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);
  2859. 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);
  2860. 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);
  2861. if (device->subgroup_clustered && device->subgroup_require_full_support) {
  2862. 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);
  2863. 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);
  2864. } else {
  2865. 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);
  2866. 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);
  2867. }
  2868. for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) {
  2869. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  2870. 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);
  2871. } else {
  2872. 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);
  2873. }
  2874. }
  2875. 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);
  2876. 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);
  2877. 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);
  2878. 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);
  2879. 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);
  2880. 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);
  2881. 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);
  2882. 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);
  2883. 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);
  2884. 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);
  2885. 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);
  2886. 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);
  2887. 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);
  2888. 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);
  2889. 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);
  2890. 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);
  2891. 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);
  2892. 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);
  2893. 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);
  2894. 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);
  2895. 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);
  2896. 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);
  2897. 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);
  2898. if (device->float_controls_rte_fp16) {
  2899. 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);
  2900. 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);
  2901. 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);
  2902. 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);
  2903. 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);
  2904. 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);
  2905. } else {
  2906. 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);
  2907. 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);
  2908. 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);
  2909. 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);
  2910. 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);
  2911. 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);
  2912. }
  2913. #define SET_ROWS(itype, rte) \
  2914. 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); \
  2915. 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); \
  2916. 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); \
  2917. 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); \
  2918. 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); \
  2919. 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); \
  2920. 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); \
  2921. 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); \
  2922. 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);
  2923. if (device->float_controls_rte_fp16) {
  2924. SET_ROWS(_i32, _rte)
  2925. SET_ROWS(_i64, _rte)
  2926. } else {
  2927. SET_ROWS(_i32, )
  2928. SET_ROWS(_i64, )
  2929. }
  2930. #undef SET_ROWS
  2931. 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);
  2932. 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);
  2933. 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);
  2934. 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);
  2935. 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);
  2936. 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);
  2937. auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) {
  2938. std::string s;
  2939. s += std::string(src0_f16 ? "_f16" : "_f32");
  2940. s += std::string(src1_f16 ? "_f16" : "_f32");
  2941. s += std::string(dst_f16 ? "_f16" : "_f32");
  2942. return s;
  2943. };
  2944. bool rte = device->float_controls_rte_fp16;
  2945. #define CREATE_BINARY(name, namemod, spec, bindings) \
  2946. for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \
  2947. ggml_vk_create_pipeline2(device, device->pipeline_ ## name ## namemod[s0][s1][d], \
  2948. #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d][rte], name ## _data[s0][s1][d][rte], \
  2949. "main", (bindings), sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1);
  2950. CREATE_BINARY(add, , {0}, 4)
  2951. CREATE_BINARY(add, _norepeat, {1}, 4)
  2952. CREATE_BINARY(sub, , {0}, 3)
  2953. CREATE_BINARY(sub, _norepeat, {1}, 3)
  2954. CREATE_BINARY(mul, , {0}, 3)
  2955. CREATE_BINARY(mul, _norepeat, {1}, 3)
  2956. CREATE_BINARY(div, , {0}, 3)
  2957. CREATE_BINARY(div, _norepeat, {1}, 3)
  2958. CREATE_BINARY(add_rms, , {0}, 4)
  2959. CREATE_BINARY(add_rms, _norepeat, {1}, 4)
  2960. #undef CREATE_BINARY
  2961. if (device->multi_add) {
  2962. for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) {
  2963. 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);
  2964. 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);
  2965. }
  2966. }
  2967. 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);
  2968. 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);
  2969. 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);
  2970. 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);
  2971. 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);
  2972. 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);
  2973. 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);
  2974. 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);
  2975. 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);
  2976. 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);
  2977. 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);
  2978. 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);
  2979. 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);
  2980. 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);
  2981. 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);
  2982. 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);
  2983. 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);
  2984. 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);
  2985. #define CREATE_UNARY(name) \
  2986. 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); \
  2987. 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);
  2988. CREATE_UNARY(gelu)
  2989. CREATE_UNARY(gelu_erf)
  2990. CREATE_UNARY(gelu_quick)
  2991. CREATE_UNARY(silu)
  2992. CREATE_UNARY(relu)
  2993. CREATE_UNARY(tanh)
  2994. CREATE_UNARY(sigmoid)
  2995. CREATE_UNARY(hardsigmoid)
  2996. CREATE_UNARY(hardswish)
  2997. #undef CREATE_UNARY
  2998. #define CREATE_UNARY_RTE(name) \
  2999. if (device->float_controls_rte_fp16) { \
  3000. 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); \
  3001. 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); \
  3002. } else { \
  3003. 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); \
  3004. 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); \
  3005. }
  3006. CREATE_UNARY_RTE(exp)
  3007. #undef CREATE_UNARY_RTE
  3008. #define CREATE_GLU(name) \
  3009. if (device->float_controls_rte_fp16) { \
  3010. 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); \
  3011. 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); \
  3012. } else { \
  3013. 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); \
  3014. 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); \
  3015. }
  3016. CREATE_GLU(geglu)
  3017. CREATE_GLU(reglu)
  3018. CREATE_GLU(swiglu)
  3019. CREATE_GLU(swiglu_oai)
  3020. CREATE_GLU(geglu_erf)
  3021. CREATE_GLU(geglu_quick)
  3022. #undef CREATE_GLU
  3023. 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);
  3024. 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);
  3025. 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);
  3026. 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);
  3027. 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);
  3028. 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);
  3029. 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);
  3030. 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);
  3031. 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);
  3032. 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);
  3033. 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);
  3034. 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);
  3035. if (device->float_controls_rte_fp16) {
  3036. 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);
  3037. 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);
  3038. 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);
  3039. 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);
  3040. } else {
  3041. 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);
  3042. 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);
  3043. 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);
  3044. 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);
  3045. }
  3046. for (uint32_t i = 0; i < num_argsort_pipelines; ++i) {
  3047. 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);
  3048. }
  3049. 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);
  3050. 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);
  3051. 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);
  3052. #define IM2COL(bda) \
  3053. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32, "im2col_f32", im2col_f32 ## bda ## _len, im2col_f32 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \
  3054. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32, "im2col_3d_f32", im2col_3d_f32 ## bda ## _len, im2col_3d_f32 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \
  3055. if (device->float_controls_rte_fp16) { \
  3056. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16_rte ## bda ## _len, im2col_f32_f16_rte ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \
  3057. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32_f16, "im2col_3d_f32_f16", im2col_3d_f32_f16_rte ## bda ## _len, im2col_3d_f32_f16_rte ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \
  3058. } else { \
  3059. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16 ## bda ## _len, im2col_f32_f16 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \
  3060. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32_f16, "im2col_3d_f32_f16", im2col_3d_f32_f16 ## bda ## _len, im2col_3d_f32_f16 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \
  3061. }
  3062. if (device->shader_int64 && device->buffer_device_address) {
  3063. IM2COL(_bda)
  3064. } else {
  3065. IM2COL()
  3066. }
  3067. 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);
  3068. 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);
  3069. 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);
  3070. 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);
  3071. 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);
  3072. 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);
  3073. 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);
  3074. // conv2d, conv_transpose_2d
  3075. for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) {
  3076. uint32_t conv2d_WG_SIZE = 256;
  3077. uint32_t conv2d_BS_K = 128;
  3078. uint32_t conv2d_BS_CRS = 16;
  3079. uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices.
  3080. uint32_t conv2d_BS_NPQ = 128;
  3081. uint32_t conv2d_TS_K = 8;
  3082. uint32_t conv2d_SHMEM_PAD = 4;
  3083. bool conv2d_UNROLL = true;
  3084. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3085. if (device->coopmat2) {
  3086. conv2d_SHMEM_PAD = 8; // 8 float16_t
  3087. }
  3088. #endif
  3089. if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3090. conv2d_SHMEM_PAD = 0;
  3091. conv2d_UNROLL = false;
  3092. } else if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3093. conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4;
  3094. }
  3095. switch (s) {
  3096. default:
  3097. case CONV_SHAPE_128x128:
  3098. conv2d_BS_K = 128;
  3099. conv2d_BS_NPQ = 128;
  3100. conv2d_BS_CRS = 16;
  3101. if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != vk_device_architecture::AMD_GCN) {
  3102. conv2d_UNROLL = false;
  3103. }
  3104. break;
  3105. case CONV_SHAPE_64x32:
  3106. conv2d_BS_K = 64;
  3107. conv2d_BS_NPQ = 32;
  3108. conv2d_BS_CRS = 32;
  3109. conv2d_TS_K = 4;
  3110. break;
  3111. case CONV_SHAPE_32x256:
  3112. conv2d_BS_K = 32;
  3113. conv2d_BS_NPQ = 256;
  3114. conv2d_BS_CRS = 16;
  3115. break;
  3116. }
  3117. // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math.
  3118. bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA ||
  3119. device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  3120. bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD ||
  3121. device->architecture == vk_device_architecture::AMD_GCN;
  3122. if (device->subgroup_shuffle &&
  3123. device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316.
  3124. allow_collectives_nv &&
  3125. allow_collectives_amd) {
  3126. use_collectives = 1;
  3127. conv2d_BS_CRS = std::min(
  3128. device->subgroup_size,
  3129. conv2d_BS_CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used.
  3130. }
  3131. uint32_t conv2d_shmem_req =
  3132. (conv2d_BS_K * (conv2d_BS_CRS + conv2d_SHMEM_PAD) + conv2d_BS_CRS * (conv2d_BS_NPQ + conv2d_SHMEM_PAD)) * sizeof(float);
  3133. if (device->properties.limits.maxComputeSharedMemorySize < conv2d_shmem_req) {
  3134. conv2d_BS_CRS = 8;
  3135. if (use_collectives) {
  3136. conv2d_BS_CRS = std::min(device->subgroup_size, conv2d_BS_CRS);
  3137. }
  3138. }
  3139. std::array<uint32_t, 3> wg_denoms = { conv2d_BS_K, conv2d_BS_NPQ, 1 };
  3140. 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 };
  3141. #define CREATE_CONV(name, type_suffix, spv_suffix) \
  3142. ggml_vk_create_pipeline( \
  3143. device, device->pipeline_##name##type_suffix[s], #name #type_suffix, \
  3144. name##type_suffix##spv_suffix##_len, name##type_suffix##spv_suffix##_data, "main", 3, \
  3145. sizeof(vk_op_##name##_push_constants), wg_denoms, spec_constants, 1, true, use_collectives);
  3146. #define CREATE_CONVS(spv_suffix) \
  3147. CREATE_CONV(conv2d, _f32, spv_suffix) \
  3148. CREATE_CONV(conv2d, _f16_f32, spv_suffix) \
  3149. if (device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_conv_transpose_2d_push_constants)) { \
  3150. CREATE_CONV(conv_transpose_2d, _f32, spv_suffix) \
  3151. CREATE_CONV(conv_transpose_2d, _f16_f32, spv_suffix) \
  3152. }
  3153. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3154. if (device->coopmat2) {
  3155. CREATE_CONVS(_cm2)
  3156. } else
  3157. #endif
  3158. if (conv2d_UNROLL) {
  3159. CREATE_CONVS(_unroll)
  3160. } else {
  3161. CREATE_CONVS( )
  3162. }
  3163. #undef CREATE_CONV
  3164. #undef CREATE_CONVS
  3165. }
  3166. 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);
  3167. 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);
  3168. 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);
  3169. 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);
  3170. for (auto &c : compiles) {
  3171. c.wait();
  3172. }
  3173. device->need_compiles = false;
  3174. }
  3175. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch);
  3176. static vk_device ggml_vk_get_device(size_t idx) {
  3177. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  3178. if (vk_instance.devices[idx] == nullptr) {
  3179. VK_LOG_DEBUG("Initializing new vk_device");
  3180. vk_device device = std::make_shared<vk_device_struct>();
  3181. vk_instance.devices[idx] = device;
  3182. #ifdef GGML_VULKAN_MEMORY_DEBUG
  3183. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  3184. #endif
  3185. if (vk_perf_logger_enabled) {
  3186. device->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  3187. }
  3188. size_t dev_num = vk_instance.device_indices[idx];
  3189. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  3190. if (dev_num >= physical_devices.size()) {
  3191. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3192. throw std::runtime_error("Device not found");
  3193. }
  3194. device->physical_device = physical_devices[dev_num];
  3195. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  3196. device->architecture = get_device_architecture(device->physical_device);
  3197. const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY");
  3198. device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr;
  3199. const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM");
  3200. device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr;
  3201. const char* GGML_VK_ALLOW_SYSMEM_FALLBACK = getenv("GGML_VK_ALLOW_SYSMEM_FALLBACK");
  3202. device->allow_sysmem_fallback = GGML_VK_ALLOW_SYSMEM_FALLBACK != nullptr;
  3203. const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE");
  3204. device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr;
  3205. bool fp16_storage = false;
  3206. bool fp16_compute = false;
  3207. bool maintenance4_support = false;
  3208. bool sm_builtins = false;
  3209. bool amd_shader_core_properties2 = false;
  3210. bool pipeline_robustness = false;
  3211. bool coopmat2_support = false;
  3212. bool pipeline_executable_properties_support = false;
  3213. device->coopmat_support = false;
  3214. device->integer_dot_product = false;
  3215. bool bfloat16_support = false;
  3216. for (const auto& properties : ext_props) {
  3217. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  3218. maintenance4_support = true;
  3219. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3220. fp16_storage = true;
  3221. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3222. fp16_compute = true;
  3223. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  3224. sm_builtins = true;
  3225. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  3226. amd_shader_core_properties2 = true;
  3227. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  3228. pipeline_robustness = true;
  3229. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  3230. device->subgroup_size_control = true;
  3231. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3232. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3233. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3234. device->coopmat_support = true;
  3235. device->coopmat_m = 0;
  3236. device->coopmat_n = 0;
  3237. device->coopmat_k = 0;
  3238. #endif
  3239. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3240. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3241. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3242. coopmat2_support = true;
  3243. #endif
  3244. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3245. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3246. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3247. device->integer_dot_product = true;
  3248. #endif
  3249. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3250. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3251. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3252. bfloat16_support = true;
  3253. #endif
  3254. } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) {
  3255. pipeline_executable_properties_support = true;
  3256. }
  3257. }
  3258. vk::PhysicalDeviceProperties2 props2;
  3259. vk::PhysicalDeviceMaintenance3Properties props3;
  3260. vk::PhysicalDeviceMaintenance4Properties props4;
  3261. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3262. vk::PhysicalDeviceDriverProperties driver_props;
  3263. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  3264. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  3265. vk::PhysicalDeviceVulkan11Properties vk11_props;
  3266. vk::PhysicalDeviceVulkan12Properties vk12_props;
  3267. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  3268. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3269. props2.pNext = &props3;
  3270. props3.pNext = &subgroup_props;
  3271. subgroup_props.pNext = &driver_props;
  3272. driver_props.pNext = &vk11_props;
  3273. vk11_props.pNext = &vk12_props;
  3274. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  3275. if (maintenance4_support) {
  3276. last_struct->pNext = (VkBaseOutStructure *)&props4;
  3277. last_struct = (VkBaseOutStructure *)&props4;
  3278. }
  3279. if (sm_builtins) {
  3280. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  3281. last_struct = (VkBaseOutStructure *)&sm_props;
  3282. }
  3283. if (amd_shader_core_properties2) {
  3284. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3285. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3286. }
  3287. if (device->subgroup_size_control) {
  3288. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  3289. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  3290. }
  3291. #if defined(VK_NV_cooperative_matrix2)
  3292. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  3293. if (coopmat2_support) {
  3294. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  3295. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  3296. }
  3297. #endif
  3298. if (device->integer_dot_product) {
  3299. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3300. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3301. }
  3302. device->physical_device.getProperties2(&props2);
  3303. device->properties = props2.properties;
  3304. device->vendor_id = device->properties.vendorID;
  3305. device->driver_id = driver_props.driverID;
  3306. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  3307. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  3308. device->max_memory_allocation_size = std::stoul(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  3309. } else if (maintenance4_support) {
  3310. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  3311. } else {
  3312. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  3313. }
  3314. const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE");
  3315. if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) {
  3316. device->suballocation_block_size = std::stoul(GGML_VK_SUBALLOCATION_BLOCK_SIZE);
  3317. } else {
  3318. // Limit batching of allocations to 1GB by default to avoid fragmentation issues
  3319. device->suballocation_block_size = 1024*1024*1024;
  3320. }
  3321. device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size);
  3322. device->subgroup_size = subgroup_props.subgroupSize;
  3323. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3324. if (sm_builtins) {
  3325. device->shader_core_count = sm_props.shaderSMCount;
  3326. } else if (amd_shader_core_properties2) {
  3327. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  3328. } else {
  3329. device->shader_core_count = 0;
  3330. }
  3331. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  3332. device->subgroup_arithmetic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3333. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic);
  3334. #ifdef __APPLE__
  3335. // Workaround for subgroup arithmetic failing on MoltenVK with AMD GPUs (issue 15846)
  3336. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3337. device->subgroup_arithmetic = false;
  3338. }
  3339. #endif
  3340. device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3341. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle);
  3342. device->subgroup_clustered = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3343. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eClustered);
  3344. device->subgroup_ballot = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3345. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBallot);
  3346. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  3347. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  3348. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) {
  3349. device->coopmat_support = false;
  3350. }
  3351. device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated;
  3352. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  3353. // Try to find a non-graphics compute queue and transfer-focused queues
  3354. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  3355. 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);
  3356. const float priorities[] = { 1.0f, 1.0f };
  3357. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  3358. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  3359. if (compute_queue_family_index != transfer_queue_family_index) {
  3360. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3361. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  3362. } else if(!device->single_queue) {
  3363. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  3364. } else {
  3365. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3366. }
  3367. vk::DeviceCreateInfo device_create_info;
  3368. std::vector<const char *> device_extensions;
  3369. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  3370. VkPhysicalDeviceFeatures2 device_features2;
  3371. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  3372. device_features2.pNext = nullptr;
  3373. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  3374. VkPhysicalDeviceVulkan11Features vk11_features;
  3375. vk11_features.pNext = nullptr;
  3376. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  3377. device_features2.pNext = &vk11_features;
  3378. VkPhysicalDeviceVulkan12Features vk12_features;
  3379. vk12_features.pNext = nullptr;
  3380. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  3381. vk11_features.pNext = &vk12_features;
  3382. last_struct = (VkBaseOutStructure *)&vk12_features;
  3383. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  3384. pl_robustness_features.pNext = nullptr;
  3385. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  3386. pl_robustness_features.pipelineRobustness = VK_FALSE;
  3387. if (pipeline_robustness) {
  3388. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  3389. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  3390. device_extensions.push_back("VK_EXT_pipeline_robustness");
  3391. }
  3392. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  3393. subgroup_size_control_features.pNext = nullptr;
  3394. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  3395. subgroup_size_control_features.computeFullSubgroups = false;
  3396. subgroup_size_control_features.subgroupSizeControl = false;
  3397. if (device->subgroup_size_control) {
  3398. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  3399. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  3400. }
  3401. #if defined(VK_KHR_cooperative_matrix)
  3402. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  3403. coopmat_features.pNext = nullptr;
  3404. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  3405. coopmat_features.cooperativeMatrix = VK_FALSE;
  3406. if (device->coopmat_support) {
  3407. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  3408. last_struct = (VkBaseOutStructure *)&coopmat_features;
  3409. }
  3410. #endif
  3411. #if defined(VK_NV_cooperative_matrix2)
  3412. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  3413. coopmat2_features.pNext = nullptr;
  3414. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  3415. if (coopmat2_support) {
  3416. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  3417. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  3418. device_extensions.push_back("VK_NV_cooperative_matrix2");
  3419. }
  3420. #endif
  3421. #if defined(VK_KHR_shader_bfloat16)
  3422. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  3423. bfloat16_features.pNext = nullptr;
  3424. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  3425. if (bfloat16_support) {
  3426. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  3427. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  3428. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3429. }
  3430. #endif
  3431. VkPhysicalDeviceMaintenance4Features maint4_features {};
  3432. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  3433. if (maintenance4_support) {
  3434. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  3435. last_struct = (VkBaseOutStructure *)&maint4_features;
  3436. device_extensions.push_back("VK_KHR_maintenance4");
  3437. }
  3438. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  3439. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  3440. if (device->integer_dot_product) {
  3441. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3442. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3443. device_extensions.push_back("VK_KHR_shader_integer_dot_product");
  3444. }
  3445. VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pep_features {};
  3446. pep_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR;
  3447. if (pipeline_executable_properties_support) {
  3448. last_struct->pNext = (VkBaseOutStructure *)&pep_features;
  3449. last_struct = (VkBaseOutStructure *)&pep_features;
  3450. device_extensions.push_back("VK_KHR_pipeline_executable_properties");
  3451. }
  3452. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  3453. device->pipeline_executable_properties_support = pipeline_executable_properties_support;
  3454. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  3455. #if defined(VK_KHR_shader_bfloat16)
  3456. device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  3457. #else
  3458. device->bf16 = false;
  3459. #endif
  3460. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  3461. device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 &&
  3462. device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) &&
  3463. vk12_features.runtimeDescriptorArray &&
  3464. device->vendor_id != VK_VENDOR_ID_INTEL &&
  3465. getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr;
  3466. device->shader_int64 = device_features2.features.shaderInt64;
  3467. device->buffer_device_address = vk12_features.bufferDeviceAddress;
  3468. if (device->subgroup_size_control) {
  3469. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  3470. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  3471. device_extensions.push_back("VK_EXT_subgroup_size_control");
  3472. }
  3473. device->subgroup_size_control = device->subgroup_size_control &&
  3474. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  3475. subgroup_size_control_features.subgroupSizeControl;
  3476. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  3477. #if defined(VK_KHR_cooperative_matrix)
  3478. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  3479. // coopmat1 fa shader currently assumes 32 invocations per subgroup
  3480. device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support &&
  3481. device->subgroup_size_control && device->subgroup_min_size <= 32 &&
  3482. device->subgroup_max_size >= 32;
  3483. #endif
  3484. if (coopmat2_support) {
  3485. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3486. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  3487. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  3488. coopmat2_features.cooperativeMatrixReductions &&
  3489. coopmat2_features.cooperativeMatrixConversions &&
  3490. coopmat2_features.cooperativeMatrixPerElementOperations &&
  3491. coopmat2_features.cooperativeMatrixTensorAddressing &&
  3492. coopmat2_features.cooperativeMatrixBlockLoads &&
  3493. vk12_features.bufferDeviceAddress) {
  3494. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  3495. uint32_t count = 0;
  3496. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  3497. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  3498. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  3499. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  3500. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  3501. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  3502. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  3503. flexible_dimensions.resize(count, empty_prop);
  3504. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  3505. bool found_fp16_128 = false,
  3506. found_fp16_256 = false,
  3507. found_fp32_128 = false,
  3508. found_fp32_256 = false;
  3509. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  3510. // with 32x16x16 and 256 with 32x32x16.
  3511. for (auto &prop : flexible_dimensions) {
  3512. if (prop.saturatingAccumulation == VK_FALSE &&
  3513. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  3514. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3515. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3516. if (prop.workgroupInvocations == 128 &&
  3517. prop.MGranularity <= 32 &&
  3518. prop.NGranularity <= 16 &&
  3519. prop.KGranularity <= 16) {
  3520. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3521. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3522. found_fp16_128 = true;
  3523. }
  3524. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3525. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3526. found_fp32_128 = true;
  3527. }
  3528. }
  3529. if (prop.workgroupInvocations == 256 &&
  3530. prop.MGranularity <= 32 &&
  3531. prop.NGranularity <= 32 &&
  3532. prop.KGranularity <= 16) {
  3533. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3534. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3535. found_fp16_256 = true;
  3536. }
  3537. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3538. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3539. found_fp32_256 = true;
  3540. }
  3541. }
  3542. }
  3543. }
  3544. if (found_fp16_128 && found_fp16_256 &&
  3545. found_fp32_128 && found_fp32_256 &&
  3546. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  3547. device->coopmat2 = true;
  3548. }
  3549. }
  3550. #endif
  3551. }
  3552. if (!vk11_features.storageBuffer16BitAccess) {
  3553. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  3554. throw std::runtime_error("Unsupported device");
  3555. }
  3556. device_extensions.push_back("VK_KHR_16bit_storage");
  3557. #ifdef GGML_VULKAN_VALIDATE
  3558. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  3559. #endif
  3560. if (device->fp16) {
  3561. device_extensions.push_back("VK_KHR_shader_float16_int8");
  3562. }
  3563. #if defined(VK_KHR_cooperative_matrix)
  3564. if (device->coopmat_support) {
  3565. // Query supported shapes
  3566. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  3567. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  3568. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  3569. uint32_t cm_props_num;
  3570. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  3571. cm_props.resize(cm_props_num);
  3572. for (auto& prop : cm_props) {
  3573. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  3574. }
  3575. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  3576. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  3577. for (auto& prop : cm_props) {
  3578. 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));
  3579. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  3580. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  3581. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3582. ) {
  3583. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  3584. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  3585. // coopmat sizes not set yet
  3586. if (device->coopmat_m == 0) {
  3587. device->coopmat_acc_f32_support = true;
  3588. device->coopmat_m = prop.MSize;
  3589. device->coopmat_n = prop.NSize;
  3590. device->coopmat_k = prop.KSize;
  3591. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3592. // Only enable if shape is identical
  3593. device->coopmat_acc_f32_support = true;
  3594. }
  3595. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3596. device->coopmat_support_16x16x16_f32acc = true;
  3597. }
  3598. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  3599. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  3600. // coopmat sizes not set yet
  3601. if (device->coopmat_m == 0) {
  3602. device->coopmat_acc_f16_support = true;
  3603. device->coopmat_m = prop.MSize;
  3604. device->coopmat_n = prop.NSize;
  3605. device->coopmat_k = prop.KSize;
  3606. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3607. // Only enable if shape is identical
  3608. device->coopmat_acc_f16_support = true;
  3609. }
  3610. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3611. device->coopmat_support_16x16x16_f16acc = true;
  3612. }
  3613. }
  3614. } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 &&
  3615. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 &&
  3616. (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 &&
  3617. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 &&
  3618. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup &&
  3619. device->coopmat_int_m == 0
  3620. ) {
  3621. device->coopmat_int_support = true;
  3622. device->coopmat_int_m = prop.MSize;
  3623. device->coopmat_int_n = prop.NSize;
  3624. device->coopmat_int_k = prop.KSize;
  3625. }
  3626. #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3627. if (prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3628. prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3629. prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3630. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3631. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3632. ) {
  3633. // coopmat sizes not set yet
  3634. if (device->coopmat_m == 0) {
  3635. device->coopmat_bf16_support = true;
  3636. device->coopmat_m = prop.MSize;
  3637. device->coopmat_n = prop.NSize;
  3638. device->coopmat_k = prop.KSize;
  3639. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3640. // Only enable if shape is identical
  3641. device->coopmat_bf16_support = true;
  3642. }
  3643. }
  3644. #endif
  3645. }
  3646. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  3647. // No suitable matmul mode found
  3648. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  3649. device->coopmat_support = false;
  3650. }
  3651. if (getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3652. device->coopmat_bf16_support = false;
  3653. }
  3654. }
  3655. if (device->coopmat_support) {
  3656. device_extensions.push_back("VK_KHR_cooperative_matrix");
  3657. }
  3658. #if defined(VK_KHR_shader_bfloat16)
  3659. if (device->coopmat_bf16_support) {
  3660. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3661. }
  3662. #endif
  3663. #endif
  3664. device->name = GGML_VK_NAME + std::to_string(idx);
  3665. device_create_info = {
  3666. vk::DeviceCreateFlags(),
  3667. device_queue_create_infos,
  3668. {},
  3669. device_extensions
  3670. };
  3671. device_create_info.setPNext(&device_features2);
  3672. device->device = device->physical_device.createDevice(device_create_info);
  3673. // Queues
  3674. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  3675. // Shaders
  3676. // Disable matmul tile sizes early if performance low or not supported
  3677. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  3678. switch (device->vendor_id) {
  3679. #ifndef GGML_VULKAN_RUN_TESTS
  3680. case VK_VENDOR_ID_AMD:
  3681. case VK_VENDOR_ID_INTEL:
  3682. device->mul_mat_l[i] = false;
  3683. device->mul_mat_m[i] = true;
  3684. device->mul_mat_s[i] = true;
  3685. device->mul_mat_id_l[i] = false;
  3686. device->mul_mat_id_m[i] = true;
  3687. device->mul_mat_id_s[i] = true;
  3688. break;
  3689. case VK_VENDOR_ID_APPLE:
  3690. device->mul_mat_l[i] = false;
  3691. device->mul_mat_m[i] = true;
  3692. device->mul_mat_s[i] = false;
  3693. device->mul_mat_id_l[i] = false;
  3694. device->mul_mat_id_m[i] = true;
  3695. device->mul_mat_id_s[i] = false;
  3696. break;
  3697. #endif
  3698. default:
  3699. device->mul_mat_l[i] = true;
  3700. device->mul_mat_m[i] = true;
  3701. device->mul_mat_s[i] = true;
  3702. device->mul_mat_id_l[i] = true;
  3703. device->mul_mat_id_m[i] = true;
  3704. device->mul_mat_id_s[i] = true;
  3705. break;
  3706. }
  3707. }
  3708. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  3709. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  3710. for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
  3711. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  3712. dsl_binding_flags.push_back({});
  3713. }
  3714. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  3715. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  3716. {},
  3717. dsl_binding);
  3718. descriptor_set_layout_create_info.setPNext(&dslbfci);
  3719. device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  3720. ggml_vk_load_shaders(device);
  3721. if (!device->single_queue) {
  3722. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  3723. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  3724. } else {
  3725. // TODO: Use pointer or reference to avoid copy
  3726. device->transfer_queue.copyFrom(device->compute_queue);
  3727. device->transfer_queue.cmd_pool.init(device, &device->transfer_queue);
  3728. }
  3729. device->buffer_type = {
  3730. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  3731. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  3732. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  3733. };
  3734. device->fence = device->device.createFence({});
  3735. device->idx = idx;
  3736. device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr;
  3737. device->add_rms_fusion = !device->disable_fusion &&
  3738. device->subgroup_arithmetic &&
  3739. device->vendor_id != VK_VENDOR_ID_INTEL;
  3740. device->partials_binding_alignment =
  3741. std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment);
  3742. device->mmvq_mode = 0;
  3743. if (getenv("GGML_VK_DISABLE_MMVQ")) {
  3744. device->mmvq_mode = -1;
  3745. } else if (getenv("GGML_VK_FORCE_MMVQ")) {
  3746. device->mmvq_mode = 1;
  3747. }
  3748. return device;
  3749. }
  3750. return vk_instance.devices[idx];
  3751. }
  3752. static void ggml_vk_print_gpu_info(size_t idx) {
  3753. GGML_ASSERT(idx < vk_instance.device_indices.size());
  3754. size_t dev_num = vk_instance.device_indices[idx];
  3755. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  3756. GGML_ASSERT(vk_instance_initialized);
  3757. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  3758. if (dev_num >= devices.size()) {
  3759. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3760. throw std::runtime_error("Device not found");
  3761. }
  3762. vk::PhysicalDevice physical_device = devices[dev_num];
  3763. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  3764. bool fp16_storage = false;
  3765. bool fp16_compute = false;
  3766. bool coopmat_support = false;
  3767. bool coopmat2_support = false;
  3768. bool integer_dot_product = false;
  3769. bool bfloat16_support = false;
  3770. for (auto properties : ext_props) {
  3771. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3772. fp16_storage = true;
  3773. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3774. fp16_compute = true;
  3775. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3776. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3777. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3778. coopmat_support = true;
  3779. #endif
  3780. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3781. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3782. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3783. coopmat2_support = true;
  3784. #endif
  3785. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3786. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3787. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3788. integer_dot_product = true;
  3789. #endif
  3790. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3791. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3792. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3793. bfloat16_support = true;
  3794. #endif
  3795. }
  3796. }
  3797. const vk_device_architecture device_architecture = get_device_architecture(physical_device);
  3798. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  3799. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  3800. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  3801. vk::PhysicalDeviceProperties2 props2;
  3802. vk::PhysicalDeviceMaintenance3Properties props3;
  3803. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3804. vk::PhysicalDeviceDriverProperties driver_props;
  3805. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3806. props2.pNext = &props3;
  3807. props3.pNext = &subgroup_props;
  3808. subgroup_props.pNext = &driver_props;
  3809. // Pointer to the last chain element
  3810. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  3811. if (integer_dot_product) {
  3812. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3813. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3814. }
  3815. physical_device.getProperties2(&props2);
  3816. VkPhysicalDeviceFeatures2 device_features2;
  3817. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  3818. device_features2.pNext = nullptr;
  3819. VkPhysicalDeviceVulkan11Features vk11_features;
  3820. vk11_features.pNext = nullptr;
  3821. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  3822. device_features2.pNext = &vk11_features;
  3823. VkPhysicalDeviceVulkan12Features vk12_features;
  3824. vk12_features.pNext = nullptr;
  3825. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  3826. vk11_features.pNext = &vk12_features;
  3827. // Pointer to the last chain element
  3828. last_struct = (VkBaseOutStructure *)&vk12_features;
  3829. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3830. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  3831. coopmat_features.pNext = nullptr;
  3832. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  3833. coopmat_features.cooperativeMatrix = VK_FALSE;
  3834. if (coopmat_support) {
  3835. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  3836. last_struct = (VkBaseOutStructure *)&coopmat_features;
  3837. }
  3838. #endif
  3839. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  3840. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  3841. if (integer_dot_product) {
  3842. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3843. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3844. }
  3845. #if defined(VK_KHR_shader_bfloat16)
  3846. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  3847. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  3848. if (bfloat16_support) {
  3849. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  3850. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  3851. }
  3852. #endif
  3853. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  3854. fp16 = fp16 && vk12_features.shaderFloat16;
  3855. #if defined(VK_KHR_shader_bfloat16)
  3856. bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  3857. #else
  3858. bool bf16 = false;
  3859. #endif
  3860. uint32_t default_subgroup_size = get_subgroup_size("", device_architecture);
  3861. const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize;
  3862. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3863. integer_dot_product = integer_dot_product
  3864. && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated
  3865. && shader_integer_dot_product_features.shaderIntegerDotProduct;
  3866. coopmat_support = coopmat_support
  3867. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3868. && coopmat_features.cooperativeMatrix
  3869. #endif
  3870. && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture);
  3871. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  3872. std::string device_name = props2.properties.deviceName.data();
  3873. 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",
  3874. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, bf16, subgroup_size,
  3875. props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str());
  3876. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  3877. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  3878. }
  3879. }
  3880. static bool ggml_vk_instance_validation_ext_available();
  3881. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  3882. static bool ggml_vk_instance_debug_utils_ext_available(const std::vector<vk::ExtensionProperties> & instance_extensions);
  3883. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev);
  3884. static vk::detail::DispatchLoaderDynamic ggml_vk_default_dispatcher_instance;
  3885. vk::detail::DispatchLoaderDynamic & ggml_vk_default_dispatcher() {
  3886. return ggml_vk_default_dispatcher_instance;
  3887. }
  3888. static void ggml_vk_instance_init() {
  3889. if (vk_instance_initialized) {
  3890. return;
  3891. }
  3892. VK_LOG_DEBUG("ggml_vk_instance_init()");
  3893. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  3894. ggml_vk_default_dispatcher_instance.init(vkGetInstanceProcAddr);
  3895. uint32_t api_version = vk::enumerateInstanceVersion();
  3896. if (api_version < VK_API_VERSION_1_2) {
  3897. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  3898. throw vk::SystemError(vk::Result::eErrorFeatureNotPresent, "Vulkan 1.2 required");
  3899. }
  3900. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  3901. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  3902. const bool validation_ext = ggml_vk_instance_validation_ext_available();
  3903. #ifdef __APPLE__
  3904. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  3905. #endif
  3906. const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr;
  3907. std::vector<const char*> layers;
  3908. if (validation_ext) {
  3909. layers.push_back("VK_LAYER_KHRONOS_validation");
  3910. }
  3911. std::vector<const char*> extensions;
  3912. if (validation_ext) {
  3913. extensions.push_back("VK_EXT_validation_features");
  3914. }
  3915. #ifdef __APPLE__
  3916. if (portability_enumeration_ext) {
  3917. extensions.push_back("VK_KHR_portability_enumeration");
  3918. }
  3919. #endif
  3920. if (debug_utils_ext) {
  3921. extensions.push_back("VK_EXT_debug_utils");
  3922. }
  3923. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions);
  3924. #ifdef __APPLE__
  3925. if (portability_enumeration_ext) {
  3926. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  3927. }
  3928. #endif
  3929. std::vector<vk::ValidationFeatureEnableEXT> features_enable;
  3930. vk::ValidationFeaturesEXT validation_features;
  3931. if (validation_ext) {
  3932. features_enable = { vk::ValidationFeatureEnableEXT::eBestPractices };
  3933. validation_features = {
  3934. features_enable,
  3935. {},
  3936. };
  3937. validation_features.setPNext(nullptr);
  3938. instance_create_info.setPNext(&validation_features);
  3939. GGML_LOG_DEBUG("ggml_vulkan: Validation layers enabled\n");
  3940. }
  3941. vk_instance.instance = vk::createInstance(instance_create_info);
  3942. vk_instance_initialized = true;
  3943. if (debug_utils_ext) {
  3944. vk_instance.debug_utils_support = true;
  3945. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT");
  3946. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT");
  3947. vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT");
  3948. vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT");
  3949. vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT");
  3950. vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT");
  3951. }
  3952. vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr;
  3953. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  3954. VULKAN_HPP_DEFAULT_DISPATCHER.init(vk_instance.instance);
  3955. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  3956. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  3957. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  3958. if (devices_env != nullptr) {
  3959. size_t num_available_devices = devices.size();
  3960. std::string devices(devices_env);
  3961. std::replace(devices.begin(), devices.end(), ',', ' ');
  3962. std::stringstream ss(devices);
  3963. size_t tmp;
  3964. while (ss >> tmp) {
  3965. if(tmp >= num_available_devices) {
  3966. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  3967. throw std::runtime_error("Invalid Vulkan device index");
  3968. }
  3969. vk_instance.device_indices.push_back(tmp);
  3970. }
  3971. } else {
  3972. // If no vulkan devices are found, return early
  3973. if (devices.empty()) {
  3974. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  3975. return;
  3976. }
  3977. // Default to using all dedicated GPUs
  3978. for (size_t i = 0; i < devices.size(); i++) {
  3979. vk::PhysicalDeviceProperties2 new_props;
  3980. vk::PhysicalDeviceDriverProperties new_driver;
  3981. vk::PhysicalDeviceIDProperties new_id;
  3982. new_props.pNext = &new_driver;
  3983. new_driver.pNext = &new_id;
  3984. devices[i].getProperties2(&new_props);
  3985. if ((new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu || new_props.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) && ggml_vk_device_is_supported(devices[i])) {
  3986. // Check if there are two physical devices corresponding to the same GPU
  3987. auto old_device = std::find_if(
  3988. vk_instance.device_indices.begin(),
  3989. vk_instance.device_indices.end(),
  3990. [&devices, &new_id](const size_t k){
  3991. vk::PhysicalDeviceProperties2 old_props;
  3992. vk::PhysicalDeviceIDProperties old_id;
  3993. old_props.pNext = &old_id;
  3994. devices[k].getProperties2(&old_props);
  3995. return std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  3996. }
  3997. );
  3998. if (old_device == vk_instance.device_indices.end()) {
  3999. vk_instance.device_indices.push_back(i);
  4000. } else {
  4001. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  4002. // This can cause error when splitting layers aross the devices, need to keep only 1
  4003. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  4004. vk::PhysicalDeviceProperties2 old_props;
  4005. vk::PhysicalDeviceDriverProperties old_driver;
  4006. old_props.pNext = &old_driver;
  4007. devices[*old_device].getProperties2(&old_props);
  4008. std::map<vk::DriverId, int> driver_priorities {};
  4009. int old_priority = std::numeric_limits<int>::max();
  4010. int new_priority = std::numeric_limits<int>::max();
  4011. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  4012. // Smaller number -> higher priority
  4013. switch (old_props.properties.vendorID) {
  4014. case VK_VENDOR_ID_AMD:
  4015. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  4016. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  4017. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  4018. break;
  4019. case VK_VENDOR_ID_INTEL:
  4020. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  4021. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  4022. break;
  4023. case VK_VENDOR_ID_NVIDIA:
  4024. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  4025. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  4026. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  4027. #endif
  4028. break;
  4029. }
  4030. if (driver_priorities.count(old_driver.driverID)) {
  4031. old_priority = driver_priorities[old_driver.driverID];
  4032. }
  4033. if (driver_priorities.count(new_driver.driverID)) {
  4034. new_priority = driver_priorities[new_driver.driverID];
  4035. }
  4036. if (new_priority < old_priority) {
  4037. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  4038. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  4039. vk_instance.device_indices.push_back(i);
  4040. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  4041. }
  4042. else {
  4043. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  4044. }
  4045. }
  4046. }
  4047. }
  4048. // If no GPUs found, fall back to the first non-CPU device.
  4049. // If only CPU devices are available, return without devices.
  4050. if (vk_instance.device_indices.empty()) {
  4051. for (size_t i = 0; i < devices.size(); i++) {
  4052. if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) {
  4053. vk_instance.device_indices.push_back(i);
  4054. break;
  4055. }
  4056. }
  4057. }
  4058. if (vk_instance.device_indices.empty()) {
  4059. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4060. return;
  4061. }
  4062. }
  4063. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  4064. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  4065. vk::PhysicalDevice vkdev = devices[vk_instance.device_indices[i]];
  4066. std::vector<vk::ExtensionProperties> extensionprops = vkdev.enumerateDeviceExtensionProperties();
  4067. bool membudget_supported = false;
  4068. for (const auto & ext : extensionprops) {
  4069. if (strcmp(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, ext.extensionName) == 0) {
  4070. membudget_supported = true;
  4071. break;
  4072. }
  4073. }
  4074. vk_instance.device_supports_membudget.push_back(membudget_supported);
  4075. ggml_vk_print_gpu_info(i);
  4076. }
  4077. }
  4078. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  4079. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  4080. ggml_vk_instance_init();
  4081. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4082. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4083. ctx->device = ggml_vk_get_device(idx);
  4084. ctx->semaphore_idx = 0;
  4085. ctx->event_idx = 0;
  4086. ctx->prealloc_size_x = 0;
  4087. ctx->prealloc_size_y = 0;
  4088. ctx->prealloc_size_split_k = 0;
  4089. ctx->fence = ctx->device->device.createFence({});
  4090. ctx->almost_ready_fence = ctx->device->device.createFence({});
  4091. ctx->compute_cmd_pool.init(ctx->device, &ctx->device->compute_queue);
  4092. ctx->transfer_cmd_pool.init(ctx->device, &ctx->device->transfer_queue);
  4093. #ifdef GGML_VULKAN_CHECK_RESULTS
  4094. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  4095. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  4096. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  4097. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  4098. #endif
  4099. }
  4100. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  4101. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  4102. switch (type) {
  4103. case GGML_TYPE_F32:
  4104. case GGML_TYPE_Q4_0:
  4105. case GGML_TYPE_Q4_1:
  4106. case GGML_TYPE_Q5_0:
  4107. case GGML_TYPE_Q5_1:
  4108. case GGML_TYPE_Q8_0:
  4109. case GGML_TYPE_Q2_K:
  4110. case GGML_TYPE_Q3_K:
  4111. case GGML_TYPE_Q4_K:
  4112. case GGML_TYPE_Q5_K:
  4113. case GGML_TYPE_Q6_K:
  4114. case GGML_TYPE_IQ1_S:
  4115. case GGML_TYPE_IQ1_M:
  4116. case GGML_TYPE_IQ2_XXS:
  4117. case GGML_TYPE_IQ2_XS:
  4118. case GGML_TYPE_IQ2_S:
  4119. case GGML_TYPE_IQ3_XXS:
  4120. case GGML_TYPE_IQ3_S:
  4121. case GGML_TYPE_IQ4_XS:
  4122. case GGML_TYPE_IQ4_NL:
  4123. case GGML_TYPE_MXFP4:
  4124. break;
  4125. default:
  4126. return nullptr;
  4127. }
  4128. return ctx->device->pipeline_dequant[type];
  4129. }
  4130. 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) {
  4131. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ", " << prec << ")");
  4132. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4133. return ctx->device->pipeline_matmul_f32;
  4134. }
  4135. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4136. return ctx->device->pipeline_matmul_f32_f16;
  4137. }
  4138. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4139. return ctx->device->pipeline_matmul_bf16;
  4140. }
  4141. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4142. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4143. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  4144. }
  4145. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4146. return ctx->device->pipeline_matmul_f16.f16acc;
  4147. }
  4148. } else {
  4149. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4150. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  4151. }
  4152. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4153. return ctx->device->pipeline_matmul_f16.f32acc;
  4154. }
  4155. }
  4156. // MMQ
  4157. if (src1_type == GGML_TYPE_Q8_1) {
  4158. 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;
  4159. if (pipelines->s == nullptr && pipelines->m == nullptr && pipelines->l == nullptr) {
  4160. return nullptr;
  4161. }
  4162. return pipelines;
  4163. }
  4164. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  4165. return nullptr;
  4166. }
  4167. switch (src0_type) {
  4168. case GGML_TYPE_Q4_0:
  4169. case GGML_TYPE_Q4_1:
  4170. case GGML_TYPE_Q5_0:
  4171. case GGML_TYPE_Q5_1:
  4172. case GGML_TYPE_Q8_0:
  4173. case GGML_TYPE_Q2_K:
  4174. case GGML_TYPE_Q3_K:
  4175. case GGML_TYPE_Q4_K:
  4176. case GGML_TYPE_Q5_K:
  4177. case GGML_TYPE_Q6_K:
  4178. case GGML_TYPE_IQ1_S:
  4179. case GGML_TYPE_IQ1_M:
  4180. case GGML_TYPE_IQ2_XXS:
  4181. case GGML_TYPE_IQ2_XS:
  4182. case GGML_TYPE_IQ2_S:
  4183. case GGML_TYPE_IQ3_XXS:
  4184. case GGML_TYPE_IQ3_S:
  4185. case GGML_TYPE_IQ4_XS:
  4186. case GGML_TYPE_IQ4_NL:
  4187. case GGML_TYPE_MXFP4:
  4188. break;
  4189. default:
  4190. return nullptr;
  4191. }
  4192. if (ctx->device->coopmat2) {
  4193. assert(src1_type == GGML_TYPE_F16);
  4194. 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;
  4195. }
  4196. if (ctx->device->coopmat_support) {
  4197. 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;
  4198. }
  4199. 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;
  4200. }
  4201. 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) {
  4202. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  4203. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1);
  4204. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  4205. if (b_type == GGML_TYPE_Q8_1) {
  4206. switch (a_type) {
  4207. case GGML_TYPE_Q4_0:
  4208. case GGML_TYPE_Q4_1:
  4209. case GGML_TYPE_Q5_0:
  4210. case GGML_TYPE_Q5_1:
  4211. case GGML_TYPE_Q8_0:
  4212. break;
  4213. default:
  4214. return nullptr;
  4215. }
  4216. }
  4217. switch (a_type) {
  4218. case GGML_TYPE_F32:
  4219. case GGML_TYPE_F16:
  4220. case GGML_TYPE_BF16:
  4221. case GGML_TYPE_Q4_0:
  4222. case GGML_TYPE_Q4_1:
  4223. case GGML_TYPE_Q5_0:
  4224. case GGML_TYPE_Q5_1:
  4225. case GGML_TYPE_Q8_0:
  4226. case GGML_TYPE_Q2_K:
  4227. case GGML_TYPE_Q3_K:
  4228. case GGML_TYPE_Q4_K:
  4229. case GGML_TYPE_Q5_K:
  4230. case GGML_TYPE_Q6_K:
  4231. case GGML_TYPE_IQ1_S:
  4232. case GGML_TYPE_IQ1_M:
  4233. case GGML_TYPE_IQ2_XXS:
  4234. case GGML_TYPE_IQ2_XS:
  4235. case GGML_TYPE_IQ2_S:
  4236. case GGML_TYPE_IQ3_XXS:
  4237. case GGML_TYPE_IQ3_S:
  4238. case GGML_TYPE_IQ4_XS:
  4239. case GGML_TYPE_IQ4_NL:
  4240. case GGML_TYPE_MXFP4:
  4241. break;
  4242. default:
  4243. return nullptr;
  4244. }
  4245. // heuristic to choose workgroup size
  4246. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4247. 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) {
  4248. // Prefer larger workgroups when M is small, to spread the work out more
  4249. // and keep more SMs busy.
  4250. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4251. if (a_type == GGML_TYPE_Q6_K) {
  4252. if (m < 4096 && k >= 1024) {
  4253. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4254. }
  4255. } else {
  4256. if (m <= 8192 && k >= 1024) {
  4257. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4258. }
  4259. }
  4260. }
  4261. if (b_type == GGML_TYPE_Q8_1) {
  4262. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4263. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4264. }
  4265. return ctx->device->pipeline_dequant_mul_mat_vec_q8_1_f32[dmmv_wg][a_type][num_cols-1];
  4266. }
  4267. 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];
  4268. }
  4269. 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) {
  4270. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  4271. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4272. return ctx->device->pipeline_matmul_id_f32;
  4273. }
  4274. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4275. return ctx->device->pipeline_matmul_id_bf16;
  4276. }
  4277. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4278. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4279. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  4280. }
  4281. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4282. return ctx->device->pipeline_matmul_id_f16.f16acc;
  4283. }
  4284. } else {
  4285. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4286. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  4287. }
  4288. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4289. return ctx->device->pipeline_matmul_id_f16.f32acc;
  4290. }
  4291. }
  4292. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  4293. switch (src0_type) {
  4294. case GGML_TYPE_Q4_0:
  4295. case GGML_TYPE_Q4_1:
  4296. case GGML_TYPE_Q5_0:
  4297. case GGML_TYPE_Q5_1:
  4298. case GGML_TYPE_Q8_0:
  4299. case GGML_TYPE_Q2_K:
  4300. case GGML_TYPE_Q3_K:
  4301. case GGML_TYPE_Q4_K:
  4302. case GGML_TYPE_Q5_K:
  4303. case GGML_TYPE_Q6_K:
  4304. case GGML_TYPE_IQ1_S:
  4305. case GGML_TYPE_IQ1_M:
  4306. case GGML_TYPE_IQ2_XXS:
  4307. case GGML_TYPE_IQ2_XS:
  4308. case GGML_TYPE_IQ2_S:
  4309. case GGML_TYPE_IQ3_XXS:
  4310. case GGML_TYPE_IQ3_S:
  4311. case GGML_TYPE_IQ4_XS:
  4312. case GGML_TYPE_IQ4_NL:
  4313. case GGML_TYPE_MXFP4:
  4314. break;
  4315. default:
  4316. return nullptr;
  4317. }
  4318. // XXX TODO 'prec' is not actually allowed in mul_mat_id.
  4319. bool prefer_fp16acc = ctx->device->fp16 /*&& prec == GGML_PREC_DEFAULT*/;
  4320. bool support_fp16acc = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f16acc != nullptr;
  4321. bool support_fp32acc = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f32acc != nullptr;
  4322. if (support_fp16acc && (prefer_fp16acc || !support_fp32acc)) {
  4323. return ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f16acc;
  4324. } else {
  4325. GGML_ASSERT(support_fp32acc);
  4326. return ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f32acc;
  4327. }
  4328. }
  4329. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type) {
  4330. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()");
  4331. GGML_ASSERT(b_type == GGML_TYPE_F32);
  4332. switch (a_type) {
  4333. case GGML_TYPE_F32:
  4334. case GGML_TYPE_F16:
  4335. case GGML_TYPE_BF16:
  4336. case GGML_TYPE_Q4_0:
  4337. case GGML_TYPE_Q4_1:
  4338. case GGML_TYPE_Q5_0:
  4339. case GGML_TYPE_Q5_1:
  4340. case GGML_TYPE_Q8_0:
  4341. case GGML_TYPE_Q2_K:
  4342. case GGML_TYPE_Q3_K:
  4343. case GGML_TYPE_Q4_K:
  4344. case GGML_TYPE_Q5_K:
  4345. case GGML_TYPE_Q6_K:
  4346. case GGML_TYPE_IQ1_S:
  4347. case GGML_TYPE_IQ1_M:
  4348. case GGML_TYPE_IQ2_XXS:
  4349. case GGML_TYPE_IQ2_XS:
  4350. case GGML_TYPE_IQ2_S:
  4351. case GGML_TYPE_IQ3_XXS:
  4352. case GGML_TYPE_IQ3_S:
  4353. case GGML_TYPE_IQ4_XS:
  4354. case GGML_TYPE_IQ4_NL:
  4355. case GGML_TYPE_MXFP4:
  4356. break;
  4357. default:
  4358. return nullptr;
  4359. }
  4360. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[a_type];
  4361. }
  4362. static vk_buffer ggml_vk_pool_malloc(ggml_backend_vk_context * ctx, size_t size) {
  4363. VK_LOG_DEBUG("ggml_vk_pool_malloc(" << size << ")");
  4364. VK_LOG_MEMORY("ggml_vk_pool_malloc");
  4365. int best_i = -1;
  4366. size_t best_size = std::numeric_limits<size_t>::max(); //smallest unused buffer that fits our needs
  4367. int worst_i = -1;
  4368. size_t worst_size = 0; //largest unused buffer seen so far
  4369. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  4370. vk_buffer &b = ctx->buffer_pool[i];
  4371. if (b != nullptr && b->size >= size && b->size < best_size) {
  4372. best_i = i;
  4373. best_size = b->size;
  4374. }
  4375. if (b != nullptr && b->size > worst_size) {
  4376. worst_i = i;
  4377. worst_size = b->size;
  4378. }
  4379. }
  4380. if(best_i != -1) {
  4381. //found the smallest buffer that fits our needs
  4382. vk_buffer b = ctx->buffer_pool[best_i];
  4383. ctx->buffer_pool[best_i].reset();
  4384. return b;
  4385. }
  4386. if(worst_i != -1) {
  4387. //no buffer that fits our needs, resize largest one to save memory
  4388. vk_buffer& b = ctx->buffer_pool[worst_i];
  4389. ggml_vk_destroy_buffer(b);
  4390. }
  4391. return ggml_vk_create_buffer_device(ctx->device, size);
  4392. }
  4393. static void ggml_vk_pool_free(ggml_backend_vk_context * ctx, vk_buffer& buffer) {
  4394. VK_LOG_DEBUG("ggml_vk_pool_free(" << buffer->size << ")");
  4395. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  4396. vk_buffer& b = ctx->buffer_pool[i];
  4397. if (b == nullptr) {
  4398. b = buffer;
  4399. return;
  4400. }
  4401. }
  4402. std::cerr << "ggml_vulkan: WARNING: vk buffer pool full, increase MAX_VK_BUFFERS" << std::endl;
  4403. ggml_vk_destroy_buffer(buffer);
  4404. }
  4405. // Returns an available temporary buffer that may only be used temporarily, it will be reused
  4406. static vk_buffer ggml_vk_create_buffer_temp(ggml_backend_vk_context * ctx, size_t size) {
  4407. // Try to find existing temp buffer with enough capacity
  4408. for (auto& buffer : ctx->gc.temp_buffers) {
  4409. if (buffer->size >= size) {
  4410. return buffer;
  4411. }
  4412. }
  4413. VK_LOG_MEMORY("ggml_vk_create_buffer_temp(" << size << ")");
  4414. // Otherwise create new buffer
  4415. vk_buffer buf = ggml_vk_pool_malloc(ctx, size);
  4416. ctx->gc.temp_buffers.push_back(buf);
  4417. return buf;
  4418. }
  4419. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  4420. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  4421. vk_buffer buf = ggml_vk_create_buffer(device, size,
  4422. {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4423. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  4424. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  4425. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  4426. size/1024.0/1024.0);
  4427. device->device.freeMemory(buf->device_memory);
  4428. device->device.destroyBuffer(buf->buffer);
  4429. return nullptr;
  4430. }
  4431. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4432. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  4433. return buf->ptr;
  4434. }
  4435. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  4436. if (ptr == nullptr) {
  4437. return;
  4438. }
  4439. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  4440. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4441. vk_buffer buf;
  4442. size_t index;
  4443. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4444. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4445. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4446. if (ptr >= addr && ptr < endr) {
  4447. buf = std::get<2>(device->pinned_memory[i]);
  4448. index = i;
  4449. break;
  4450. }
  4451. }
  4452. if (buf == nullptr) {
  4453. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  4454. return;
  4455. }
  4456. ggml_vk_destroy_buffer(buf);
  4457. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  4458. }
  4459. static void ggml_vk_host_get(vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  4460. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4461. buf = nullptr;
  4462. buf_offset = 0;
  4463. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4464. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4465. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4466. if (ptr >= addr && ptr < endr) {
  4467. buf = std::get<2>(device->pinned_memory[i]);
  4468. buf_offset = ((const uint8_t *)ptr) - addr;
  4469. break;
  4470. }
  4471. }
  4472. }
  4473. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) {
  4474. vk_submission s;
  4475. s.buffer = ggml_vk_create_cmd_buffer(device, p);
  4476. if (one_time) {
  4477. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  4478. } else {
  4479. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  4480. }
  4481. return s;
  4482. }
  4483. template <typename T> size_t push_constant_size(const T &t) {
  4484. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4485. GGML_UNUSED(t);
  4486. return sizeof(T);
  4487. }
  4488. template <typename T> size_t push_constant_size(const std::vector<T> &t) {
  4489. GGML_UNUSED(t);
  4490. return sizeof(T) * t.size();
  4491. }
  4492. template <typename T, uint32_t N> size_t push_constant_size(const std::array<T, N> &t) {
  4493. GGML_UNUSED(t);
  4494. return sizeof(T) * N;
  4495. }
  4496. template <typename T> const T *push_constant_data(const T &t) {
  4497. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4498. return &t;
  4499. }
  4500. template <typename T> const T *push_constant_data(const std::vector<T> &t) {
  4501. return t.data();
  4502. }
  4503. template <typename T, uint32_t N> const T *push_constant_data(const std::array<T, N> &t) {
  4504. return t.data();
  4505. }
  4506. template <typename T>
  4507. 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) {
  4508. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  4509. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  4510. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  4511. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  4512. for (auto& buffer : descriptor_buffer_infos) {
  4513. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  4514. }
  4515. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  4516. GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size());
  4517. GGML_ASSERT(descriptor_buffer_infos.size() <= MAX_PARAMETER_COUNT);
  4518. GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size());
  4519. vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[ctx->descriptor_set_idx++];
  4520. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  4521. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  4522. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size(push_constants), push_constant_data(push_constants));
  4523. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  4524. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  4525. pipeline->layout,
  4526. 0,
  4527. { descriptor_set },
  4528. {});
  4529. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  4530. }
  4531. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  4532. s.buffer.end();
  4533. s.wait_semaphores = std::move(wait_semaphores);
  4534. s.signal_semaphores = std::move(signal_semaphores);
  4535. }
  4536. static void ggml_vk_ctx_end(vk_context& ctx) {
  4537. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  4538. if (ctx->s == nullptr) {
  4539. return;
  4540. }
  4541. ctx->s->buffer.end();
  4542. ctx->s = nullptr;
  4543. }
  4544. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  4545. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  4546. if (subctx->s != nullptr) {
  4547. ggml_vk_ctx_end(subctx);
  4548. }
  4549. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) });
  4550. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  4551. }
  4552. static size_t ggml_vk_align_size(size_t width, size_t align) {
  4553. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  4554. return CEIL_DIV(width, align) * align;
  4555. }
  4556. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  4557. if (memcpys == nullptr) {
  4558. memcpy(dst, src, size);
  4559. } else {
  4560. memcpys->emplace_back(dst, src, size);
  4561. }
  4562. }
  4563. static void deferred_memset(void * dst, uint32_t val, size_t size, std::vector<vk_staging_memset>* memsets = nullptr) {
  4564. if (memsets == nullptr) {
  4565. memset(dst, val, size);
  4566. } else {
  4567. memsets->emplace_back(dst, val, size);
  4568. }
  4569. }
  4570. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  4571. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  4572. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  4573. ggml_vk_destroy_buffer(device->sync_staging);
  4574. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  4575. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4576. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  4577. }
  4578. }
  4579. 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) {
  4580. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  4581. GGML_ASSERT(!ggml_is_contiguous(tensor));
  4582. // Buffer is already mapped
  4583. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4584. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4585. GGML_ABORT("fatal error");
  4586. }
  4587. // Check if src is pinned memory
  4588. vk_buffer buf = nullptr;
  4589. size_t buf_offset = 0;
  4590. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  4591. const uint64_t ne0 = tensor->ne[0];
  4592. const uint64_t ne1 = tensor->ne[1];
  4593. const uint64_t ne2 = tensor->ne[2];
  4594. const uint64_t ne3 = tensor->ne[3];
  4595. const uint64_t nb0 = tensor->nb[0];
  4596. const uint64_t nb1 = tensor->nb[1];
  4597. const uint64_t nb2 = tensor->nb[2];
  4598. const uint64_t nb3 = tensor->nb[3];
  4599. const ggml_type type = tensor->type;
  4600. const uint64_t ts = ggml_type_size(type);
  4601. const uint64_t bs = ggml_blck_size(type);
  4602. const uint64_t dstnb0 = ts;
  4603. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  4604. const uint64_t dstnb2 = dstnb1*ne1;
  4605. const uint64_t dstnb3 = dstnb2*ne2;
  4606. const uint64_t ne = ggml_nelements(tensor);
  4607. if (buf != nullptr) {
  4608. // Memory is pinned, use as staging buffer
  4609. std::vector<vk::BufferCopy> slices;
  4610. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4611. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4612. // Find longest contiguous slice
  4613. if (ne1*nb1 == dstnb2) {
  4614. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  4615. } else {
  4616. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4617. if (ne0*nb0/bs == dstnb1) {
  4618. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  4619. } else {
  4620. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4621. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4622. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4623. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  4624. }
  4625. }
  4626. }
  4627. }
  4628. }
  4629. }
  4630. ggml_vk_sync_buffers(ctx, subctx);
  4631. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  4632. return;
  4633. }
  4634. if (!sync_staging) {
  4635. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  4636. }
  4637. // Staging buffer required
  4638. vk_buffer& staging = ctx->device->sync_staging;
  4639. const uint64_t copy_size = ts*ne/bs;
  4640. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  4641. VkBufferCopy buf_copy{ 0, offset, copy_size };
  4642. ggml_vk_sync_buffers(ctx, subctx);
  4643. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  4644. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4645. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4646. // Find longest contiguous slice
  4647. if (ne1*nb1 == dstnb2) {
  4648. 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);
  4649. } else {
  4650. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4651. if (ne0*nb0/bs == dstnb1) {
  4652. 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);
  4653. } else {
  4654. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4655. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4656. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4657. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  4658. }
  4659. }
  4660. }
  4661. }
  4662. }
  4663. }
  4664. }
  4665. 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) {
  4666. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  4667. // Buffer is already mapped
  4668. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4669. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4670. GGML_ABORT("fatal error");
  4671. }
  4672. // Check if src is pinned memory
  4673. vk_buffer buf = nullptr;
  4674. size_t buf_offset = 0;
  4675. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  4676. if (buf != nullptr) {
  4677. // Memory is pinned, use as staging buffer
  4678. std::vector<vk::BufferCopy> slices(1);
  4679. if (width == spitch) {
  4680. // Only do single write if stride is equal
  4681. slices[0].srcOffset = buf_offset;
  4682. slices[0].dstOffset = offset;
  4683. slices[0].size = width * height;
  4684. } else {
  4685. slices.resize(height);
  4686. for (size_t i = 0; i < height; i++) {
  4687. slices[i].srcOffset = buf_offset + i * spitch;
  4688. slices[i].dstOffset = offset + i * width;
  4689. slices[i].size = width;
  4690. }
  4691. }
  4692. ggml_vk_sync_buffers(nullptr, subctx);
  4693. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  4694. return;
  4695. }
  4696. VK_LOG_DEBUG("STAGING");
  4697. if (!sync_staging) {
  4698. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  4699. }
  4700. // Staging buffer required
  4701. const size_t copy_size = width*height;
  4702. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  4703. vk_buffer& staging_buffer = dst->device->sync_staging;
  4704. VkBufferCopy buf_copy = {
  4705. 0,
  4706. offset,
  4707. copy_size};
  4708. ggml_vk_sync_buffers(nullptr, subctx);
  4709. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  4710. if (width == spitch) {
  4711. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  4712. } else {
  4713. for (size_t i = 0; i < height; i++) {
  4714. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  4715. }
  4716. }
  4717. }
  4718. 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) {
  4719. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  4720. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  4721. }
  4722. 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) {
  4723. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  4724. // Buffer is already mapped
  4725. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4726. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  4727. for (size_t i = 0; i < height; i++) {
  4728. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  4729. }
  4730. } else {
  4731. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  4732. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  4733. ggml_vk_ctx_begin(dst->device, subctx);
  4734. ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  4735. ggml_vk_ctx_end(subctx);
  4736. for (auto& cpy : subctx->in_memcpys) {
  4737. memcpy(cpy.dst, cpy.src, cpy.n);
  4738. }
  4739. for (auto& mset : subctx->memsets) {
  4740. memset(mset.dst, mset.val, mset.n);
  4741. }
  4742. ggml_vk_submit(subctx, dst->device->fence);
  4743. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  4744. dst->device->device.resetFences({ dst->device->fence });
  4745. ggml_vk_queue_command_pools_cleanup(dst->device);
  4746. }
  4747. }
  4748. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  4749. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  4750. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  4751. }
  4752. 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) {
  4753. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  4754. GGML_ASSERT(width > 0);
  4755. GGML_ASSERT(height > 0);
  4756. GGML_ASSERT(src != nullptr);
  4757. // TODO: staging_offset is not used
  4758. // Check if dst is pinned memory
  4759. vk_buffer buf = nullptr;
  4760. size_t buf_offset = 0;
  4761. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  4762. std::vector<vk::BufferCopy> slices(1);
  4763. if (width == spitch && width == dpitch) {
  4764. // Only do single write if stride is equal
  4765. slices[0].srcOffset = offset;
  4766. slices[0].dstOffset = buf_offset;
  4767. slices[0].size = width * height;
  4768. } else {
  4769. slices.resize(height);
  4770. for (size_t i = 0; i < height; i++) {
  4771. slices[i].srcOffset = offset + i * spitch;
  4772. slices[i].dstOffset = buf_offset + i * dpitch;
  4773. slices[i].size = width;
  4774. }
  4775. }
  4776. if (buf != nullptr) {
  4777. // Memory is pinned, use as staging buffer
  4778. ggml_vk_sync_buffers(nullptr, subctx);
  4779. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  4780. return;
  4781. }
  4782. VK_LOG_DEBUG("STAGING");
  4783. if (!sync_staging) {
  4784. GGML_ABORT("Asynchronous read from non-pinned memory not supported");
  4785. }
  4786. // Fall back to staging buffer
  4787. const size_t copy_size = dpitch * height;
  4788. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  4789. vk_buffer& staging_buffer = src->device->sync_staging;
  4790. ggml_vk_sync_buffers(nullptr, subctx);
  4791. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  4792. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  4793. }
  4794. 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) {
  4795. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  4796. }
  4797. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  4798. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  4799. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  4800. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  4801. // the HW device to host copy path.
  4802. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  4803. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  4804. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  4805. } else {
  4806. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  4807. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  4808. ggml_vk_ctx_begin(src->device, subctx);
  4809. ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  4810. ggml_vk_ctx_end(subctx);
  4811. ggml_vk_submit(subctx, src->device->fence);
  4812. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  4813. src->device->device.resetFences({ src->device->fence });
  4814. ggml_vk_queue_command_pools_cleanup(src->device);
  4815. for (auto& cpy : subctx->out_memcpys) {
  4816. memcpy(cpy.dst, cpy.src, cpy.n);
  4817. }
  4818. }
  4819. }
  4820. 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) {
  4821. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  4822. // Make sure both buffers are on same device
  4823. GGML_ASSERT(src->device == dst->device);
  4824. VkBufferCopy bc{ src_offset, dst_offset, size };
  4825. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  4826. }
  4827. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  4828. if (src->device == dst->device) {
  4829. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  4830. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  4831. // Copy within the device
  4832. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  4833. ggml_vk_ctx_begin(src->device, subctx);
  4834. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  4835. ggml_vk_ctx_end(subctx);
  4836. ggml_vk_submit(subctx, src->device->fence);
  4837. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  4838. src->device->device.resetFences({ src->device->fence });
  4839. ggml_vk_queue_command_pools_cleanup(src->device);
  4840. } else {
  4841. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  4842. // Copy device to device
  4843. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  4844. ggml_vk_ensure_sync_staging_buffer(dst->device, size);
  4845. // Copy to src staging buffer
  4846. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  4847. // memcpy to dst staging buffer
  4848. memcpy(dst->device->sync_staging->ptr, src->device->sync_staging->ptr, size);
  4849. // Copy to dst buffer
  4850. ggml_vk_buffer_copy(dst, dst_offset, dst->device->sync_staging, 0, size);
  4851. }
  4852. }
  4853. static void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  4854. VK_LOG_DEBUG("ggml_vk_buffer_memset_async(" << offset << ", " << c << ", " << size << ")");
  4855. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  4856. dst->device->uma) {
  4857. deferred_memset((uint8_t*)dst->ptr + offset, c, size, &ctx->memsets);
  4858. return;
  4859. }
  4860. // Fall back to GPU fillBuffer for non-UMA or non-host-visible buffers
  4861. ctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  4862. }
  4863. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  4864. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  4865. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  4866. dst->device->uma) {
  4867. memset((uint8_t*)dst->ptr + offset, c, size);
  4868. return;
  4869. }
  4870. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  4871. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  4872. ggml_vk_ctx_begin(dst->device, subctx);
  4873. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  4874. ggml_vk_ctx_end(subctx);
  4875. ggml_vk_submit(subctx, dst->device->fence);
  4876. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  4877. dst->device->device.resetFences({ dst->device->fence });
  4878. ggml_vk_queue_command_pools_cleanup(dst->device);
  4879. }
  4880. static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, uint32_t m, uint32_t n, uint32_t k, bool disable_split_k, const vk_pipeline& pipeline) {
  4881. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ", " << disable_split_k << ")");
  4882. if (disable_split_k) {
  4883. return 1;
  4884. }
  4885. uint32_t split_k = 1;
  4886. if (ctx->device->shader_core_count != 0 && m >= pipeline->wg_denoms[0] && n >= pipeline->wg_denoms[1]) {
  4887. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  4888. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  4889. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  4890. if (k >= 2048) {
  4891. if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) {
  4892. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  4893. } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) {
  4894. split_k = 3;
  4895. }
  4896. // Cap the split at 8x. Unless k is huge this is a lot of overhead.
  4897. split_k = std::min(split_k, 8u);
  4898. // ggml_vk_matmul will align the splits to be a multiple of 256.
  4899. // If this rounded up size would cause the last split to be empty,
  4900. // then reduce the split count.
  4901. while (true) {
  4902. if (split_k == 1) {
  4903. break;
  4904. }
  4905. uint32_t k_split = CEIL_DIV(k, split_k);
  4906. k_split = ROUNDUP_POW2(k_split, 256);
  4907. if (k_split * (split_k - 1) < k) {
  4908. break;
  4909. }
  4910. split_k--;
  4911. }
  4912. }
  4913. }
  4914. return split_k;
  4915. }
  4916. 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) {
  4917. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  4918. if (ctx->device->coopmat2) {
  4919. const uint32_t shader_core_count = ctx->device->shader_core_count;
  4920. const uint32_t tiles_l = CEIL_DIV(m, mmp->a_l->wg_denoms[0]) * CEIL_DIV(n, mmp->a_l->wg_denoms[1]);
  4921. const uint32_t tiles_m = CEIL_DIV(m, mmp->a_m->wg_denoms[0]) * CEIL_DIV(n, mmp->a_m->wg_denoms[1]);
  4922. // Use large shader when the N dimension is greater than the medium shader's tile size
  4923. uint32_t crossover_large = mmp->m->wg_denoms[1];
  4924. // Prefer large over medium if either:
  4925. // - medium or large tiles would overfill the GPU
  4926. // - large tiles with a split_k==3 fits in the GPU and medium tiles with split_k==2 does not
  4927. // (medium with split_k==2 is probably better if it fits - more workgroups running and less split_k overhead)
  4928. bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count ||
  4929. // split_k==3 with large tiles likely better than medium tiles with no split_k.
  4930. (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2);
  4931. 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])) {
  4932. return aligned ? mmp->a_l : mmp->l;
  4933. }
  4934. // Use medium shader when the N dimension is greater than the small shader's tile size
  4935. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  4936. if ((ctx->device->mul_mat_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_s[src0_type]) {
  4937. return aligned ? mmp->a_m : mmp->m;
  4938. }
  4939. return aligned ? mmp->a_s : mmp->s;
  4940. }
  4941. 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])) {
  4942. return aligned ? mmp->a_s : mmp->s;
  4943. }
  4944. if ((ctx->device->mul_mat_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l[src0_type]) {
  4945. return aligned ? mmp->a_m : mmp->m;
  4946. }
  4947. return aligned ? mmp->a_l : mmp->l;
  4948. GGML_UNUSED(src1_type);
  4949. }
  4950. 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) {
  4951. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  4952. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, src0_type, src1_type)->align;
  4953. }
  4954. static void ggml_vk_matmul(
  4955. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  4956. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  4957. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  4958. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  4959. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3,
  4960. uint32_t padded_n) {
  4961. 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 << ")");
  4962. if (split_k == 1) {
  4963. 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 };
  4964. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc, { m, n, batch });
  4965. return;
  4966. }
  4967. if (ctx->prealloc_split_k_need_sync) {
  4968. ggml_vk_sync_buffers(ctx, subctx);
  4969. }
  4970. GGML_ASSERT(batch_stride_d == m * n);
  4971. // Round the split size up to a multiple of 256 (k-quant alignment)
  4972. uint32_t k_split = CEIL_DIV(k, split_k);
  4973. k_split = ROUNDUP_POW2(k_split, 256);
  4974. 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 };
  4975. // Make sure enough workgroups get assigned for split k to work
  4976. 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 });
  4977. ggml_vk_sync_buffers(ctx, subctx);
  4978. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  4979. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 });
  4980. ctx->prealloc_split_k_need_sync = true;
  4981. }
  4982. 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) {
  4983. VK_LOG_DEBUG("ggml_vk_guess_matmul_id_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ")");
  4984. if (ctx->device->coopmat2) {
  4985. // Use large shader when the N dimension is greater than the medium shader's tile size
  4986. uint32_t crossover_large = mmp->m->wg_denoms[1];
  4987. 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])) {
  4988. return aligned ? mmp->a_l : mmp->l;
  4989. }
  4990. // Use medium shader when the N dimension is greater than the small shader's tile size
  4991. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  4992. if ((ctx->device->mul_mat_id_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_id_s[src0_type]) {
  4993. return aligned ? mmp->a_m : mmp->m;
  4994. }
  4995. return aligned ? mmp->a_s : mmp->s;
  4996. }
  4997. 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])) {
  4998. return aligned ? mmp->a_s : mmp->s;
  4999. }
  5000. if ((ctx->device->mul_mat_id_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l[src0_type]) {
  5001. return aligned ? mmp->a_m : mmp->m;
  5002. }
  5003. return aligned ? mmp->a_l : mmp->l;
  5004. }
  5005. 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) {
  5006. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ")");
  5007. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true, src0_type)->align;
  5008. }
  5009. static void ggml_vk_matmul_id(
  5010. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5011. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  5012. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5013. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5014. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11,
  5015. uint32_t padded_n) {
  5016. 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 << "), " <<
  5017. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  5018. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  5019. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  5020. 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,
  5021. nei0, nei1, nbi1, ne11, padded_n };
  5022. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, pc, { m, nei1, n_as });
  5023. }
  5024. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  5025. return
  5026. tensor->nb[0] == ggml_type_size(tensor->type) &&
  5027. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  5028. (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]);
  5029. }
  5030. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  5031. // Choose "contiguous copy" shader if src/dst are contiguous
  5032. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  5033. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  5034. if (contig) {
  5035. return ctx->device->pipeline_contig_cpy_f32_f32;
  5036. } else {
  5037. return ctx->device->pipeline_cpy_f32_f32;
  5038. }
  5039. }
  5040. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  5041. if (contig) {
  5042. return ctx->device->pipeline_contig_cpy_f32_f16;
  5043. } else {
  5044. return ctx->device->pipeline_cpy_f32_f16;
  5045. }
  5046. }
  5047. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  5048. if (contig) {
  5049. return ctx->device->pipeline_contig_cpy_f16_f16;
  5050. } else {
  5051. return ctx->device->pipeline_cpy_f16_f16;
  5052. }
  5053. }
  5054. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) {
  5055. if (contig) {
  5056. return ctx->device->pipeline_contig_cpy_f16_f32;
  5057. } else {
  5058. return ctx->device->pipeline_cpy_f16_f32;
  5059. }
  5060. }
  5061. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) {
  5062. if (contig) {
  5063. return ctx->device->pipeline_contig_cpy_f32_bf16;
  5064. } else {
  5065. return ctx->device->pipeline_cpy_f32_bf16;
  5066. }
  5067. }
  5068. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
  5069. if (contig) {
  5070. return ctx->device->pipeline_contig_cpy_f32_i32;
  5071. } else {
  5072. return ctx->device->pipeline_cpy_f32_i32;
  5073. }
  5074. }
  5075. if (src->type == GGML_TYPE_I32 && to == GGML_TYPE_F32) {
  5076. if (contig) {
  5077. return ctx->device->pipeline_contig_cpy_i32_f32;
  5078. } else {
  5079. return ctx->device->pipeline_cpy_i32_f32;
  5080. }
  5081. }
  5082. if (src->type == GGML_TYPE_F32) {
  5083. switch (to) {
  5084. case GGML_TYPE_Q4_0:
  5085. case GGML_TYPE_Q4_1:
  5086. case GGML_TYPE_Q5_0:
  5087. case GGML_TYPE_Q5_1:
  5088. case GGML_TYPE_Q8_0:
  5089. case GGML_TYPE_IQ4_NL:
  5090. return ctx->device->pipeline_cpy_f32_quant[to];
  5091. default:
  5092. break;
  5093. }
  5094. }
  5095. if (to == GGML_TYPE_F32) {
  5096. switch (src->type) {
  5097. case GGML_TYPE_Q4_0:
  5098. case GGML_TYPE_Q4_1:
  5099. case GGML_TYPE_Q5_0:
  5100. case GGML_TYPE_Q5_1:
  5101. case GGML_TYPE_Q8_0:
  5102. case GGML_TYPE_IQ4_NL:
  5103. return ctx->device->pipeline_cpy_quant_f32[src->type];
  5104. default:
  5105. break;
  5106. }
  5107. }
  5108. if (src->type == to) {
  5109. // Copy two or four bytes at a time, depending on block size.
  5110. // For quantized types, we scale by block size/type size. But
  5111. // this path is also used for bf16->bf16 for example, where the
  5112. // type size must be exactly 2 or 4.
  5113. GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4);
  5114. if ((ggml_type_size(src->type) % 4) == 0) {
  5115. if (contig) {
  5116. return ctx->device->pipeline_contig_cpy_f32_f32;
  5117. } else {
  5118. return ctx->device->pipeline_cpy_f32_f32;
  5119. }
  5120. } else {
  5121. if (contig) {
  5122. return ctx->device->pipeline_contig_cpy_f16_f16;
  5123. } else {
  5124. return ctx->device->pipeline_cpy_f16_f16;
  5125. }
  5126. }
  5127. }
  5128. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  5129. GGML_ABORT("fatal error");
  5130. }
  5131. 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) {
  5132. 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] << "), ";
  5133. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  5134. const int tensor_type_size = ggml_type_size(tensor->type);
  5135. const uint32_t ne = ggml_nelements(tensor);
  5136. std::array<uint32_t, 3> elements;
  5137. if (ne > 262144) {
  5138. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  5139. } else if (ne > 512) {
  5140. elements = { 512, CEIL_DIV(ne, 512), 1 };
  5141. } else {
  5142. elements = { ne, 1, 1 };
  5143. }
  5144. vk_op_unary_push_constants pc = {
  5145. (uint32_t)ne,
  5146. (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,
  5147. (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]),
  5148. 0,
  5149. 0.0f, 0.0f,
  5150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5151. };
  5152. init_pushconst_fastdiv(pc);
  5153. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements);
  5154. ggml_vk_sync_buffers(ctx, subctx);
  5155. }
  5156. static vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type, bool use_x4_blocks) {
  5157. switch(type) {
  5158. case GGML_TYPE_Q8_1:
  5159. return use_x4_blocks ? ctx->device->pipeline_quantize_q8_1_x4 : ctx->device->pipeline_quantize_q8_1;
  5160. default:
  5161. std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl;
  5162. GGML_ABORT("fatal error");
  5163. }
  5164. }
  5165. 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) {
  5166. VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")");
  5167. 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);
  5168. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, std::array<uint32_t, 1>{ne}, { ne, 1, 1 });
  5169. ggml_vk_sync_buffers(ctx, subctx);
  5170. }
  5171. static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool disable_split_k, bool dryrun = false) {
  5172. 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];
  5173. 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];
  5174. 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];
  5175. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5176. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5177. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5178. const uint64_t ne00 = src0->ne[0];
  5179. const uint64_t ne01 = src0->ne[1];
  5180. const uint64_t ne02 = src0->ne[2];
  5181. const uint64_t ne03 = src0->ne[3];
  5182. const uint64_t ne10 = src1->ne[0];
  5183. const uint64_t ne11 = src1->ne[1];
  5184. const uint64_t ne12 = src1->ne[2];
  5185. const uint64_t ne13 = src1->ne[3];
  5186. const uint64_t ne21 = dst->ne[1];
  5187. const uint32_t stride_d = dst->nb[1] / ggml_type_size(dst->type);
  5188. const uint32_t stride_batch_d = stride_d*ne21;
  5189. const uint64_t r2 = ne12 / ne02;
  5190. const uint64_t r3 = ne13 / ne03;
  5191. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5192. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5193. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5194. vk_buffer d_Qx = nullptr;
  5195. size_t qx_buf_offset = 0;
  5196. vk_buffer d_Qy = nullptr;
  5197. size_t qy_buf_offset = 0;
  5198. bool src0_uma = false;
  5199. bool src1_uma = false;
  5200. if (ctx->device->uma) {
  5201. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5202. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5203. src0_uma = d_Qx != nullptr;
  5204. src1_uma = d_Qy != nullptr;
  5205. }
  5206. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5207. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5208. !ggml_vk_dim01_contiguous(src0);
  5209. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5210. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5211. !ggml_vk_dim01_contiguous(src1);
  5212. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5213. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5214. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5215. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0;
  5216. // Check for mmq first
  5217. 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;
  5218. if (mmp == nullptr) {
  5219. // Fall back to f16 dequant mul mat
  5220. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  5221. quantize_y = false;
  5222. }
  5223. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5224. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  5225. if (qx_needs_dequant) {
  5226. // Fall back to dequant + f16 mulmat
  5227. 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]);
  5228. }
  5229. // Not implemented
  5230. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5231. 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)));
  5232. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8;
  5233. 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));
  5234. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  5235. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11;
  5236. const int x_ne = ne01 * ne00;
  5237. const int y_ne = padded_n * ne10;
  5238. const int d_ne = ne11 * ne01;
  5239. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline);
  5240. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  5241. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5242. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  5243. 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);
  5244. const uint64_t d_sz = sizeof(float) * d_ne;
  5245. vk_pipeline to_fp16_vk_0 = nullptr;
  5246. vk_pipeline to_fp16_vk_1 = nullptr;
  5247. vk_pipeline to_q8_1 = nullptr;
  5248. if (x_non_contig) {
  5249. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  5250. } else {
  5251. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  5252. }
  5253. if (y_non_contig) {
  5254. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  5255. } else {
  5256. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5257. }
  5258. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5259. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5260. if (quantize_y) {
  5261. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true);
  5262. }
  5263. if (dryrun) {
  5264. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  5265. uint64_t y_sz_upd = y_sz * ne12 * ne13;
  5266. if (quantize_y) {
  5267. y_sz_upd = CEIL_DIV(y_sz_upd, 144) * 144;
  5268. }
  5269. const uint64_t split_k_size = split_k > 1 ? d_sz * ne12 * ne13 * split_k : 0;
  5270. if (
  5271. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  5272. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size) ||
  5273. (split_k > 1 && split_k_size > ctx->device->max_memory_allocation_size)) {
  5274. GGML_ABORT("Requested preallocation size is too large");
  5275. }
  5276. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  5277. ctx->prealloc_size_x = x_sz_upd;
  5278. }
  5279. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz_upd) {
  5280. ctx->prealloc_size_y = y_sz_upd;
  5281. }
  5282. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  5283. ctx->prealloc_size_split_k = split_k_size;
  5284. }
  5285. // Request descriptor sets
  5286. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  5287. if (qx_needs_dequant) {
  5288. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5289. }
  5290. if (qy_needs_dequant) {
  5291. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5292. }
  5293. if (quantize_y) {
  5294. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5295. }
  5296. if (split_k > 1) {
  5297. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  5298. }
  5299. return;
  5300. }
  5301. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5302. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5303. GGML_ASSERT(d_D != nullptr);
  5304. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz * ne02 * ne03);
  5305. vk_buffer d_X;
  5306. uint64_t x_buf_offset = 0;
  5307. vk_buffer d_Y;
  5308. uint64_t y_buf_offset = 0;
  5309. if (!src0_uma) {
  5310. d_Qx = src0_buf_ctx->dev_buffer;
  5311. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5312. GGML_ASSERT(d_Qx != nullptr);
  5313. }
  5314. if (!src1_uma) {
  5315. d_Qy = src1_buf_ctx->dev_buffer;
  5316. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5317. GGML_ASSERT(d_Qy != nullptr);
  5318. }
  5319. if (qx_needs_dequant) {
  5320. d_X = ctx->prealloc_x;
  5321. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  5322. } else {
  5323. d_X = d_Qx;
  5324. x_buf_offset = qx_buf_offset;
  5325. GGML_ASSERT(qx_sz == x_sz);
  5326. }
  5327. if (qy_needs_dequant) {
  5328. d_Y = ctx->prealloc_y;
  5329. GGML_ASSERT(d_Y->size >= y_sz * ne12 * ne13);
  5330. } else if (quantize_y) {
  5331. d_Y = ctx->prealloc_y;
  5332. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz * ne12 * ne13, 144) * 144);
  5333. } else {
  5334. d_Y = d_Qy;
  5335. y_buf_offset = qy_buf_offset;
  5336. GGML_ASSERT(qy_sz == y_sz);
  5337. }
  5338. if (x_non_contig || qx_needs_dequant) {
  5339. if (ctx->prealloc_x_need_sync) {
  5340. ggml_vk_sync_buffers(ctx, subctx);
  5341. }
  5342. }
  5343. if (x_non_contig) {
  5344. 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 });
  5345. } else if (qx_needs_dequant) {
  5346. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  5347. 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});
  5348. ggml_vk_sync_buffers(ctx, subctx);
  5349. }
  5350. if (y_non_contig) {
  5351. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5352. ctx->prealloc_y_last_tensor_used != src1) {
  5353. if (ctx->prealloc_y_need_sync) {
  5354. ggml_vk_sync_buffers(ctx, subctx);
  5355. }
  5356. 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 });
  5357. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5358. ctx->prealloc_y_last_tensor_used = src1;
  5359. }
  5360. }
  5361. if (quantize_y) {
  5362. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5363. ctx->prealloc_y_last_tensor_used != src1) {
  5364. if (ctx->prealloc_y_need_sync) {
  5365. ggml_vk_sync_buffers(ctx, subctx);
  5366. }
  5367. 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);
  5368. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5369. ctx->prealloc_y_last_tensor_used = src1;
  5370. }
  5371. }
  5372. uint32_t stride_batch_x = ne00*ne01;
  5373. uint32_t stride_batch_y = ne10*ne11;
  5374. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5375. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5376. }
  5377. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  5378. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5379. }
  5380. uint32_t y_sz_total = y_sz * ne12 * ne13;
  5381. if (quantize_y) {
  5382. y_sz_total = CEIL_DIV(y_sz_total, 144) * 144;
  5383. }
  5384. // No bounds checking is needed for dst. This is basically VK_WHOLE_SIZE but clamped to maxStorageBufferRange.
  5385. VkDeviceSize d_range = std::min(VkDeviceSize{d_D->size - d_buf_offset}, VkDeviceSize{ctx->device->properties.limits.maxStorageBufferRange});
  5386. // compute
  5387. ggml_vk_matmul(
  5388. ctx, subctx, pipeline,
  5389. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz_total },
  5390. { d_D, d_buf_offset, d_range }, { ctx->prealloc_split_k, 0, d_sz * ne12 * ne13 * split_k },
  5391. ne01, ne11, ne10,
  5392. ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d,
  5393. split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n
  5394. ); // NOLINT
  5395. if (x_non_contig || qx_needs_dequant) {
  5396. ctx->prealloc_x_need_sync = true;
  5397. }
  5398. if (y_non_contig || quantize_y) {
  5399. ctx->prealloc_y_need_sync = true;
  5400. }
  5401. }
  5402. // Device tuning
  5403. static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_t n, uint32_t k, ggml_type src0_type) {
  5404. if (device->mmvq_mode == 1) {
  5405. return true;
  5406. } else if (device->mmvq_mode == -1) {
  5407. return false;
  5408. }
  5409. // MMVQ is generally good for batches
  5410. if (n > 1) {
  5411. return true;
  5412. }
  5413. switch (device->vendor_id) {
  5414. case VK_VENDOR_ID_NVIDIA:
  5415. switch (src0_type) {
  5416. case GGML_TYPE_Q8_0:
  5417. return device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  5418. default:
  5419. return true;
  5420. }
  5421. case VK_VENDOR_ID_AMD:
  5422. switch (src0_type) {
  5423. case GGML_TYPE_Q8_0:
  5424. return device->architecture == vk_device_architecture::AMD_GCN;
  5425. default:
  5426. return true;
  5427. }
  5428. case VK_VENDOR_ID_INTEL:
  5429. switch (src0_type) {
  5430. // From tests on A770 Linux, may need more tuning
  5431. case GGML_TYPE_Q4_0:
  5432. case GGML_TYPE_Q5_1:
  5433. return false;
  5434. default:
  5435. return true;
  5436. }
  5437. default:
  5438. return true;
  5439. }
  5440. GGML_UNUSED(m);
  5441. GGML_UNUSED(k);
  5442. }
  5443. 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) {
  5444. 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];
  5445. 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];
  5446. 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];
  5447. std::cerr << "), " << (dryrun ? "dryrun" : "") << "),)");
  5448. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5449. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5450. const uint64_t ne00 = src0->ne[0];
  5451. const uint64_t ne01 = src0->ne[1];
  5452. const uint64_t ne02 = src0->ne[2];
  5453. const uint64_t ne03 = src0->ne[3];
  5454. const uint64_t ne10 = src1->ne[0];
  5455. const uint64_t ne11 = src1->ne[1];
  5456. const uint64_t ne12 = src1->ne[2];
  5457. const uint64_t ne13 = src1->ne[3];
  5458. const uint64_t ne20 = dst->ne[0];
  5459. const uint64_t ne21 = dst->ne[1];
  5460. const uint64_t ne22 = dst->ne[2];
  5461. const uint64_t ne23 = dst->ne[3];
  5462. const uint64_t r2 = ne12 / ne02;
  5463. const uint64_t r3 = ne13 / ne03;
  5464. // batch_n indicates that we need to compute a few vector results, and this assumes
  5465. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  5466. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  5467. bool batch_n = ne11 > 1;
  5468. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5469. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5470. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5471. vk_buffer d_Qx = nullptr;
  5472. size_t qx_buf_offset = 0;
  5473. vk_buffer d_Qy = nullptr;
  5474. size_t qy_buf_offset = 0;
  5475. bool src0_uma = false;
  5476. bool src1_uma = false;
  5477. if (ctx->device->uma) {
  5478. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5479. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5480. src0_uma = d_Qx != nullptr;
  5481. src1_uma = d_Qy != nullptr;
  5482. }
  5483. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  5484. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  5485. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  5486. 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);
  5487. vk_pipeline to_fp16_vk_0 = nullptr;
  5488. vk_pipeline to_fp16_vk_1 = nullptr;
  5489. if (x_non_contig) {
  5490. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  5491. }
  5492. if (y_non_contig) {
  5493. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  5494. } else {
  5495. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5496. }
  5497. // Check for mmq first
  5498. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr;
  5499. vk_pipeline to_q8_1 = nullptr;
  5500. if (dmmv == nullptr) {
  5501. // Fall back to f16 dequant mul mat
  5502. dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11, ne20, ne00);
  5503. quantize_y = false;
  5504. }
  5505. if (quantize_y) {
  5506. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1, true);
  5507. }
  5508. const bool qx_needs_dequant = x_non_contig;
  5509. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  5510. // Not implemented
  5511. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5512. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5513. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5514. GGML_ASSERT(dmmv != nullptr);
  5515. const uint64_t x_ne = ne01 * ne00;
  5516. const uint64_t y_ne = ne11 * ne10;
  5517. const uint64_t d_ne = ne11 * ne01;
  5518. 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);
  5519. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5520. 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;
  5521. 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);
  5522. const uint64_t d_sz = sizeof(float) * d_ne;
  5523. if (dryrun) {
  5524. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  5525. uint64_t y_sz_upd = y_sz * ne12 * ne13;
  5526. if (quantize_y) {
  5527. y_sz_upd = CEIL_DIV(y_sz_upd, 144) * 144;
  5528. }
  5529. if (
  5530. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  5531. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  5532. GGML_ABORT("Requested preallocation size is too large");
  5533. }
  5534. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  5535. ctx->prealloc_size_x = x_sz_upd;
  5536. }
  5537. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz_upd) {
  5538. ctx->prealloc_size_y = y_sz_upd;
  5539. }
  5540. // Request descriptor sets
  5541. if (qx_needs_dequant) {
  5542. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5543. }
  5544. if (qy_needs_dequant) {
  5545. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5546. }
  5547. if (quantize_y) {
  5548. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5549. }
  5550. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  5551. return;
  5552. }
  5553. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5554. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5555. GGML_ASSERT(d_D != nullptr);
  5556. vk_buffer d_X;
  5557. uint64_t x_buf_offset = 0;
  5558. vk_buffer d_Y;
  5559. uint64_t y_buf_offset = 0;
  5560. if(!src0_uma) {
  5561. d_Qx = src0_buf_ctx->dev_buffer;
  5562. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5563. GGML_ASSERT(d_Qx != nullptr);
  5564. }
  5565. if(!src1_uma) {
  5566. d_Qy = src1_buf_ctx->dev_buffer;
  5567. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5568. GGML_ASSERT(d_Qy != nullptr);
  5569. }
  5570. if (qx_needs_dequant) {
  5571. d_X = ctx->prealloc_x;
  5572. } else {
  5573. d_X = d_Qx;
  5574. x_buf_offset = qx_buf_offset;
  5575. GGML_ASSERT(qx_sz == x_sz);
  5576. }
  5577. if (qy_needs_dequant) {
  5578. d_Y = ctx->prealloc_y;
  5579. } else if (quantize_y) {
  5580. d_Y = ctx->prealloc_y;
  5581. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz * ne12 * ne13, 144) * 144);
  5582. } else {
  5583. d_Y = d_Qy;
  5584. y_buf_offset = qy_buf_offset;
  5585. GGML_ASSERT(qy_sz == y_sz);
  5586. }
  5587. if (x_non_contig) {
  5588. if (ctx->prealloc_x_need_sync) {
  5589. ggml_vk_sync_buffers(ctx, subctx);
  5590. }
  5591. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  5592. 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 });
  5593. }
  5594. if (y_non_contig) {
  5595. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  5596. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5597. ctx->prealloc_y_last_tensor_used != src1) {
  5598. if (ctx->prealloc_y_need_sync) {
  5599. ggml_vk_sync_buffers(ctx, subctx);
  5600. }
  5601. 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 });
  5602. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5603. ctx->prealloc_y_last_tensor_used = src1;
  5604. }
  5605. }
  5606. if (quantize_y) {
  5607. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5608. ctx->prealloc_y_last_tensor_used != src1) {
  5609. if (ctx->prealloc_y_need_sync) {
  5610. ggml_vk_sync_buffers(ctx, subctx);
  5611. }
  5612. 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);
  5613. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5614. ctx->prealloc_y_last_tensor_used = src1;
  5615. }
  5616. }
  5617. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  5618. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  5619. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  5620. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  5621. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5622. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5623. }
  5624. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  5625. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5626. }
  5627. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  5628. uint32_t groups_x = ne01;
  5629. uint32_t groups_z = 1;
  5630. if (ne01 > max_groups_x) {
  5631. groups_z = 64;
  5632. groups_x = CEIL_DIV(groups_x, groups_z);
  5633. }
  5634. // TODO: Clean up this whole sz * ne_2 * ne_3 thing, it hasn't been necessary for a long time
  5635. uint32_t y_sz_total = y_sz * ne12 * ne13;
  5636. if (quantize_y) {
  5637. y_sz_total = CEIL_DIV(y_sz_total, 144) * 144;
  5638. }
  5639. // compute
  5640. const vk_mat_vec_push_constants pc = {
  5641. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  5642. stride_batch_x, stride_batch_y, stride_batch_d,
  5643. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  5644. };
  5645. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  5646. { 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} },
  5647. pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  5648. if (x_non_contig) {
  5649. ctx->prealloc_x_need_sync = true;
  5650. }
  5651. if (y_non_contig || quantize_y) {
  5652. ctx->prealloc_y_need_sync = true;
  5653. }
  5654. }
  5655. 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) {
  5656. 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];
  5657. 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];
  5658. 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];
  5659. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5660. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  5661. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  5662. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  5663. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  5664. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  5665. const uint64_t ne00 = src0->ne[0];
  5666. const uint64_t ne01 = src0->ne[1];
  5667. const uint64_t ne02 = src0->ne[2];
  5668. // const uint64_t ne03 = src0->ne[3];
  5669. const uint64_t ne10 = src1->ne[0];
  5670. const uint64_t ne11 = src1->ne[1];
  5671. const uint64_t ne12 = src1->ne[2];
  5672. // const uint64_t ne13 = src1->ne[3];
  5673. GGML_ASSERT(ne11 == 1);
  5674. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5675. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5676. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5677. vk_buffer d_Qy = nullptr;
  5678. size_t qy_buf_offset = 0;
  5679. bool src1_uma = false;
  5680. if (ctx->device->uma) {
  5681. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5682. src1_uma = d_Qy != nullptr;
  5683. }
  5684. const uint64_t x_ne = ne00 * ne01 * ne02;
  5685. const uint64_t y_ne = ne10 * ne11 * ne12;
  5686. const uint64_t d_ne = ne01 * ne11 * ne12;
  5687. 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);
  5688. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5689. const uint64_t d_sz = sizeof(float) * d_ne;
  5690. // With grouped query attention there are > 1 Q matrices per K, V matrix.
  5691. uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02;
  5692. if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) {
  5693. gqa_ratio = 1;
  5694. }
  5695. if (dryrun) {
  5696. // Request descriptor sets
  5697. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], 1);
  5698. return;
  5699. }
  5700. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5701. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5702. GGML_ASSERT(d_D != nullptr);
  5703. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  5704. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5705. GGML_ASSERT(d_Qx != nullptr);
  5706. if (!src1_uma) {
  5707. d_Qy = src1_buf_ctx->dev_buffer;
  5708. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5709. GGML_ASSERT(d_Qx != nullptr);
  5710. }
  5711. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5712. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  5713. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5714. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  5715. // compute
  5716. 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)) };
  5717. uint32_t workgroups_z = (uint32_t)ne12;
  5718. // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups
  5719. if (gqa_ratio > 1) {
  5720. workgroups_z /= gqa_ratio;
  5721. }
  5722. 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 });
  5723. }
  5724. 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) {
  5725. 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];
  5726. 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];
  5727. 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];
  5728. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5729. GGML_ASSERT(!ggml_is_transposed(src0));
  5730. GGML_ASSERT(!ggml_is_transposed(src1));
  5731. GGML_ASSERT(!ggml_is_permuted(src0));
  5732. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  5733. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  5734. const uint64_t ne00 = src0->ne[0];
  5735. const uint64_t ne01 = src0->ne[1];
  5736. const uint64_t ne02 = src0->ne[2];
  5737. const uint64_t ne03 = src0->ne[3];
  5738. const uint64_t nb01 = src0->nb[1];
  5739. const uint64_t nb02 = src0->nb[2];
  5740. const uint64_t nb12 = src1->nb[2];
  5741. // const uint64_t ne10 = src1->ne[0];
  5742. const uint64_t ne11 = src1->ne[1];
  5743. const uint64_t ne12 = src1->ne[2];
  5744. // const uint64_t ne13 = src1->ne[3];
  5745. const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t));
  5746. const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float));
  5747. const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float));
  5748. GGML_ASSERT(ne11 == 1);
  5749. GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in supports_op
  5750. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5751. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5752. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5753. vk_buffer d_Qy = nullptr;
  5754. size_t qy_buf_offset = 0;
  5755. bool src1_uma = false;
  5756. if (ctx->device->uma) {
  5757. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5758. src1_uma = d_Qy != nullptr;
  5759. }
  5760. const uint64_t d_ne = ne01 * ne11 * ne12 * ne03;
  5761. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  5762. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  5763. const uint32_t channel_stride_y = nb12 / sizeof(float);
  5764. const uint64_t qx_sz = ggml_nbytes(src0);
  5765. const uint64_t qy_sz = ggml_nbytes(src1);
  5766. const uint64_t d_sz = sizeof(float) * d_ne;
  5767. if (dryrun) {
  5768. // Request descriptor sets
  5769. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  5770. return;
  5771. }
  5772. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5773. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5774. GGML_ASSERT(d_D != nullptr);
  5775. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  5776. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5777. GGML_ASSERT(d_Qx != nullptr);
  5778. if (!src1_uma) {
  5779. d_Qy = src1_buf_ctx->dev_buffer;
  5780. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5781. GGML_ASSERT(d_Qx != nullptr);
  5782. }
  5783. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5784. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  5785. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5786. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  5787. // compute
  5788. 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 };
  5789. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  5790. { 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 });
  5791. }
  5792. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * src0, ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  5793. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  5794. // Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases
  5795. // where the M dimension is very large.
  5796. // Split_k doesn't work with M splitting.
  5797. const size_t nbytes = ggml_nbytes(src0);
  5798. const bool needs_split = nbytes > ctx->device->properties.limits.maxStorageBufferRange;
  5799. if (needs_split) {
  5800. // Choose the number of rows that can fit (and divide by two, to allow for any additional offsets)
  5801. const uint32_t M_split = ctx->device->properties.limits.maxStorageBufferRange / (2 * src0->nb[1]);
  5802. uint32_t m_offset = 0;
  5803. while (m_offset < dst->ne[0]) {
  5804. const uint32_t cur_M_size = std::min(M_split, (uint32_t)(dst->ne[0] - m_offset));
  5805. ggml_tensor dst2 = *dst;
  5806. ggml_tensor src02 = *src0;
  5807. dst2.view_src = dst->view_src ? dst->view_src : dst;
  5808. src02.view_src = src0->view_src ? src0->view_src : src0;
  5809. dst2.view_offs += m_offset * dst->nb[0];
  5810. src02.view_offs += m_offset * src0->nb[1];
  5811. dst2.ne[0] = cur_M_size;
  5812. src02.ne[1] = cur_M_size;
  5813. ggml_vk_mul_mat_q_f16(ctx, subctx, &src02, src1, &dst2, true, dryrun);
  5814. m_offset += cur_M_size;
  5815. }
  5816. } else if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  5817. // detect 0213 permutation, and batch size of 1
  5818. src0->nb[0] <= src0->nb[2] &&
  5819. src0->nb[2] <= src0->nb[1] &&
  5820. src0->nb[1] <= src0->nb[3] &&
  5821. src1->nb[0] <= src1->nb[2] &&
  5822. src1->nb[2] <= src1->nb[1] &&
  5823. src1->nb[1] <= src1->nb[3] &&
  5824. src0->ne[3] == 1 &&
  5825. src1->ne[3] == 1) {
  5826. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  5827. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  5828. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  5829. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  5830. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  5831. // when ne12 and ne13 are one.
  5832. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  5833. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
  5834. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, src0, src1, dst, dryrun);
  5835. } else {
  5836. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false, dryrun);
  5837. }
  5838. }
  5839. 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) {
  5840. 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];
  5841. 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];
  5842. 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];
  5843. 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] << "),)");
  5844. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5845. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  5846. const uint64_t ne00 = src0->ne[0];
  5847. const uint64_t ne01 = src0->ne[1];
  5848. const uint64_t ne02 = src0->ne[2];
  5849. const uint64_t ne03 = src0->ne[3];
  5850. const uint64_t ne10 = src1->ne[0];
  5851. const uint64_t ne11 = src1->ne[1];
  5852. const uint64_t ne12 = src1->ne[2];
  5853. const uint64_t ne13 = src1->ne[3];
  5854. const uint64_t nei0 = ids->ne[0];
  5855. const uint64_t nei1 = ids->ne[1];
  5856. const uint32_t nbi1 = ids->nb[1];
  5857. const uint32_t nbi2 = ids->nb[2];
  5858. const uint64_t ne20 = dst->ne[0];
  5859. const uint64_t ne21 = dst->ne[1];
  5860. const uint64_t ne22 = dst->ne[2];
  5861. const uint64_t ne23 = dst->ne[3];
  5862. const uint64_t n_as = ne02;
  5863. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5864. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5865. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5866. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  5867. vk_buffer d_Qx = nullptr;
  5868. size_t qx_buf_offset = 0;
  5869. vk_buffer d_Qy = nullptr;
  5870. size_t qy_buf_offset = 0;
  5871. vk_buffer d_ids = nullptr;
  5872. size_t ids_buf_offset = 0;
  5873. bool src0_uma = false;
  5874. bool src1_uma = false;
  5875. bool ids_uma = false;
  5876. if (ctx->device->uma) {
  5877. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5878. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5879. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  5880. src0_uma = d_Qx != nullptr;
  5881. src1_uma = d_Qy != nullptr;
  5882. ids_uma = d_ids != nullptr;
  5883. }
  5884. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5885. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5886. !ggml_vk_dim01_contiguous(src0);
  5887. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5888. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5889. !ggml_vk_dim01_contiguous(src1);
  5890. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5891. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5892. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5893. 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]);
  5894. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5895. const bool qy_needs_dequant = (src1->type != f16_type && !y_f32_kernel) || y_non_contig;
  5896. if (qx_needs_dequant) {
  5897. // Fall back to dequant + f16 mulmat
  5898. 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]);
  5899. }
  5900. // Not implemented
  5901. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5902. 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));
  5903. const bool aligned = ne10 == kpad && ne01 > 8 && nei1 > 8;
  5904. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned, qx_needs_dequant ? f16_type : src0->type);
  5905. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  5906. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) :ne11;
  5907. const uint64_t x_ne = ne01 * ne00;
  5908. const uint64_t y_ne = padded_n * ne10;
  5909. const uint64_t d_ne = ne21 * ne20;
  5910. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  5911. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5912. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  5913. const uint64_t y_sz = y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  5914. const uint64_t ids_sz = nbi2;
  5915. const uint64_t d_sz = sizeof(float) * d_ne;
  5916. vk_pipeline to_fp16_vk_0 = nullptr;
  5917. vk_pipeline to_fp16_vk_1 = nullptr;
  5918. if (x_non_contig) {
  5919. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  5920. } else {
  5921. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  5922. }
  5923. if (y_non_contig) {
  5924. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  5925. } else {
  5926. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5927. }
  5928. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5929. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5930. if (dryrun) {
  5931. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  5932. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  5933. if (
  5934. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  5935. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  5936. GGML_ABORT("Requested preallocation size is too large");
  5937. }
  5938. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  5939. ctx->prealloc_size_x = x_sz_upd;
  5940. }
  5941. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  5942. ctx->prealloc_size_y = y_sz_upd;
  5943. }
  5944. // Request descriptor sets
  5945. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  5946. if (qx_needs_dequant) {
  5947. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5948. }
  5949. if (qy_needs_dequant) {
  5950. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5951. }
  5952. return;
  5953. }
  5954. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5955. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5956. GGML_ASSERT(d_D != nullptr);
  5957. vk_buffer d_X;
  5958. uint64_t x_buf_offset = 0;
  5959. vk_buffer d_Y;
  5960. uint64_t y_buf_offset = 0;
  5961. if (!src0_uma) {
  5962. d_Qx = src0_buf_ctx->dev_buffer;
  5963. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5964. GGML_ASSERT(d_Qx != nullptr);
  5965. }
  5966. if (!src1_uma) {
  5967. d_Qy = src1_buf_ctx->dev_buffer;
  5968. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5969. GGML_ASSERT(d_Qy != nullptr);
  5970. }
  5971. if (!ids_uma) {
  5972. d_ids = ids_buf_ctx->dev_buffer;
  5973. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  5974. GGML_ASSERT(d_ids != nullptr);
  5975. }
  5976. if (qx_needs_dequant) {
  5977. d_X = ctx->prealloc_x;
  5978. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  5979. } else {
  5980. d_X = d_Qx;
  5981. x_buf_offset = qx_buf_offset;
  5982. GGML_ASSERT(qx_sz == x_sz);
  5983. }
  5984. if (qy_needs_dequant) {
  5985. d_Y = ctx->prealloc_y;
  5986. GGML_ASSERT(d_Y->size >= y_sz * ne12 * ne13);
  5987. } else {
  5988. d_Y = d_Qy;
  5989. y_buf_offset = qy_buf_offset;
  5990. GGML_ASSERT(qy_sz == y_sz);
  5991. }
  5992. if (x_non_contig || qx_needs_dequant) {
  5993. if (ctx->prealloc_x_need_sync) {
  5994. ggml_vk_sync_buffers(ctx, subctx);
  5995. }
  5996. }
  5997. if (x_non_contig) {
  5998. 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 });
  5999. } else if (qx_needs_dequant) {
  6000. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6001. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  6002. { 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});
  6003. ggml_vk_sync_buffers(ctx, subctx);
  6004. }
  6005. if (y_non_contig) {
  6006. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6007. ctx->prealloc_y_last_tensor_used != src1) {
  6008. if (ctx->prealloc_y_need_sync) {
  6009. ggml_vk_sync_buffers(ctx, subctx);
  6010. }
  6011. 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 });
  6012. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6013. ctx->prealloc_y_last_tensor_used = src1;
  6014. }
  6015. }
  6016. uint32_t stride_batch_x = ne00*ne01;
  6017. uint32_t stride_batch_y = ne10*ne11;
  6018. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6019. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6020. }
  6021. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6022. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6023. }
  6024. // compute
  6025. ggml_vk_matmul_id(
  6026. ctx, subctx, pipeline,
  6027. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz * ne12 * ne13 },
  6028. { d_D, d_buf_offset, d_sz * ne22 * ne23 }, { d_ids, ids_buf_offset, ids_sz },
  6029. ne01, ne21, ne10, ne10, ne10, ne01,
  6030. stride_batch_x, stride_batch_y, ne20*ne21,
  6031. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, padded_n
  6032. ); // NOLINT
  6033. if (x_non_contig || qx_needs_dequant) {
  6034. ctx->prealloc_x_need_sync = true;
  6035. }
  6036. if (y_non_contig) {
  6037. ctx->prealloc_y_need_sync = true;
  6038. }
  6039. }
  6040. 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) {
  6041. 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];
  6042. 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];
  6043. 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];
  6044. 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];
  6045. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  6046. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6047. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6048. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6049. const uint64_t ne00 = src0->ne[0];
  6050. const uint64_t ne01 = src0->ne[1];
  6051. const uint64_t ne02 = src0->ne[2];
  6052. const uint64_t ne03 = src0->ne[3];
  6053. const uint64_t ne10 = src1->ne[0];
  6054. const uint64_t ne11 = src1->ne[1];
  6055. const uint64_t ne12 = src1->ne[2];
  6056. const uint64_t ne13 = src1->ne[3];
  6057. const uint64_t nei0 = ids->ne[0];
  6058. const uint64_t nei1 = ids->ne[1];
  6059. const uint64_t nbi2 = ids->nb[2];
  6060. GGML_ASSERT(nei1 == 1);
  6061. const uint64_t ne20 = dst->ne[0];
  6062. const uint64_t ne21 = dst->ne[1];
  6063. const uint64_t ne22 = dst->ne[2];
  6064. const uint64_t ne23 = dst->ne[3];
  6065. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6066. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6067. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6068. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6069. vk_buffer d_Qx = nullptr;
  6070. size_t qx_buf_offset = 0;
  6071. vk_buffer d_Qy = nullptr;
  6072. size_t qy_buf_offset = 0;
  6073. vk_buffer d_ids = nullptr;
  6074. size_t ids_buf_offset = 0;
  6075. bool src0_uma = false;
  6076. bool src1_uma = false;
  6077. bool ids_uma = false;
  6078. if (ctx->device->uma) {
  6079. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6080. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6081. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6082. src0_uma = d_Qx != nullptr;
  6083. src1_uma = d_Qy != nullptr;
  6084. ids_uma = d_ids != nullptr;
  6085. }
  6086. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6087. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6088. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6089. const bool qx_needs_dequant = x_non_contig;
  6090. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  6091. // Not implemented
  6092. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6093. const uint64_t x_ne = ne01 * ne00;
  6094. const uint64_t y_ne = ne11 * ne10;
  6095. const uint64_t d_ne = ne21 * ne20;
  6096. 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);
  6097. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6098. 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;
  6099. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  6100. const uint64_t ids_sz = nbi2;
  6101. const uint64_t d_sz = sizeof(float) * d_ne;
  6102. vk_pipeline to_fp16_vk_0 = nullptr;
  6103. vk_pipeline to_fp16_vk_1 = nullptr;
  6104. if (x_non_contig) {
  6105. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6106. }
  6107. if (y_non_contig) {
  6108. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6109. } else {
  6110. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6111. }
  6112. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type);
  6113. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6114. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6115. GGML_ASSERT(dmmv != nullptr);
  6116. if (dryrun) {
  6117. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  6118. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  6119. if (
  6120. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  6121. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  6122. GGML_ABORT("Requested preallocation size is too large");
  6123. }
  6124. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  6125. ctx->prealloc_size_x = x_sz_upd;
  6126. }
  6127. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  6128. ctx->prealloc_size_y = y_sz_upd;
  6129. }
  6130. // Request descriptor sets
  6131. if (qx_needs_dequant) {
  6132. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6133. }
  6134. if (qy_needs_dequant) {
  6135. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6136. }
  6137. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6138. return;
  6139. }
  6140. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6141. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6142. GGML_ASSERT(d_D != nullptr);
  6143. vk_buffer d_X;
  6144. uint64_t x_buf_offset = 0;
  6145. vk_buffer d_Y;
  6146. uint64_t y_buf_offset = 0;
  6147. if(!src0_uma) {
  6148. d_Qx = src0_buf_ctx->dev_buffer;
  6149. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6150. GGML_ASSERT(d_Qx != nullptr);
  6151. }
  6152. if(!src1_uma) {
  6153. d_Qy = src1_buf_ctx->dev_buffer;
  6154. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6155. GGML_ASSERT(d_Qy != nullptr);
  6156. }
  6157. if(!ids_uma) {
  6158. d_ids = ids_buf_ctx->dev_buffer;
  6159. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6160. GGML_ASSERT(d_ids != nullptr);
  6161. }
  6162. if (qx_needs_dequant) {
  6163. d_X = ctx->prealloc_x;
  6164. } else {
  6165. d_X = d_Qx;
  6166. x_buf_offset = qx_buf_offset;
  6167. GGML_ASSERT(qx_sz == x_sz);
  6168. }
  6169. if (qy_needs_dequant) {
  6170. d_Y = ctx->prealloc_y;
  6171. } else {
  6172. d_Y = d_Qy;
  6173. y_buf_offset = qy_buf_offset;
  6174. GGML_ASSERT(qy_sz == y_sz);
  6175. }
  6176. if (x_non_contig) {
  6177. if (ctx->prealloc_x_need_sync) {
  6178. ggml_vk_sync_buffers(ctx, subctx);
  6179. }
  6180. }
  6181. if (x_non_contig) {
  6182. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6183. 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 });
  6184. }
  6185. if (y_non_contig) {
  6186. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6187. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6188. ctx->prealloc_y_last_tensor_used != src1) {
  6189. if (ctx->prealloc_y_need_sync) {
  6190. ggml_vk_sync_buffers(ctx, subctx);
  6191. }
  6192. 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 });
  6193. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6194. ctx->prealloc_y_last_tensor_used = src1;
  6195. }
  6196. }
  6197. uint32_t stride_batch_y = ne10*ne11;
  6198. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6199. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6200. }
  6201. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6202. uint32_t groups_x = ne01;
  6203. uint32_t groups_z = 1;
  6204. if (ne01 > max_groups_x) {
  6205. groups_z = 64;
  6206. groups_x = CEIL_DIV(groups_x, groups_z);
  6207. }
  6208. // compute
  6209. const vk_mat_vec_id_push_constants pc = {
  6210. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6211. (uint32_t)x_ne, stride_batch_y, (uint32_t)(ne20*ne21),
  6212. (uint32_t)nei0, (uint32_t)ne11,
  6213. };
  6214. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6215. { vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 },
  6216. 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 } },
  6217. pc, { groups_x, (uint32_t)nei0, groups_z });
  6218. if (x_non_contig) {
  6219. ctx->prealloc_x_need_sync = true;
  6220. }
  6221. if (y_non_contig) {
  6222. ctx->prealloc_y_need_sync = true;
  6223. }
  6224. }
  6225. 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) {
  6226. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  6227. if (src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type))) {
  6228. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  6229. } else {
  6230. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  6231. }
  6232. }
  6233. static bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv) {
  6234. // Needs to be kept up to date on shader changes
  6235. GGML_UNUSED(hsv);
  6236. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6237. const uint32_t Br = get_fa_scalar_num_large_rows(hsv);
  6238. const uint32_t Bc = scalar_flash_attention_Bc;
  6239. const uint32_t tmpsh = wg_size * sizeof(float);
  6240. const uint32_t tmpshv4 = wg_size * 4 * sizeof(float);
  6241. const uint32_t masksh = Bc * Br * sizeof(float);
  6242. const uint32_t Qf = Br * (hsk / 4 + 2) * 4 * sizeof(float);
  6243. const uint32_t total_size = tmpsh + tmpshv4 + masksh + Qf;
  6244. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6245. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported);
  6246. return supported;
  6247. }
  6248. static bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool f32acc) {
  6249. // Needs to be kept up to date on shader changes
  6250. GGML_UNUSED(hsv);
  6251. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6252. const uint32_t Br = coopmat1_flash_attention_num_large_rows;
  6253. const uint32_t Bc = scalar_flash_attention_Bc;
  6254. const uint32_t hsk_pad = ROUNDUP_POW2(hsk, 16);
  6255. const uint32_t acctype = f32acc ? 4 : 2;
  6256. const uint32_t f16vec4 = 8;
  6257. const uint32_t tmpsh = wg_size * sizeof(float);
  6258. const uint32_t tmpshv4 = wg_size * 4 * acctype;
  6259. const uint32_t qstride = hsk_pad / 4 + 2;
  6260. const uint32_t Qf = Br * qstride * f16vec4;
  6261. const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br;
  6262. const uint32_t sfsh = Bc * sfshstride * acctype;
  6263. const uint32_t kshstride = hsk_pad / 4 + 2;
  6264. const uint32_t ksh = Bc * kshstride * f16vec4;
  6265. const uint32_t slope = Br * sizeof(float);
  6266. const uint32_t total_size = tmpsh + tmpshv4 + Qf + sfsh + ksh + slope;
  6267. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6268. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported);
  6269. return supported;
  6270. }
  6271. 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) {
  6272. 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];
  6273. 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];
  6274. 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];
  6275. 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];
  6276. if (sinks) {
  6277. 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];
  6278. }
  6279. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  6280. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  6281. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  6282. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  6283. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  6284. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  6285. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  6286. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  6287. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  6288. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  6289. const uint32_t nem2 = mask ? mask->ne[2] : 0;
  6290. const uint32_t nem3 = mask ? mask->ne[3] : 0;
  6291. const uint32_t HSK = nek0;
  6292. const uint32_t HSV = nev0;
  6293. uint32_t N = neq1;
  6294. const uint32_t KV = nek1;
  6295. GGML_ASSERT(ne0 == HSV);
  6296. GGML_ASSERT(ne2 == N);
  6297. // input tensor rows must be contiguous
  6298. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  6299. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  6300. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  6301. GGML_ASSERT(neq0 == HSK);
  6302. GGML_ASSERT(neq1 == N);
  6303. GGML_ASSERT(nev1 == nek1);
  6304. // dst cannot be transposed or permuted
  6305. GGML_ASSERT(nb0 == sizeof(float));
  6306. GGML_ASSERT(nb0 <= nb1);
  6307. GGML_ASSERT(nb1 <= nb2);
  6308. GGML_ASSERT(nb2 <= nb3);
  6309. assert(dst->type == GGML_TYPE_F32);
  6310. assert(q->type == GGML_TYPE_F32);
  6311. assert(k->type == v->type);
  6312. FaCodePath path = ctx->device->coopmat2 ? FA_COOPMAT2 :
  6313. ctx->device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;
  6314. if (path == FA_COOPMAT1) {
  6315. const bool coopmat_shape_supported = (dst->op_params[3] == GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f32acc) ||
  6316. (dst->op_params[3] != GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f16acc);
  6317. const bool coopmat_shmem_supported = ggml_vk_flash_attn_coopmat_shmem_support(ctx->device, HSK, HSV, dst->op_params[3] == GGML_PREC_F32);
  6318. if (!coopmat_shape_supported || !coopmat_shmem_supported) {
  6319. path = FA_SCALAR;
  6320. }
  6321. }
  6322. uint32_t gqa_ratio = 1;
  6323. uint32_t qk_ratio = neq2 / nek2;
  6324. uint32_t workgroups_x = (uint32_t)neq1;
  6325. uint32_t workgroups_y = (uint32_t)neq2;
  6326. uint32_t workgroups_z = (uint32_t)neq3;
  6327. // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga.
  6328. // For coopmat2 FA, we always use the small size (which is still pretty large for gqa).
  6329. uint32_t max_gqa;
  6330. switch (path) {
  6331. case FA_SCALAR:
  6332. case FA_COOPMAT1:
  6333. // We may switch from coopmat1 to scalar, so use the scalar limit for both
  6334. max_gqa = get_fa_scalar_num_large_rows(HSV);
  6335. break;
  6336. case FA_COOPMAT2:
  6337. max_gqa = get_fa_num_small_rows(FA_COOPMAT2);
  6338. break;
  6339. default:
  6340. GGML_ASSERT(0);
  6341. }
  6342. if (N == 1 && qk_ratio > 1 && qk_ratio <= max_gqa &&
  6343. qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) {
  6344. // grouped query attention - make the N dimension equal to gqa_ratio, reduce
  6345. // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1
  6346. // and change addressing calculations to index Q's dimension 2.
  6347. gqa_ratio = qk_ratio;
  6348. N = gqa_ratio;
  6349. workgroups_y /= N;
  6350. }
  6351. bool small_rows = N <= get_fa_num_small_rows(path);
  6352. // coopmat1 does not actually support "small rows" (it needs 16 rows).
  6353. // So use scalar instead.
  6354. if (small_rows && path == FA_COOPMAT1) {
  6355. path = FA_SCALAR;
  6356. }
  6357. // scalar is faster than coopmat2 when N==1
  6358. if (N == 1 && path == FA_COOPMAT2) {
  6359. path = FA_SCALAR;
  6360. }
  6361. // with large hsk/hsv, scalar path may need to use small_rows to fit in shared memory
  6362. if (path == FA_SCALAR &&
  6363. !ggml_vk_flash_attn_scalar_shmem_support(ctx->device, HSK, HSV)) {
  6364. small_rows = true;
  6365. }
  6366. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  6367. const uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  6368. const uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  6369. uint32_t alignment = fa_align(path, HSK, HSV, k->type, small_rows);
  6370. bool aligned = (KV % alignment) == 0 &&
  6371. // the "aligned" shader variant will forcibly align strides, for performance
  6372. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  6373. // Need to use the coopmat2 variant that clamps loads when HSK/HSV aren't sufficiently aligned.
  6374. if (((HSK | HSV) % 16) != 0 && path == FA_COOPMAT2) {
  6375. aligned = false;
  6376. }
  6377. // mask dim1 is padded to 64, we rely on this to avoid clamping mask loads
  6378. GGML_ASSERT((nem1 % GGML_KQ_MASK_PAD) == 0);
  6379. bool f32acc = path == FA_SCALAR || dst->op_params[3] == GGML_PREC_F32;
  6380. vk_fa_pipeline_state fa_pipeline_state(HSK, HSV, small_rows, path, aligned, f32acc);
  6381. vk_pipeline pipeline = nullptr;
  6382. auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16[k->type];
  6383. auto it = pipelines.find(fa_pipeline_state);
  6384. if (it != pipelines.end()) {
  6385. pipeline = it->second;
  6386. } else {
  6387. pipelines[fa_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  6388. }
  6389. assert(pipeline);
  6390. uint32_t split_kv = KV;
  6391. uint32_t split_k = 1;
  6392. // Use a placeholder core count if one isn't available. split_k is a big help for perf.
  6393. const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count : 16;
  6394. // Try to use split_k when KV is large enough to be worth the overhead
  6395. if (workgroups_x == 1 && shader_core_count > 0) {
  6396. // Try to run two workgroups per SM.
  6397. split_k = shader_core_count * 2 / (workgroups_y * workgroups_z);
  6398. if (split_k > 1) {
  6399. // Try to evenly split KV into split_k chunks, but it needs to be a multiple
  6400. // of "align", so recompute split_k based on that.
  6401. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment);
  6402. split_k = CEIL_DIV(KV, split_kv);
  6403. workgroups_x = split_k;
  6404. }
  6405. }
  6406. // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1)
  6407. // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows.
  6408. const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne3 : 0;
  6409. if (split_k_size > ctx->device->max_memory_allocation_size) {
  6410. GGML_ABORT("Requested preallocation size is too large");
  6411. }
  6412. if (ctx->prealloc_size_split_k < split_k_size) {
  6413. ctx->prealloc_size_split_k = split_k_size;
  6414. }
  6415. if (dryrun) {
  6416. // Request descriptor sets
  6417. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6418. if (split_k > 1) {
  6419. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1);
  6420. }
  6421. return;
  6422. }
  6423. float scale = 1.0f;
  6424. float max_bias = 0.0f;
  6425. float logit_softcap = 0.0f;
  6426. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  6427. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  6428. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  6429. if (logit_softcap != 0) {
  6430. scale /= logit_softcap;
  6431. }
  6432. const uint32_t n_head_kv = neq2;
  6433. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  6434. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  6435. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  6436. vk_buffer d_Q = nullptr, d_K = nullptr, d_V = nullptr, d_D = nullptr, d_M = nullptr, d_S = nullptr;
  6437. 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;
  6438. bool Q_uma = false, K_uma = false, V_uma = false, D_uma = false, M_uma = false, S_uma = false;
  6439. if (ctx->device->uma) {
  6440. ggml_vk_host_get(ctx->device, q->data, d_Q, q_buf_offset);
  6441. ggml_vk_host_get(ctx->device, k->data, d_K, k_buf_offset);
  6442. ggml_vk_host_get(ctx->device, v->data, d_V, v_buf_offset);
  6443. ggml_vk_host_get(ctx->device, dst->data, d_D, d_buf_offset);
  6444. Q_uma = d_Q != nullptr;
  6445. K_uma = d_K != nullptr;
  6446. V_uma = d_V != nullptr;
  6447. D_uma = d_D != nullptr;
  6448. if (mask) {
  6449. ggml_vk_host_get(ctx->device, mask->data, d_M, m_buf_offset);
  6450. M_uma = d_M != nullptr;
  6451. }
  6452. if (sinks) {
  6453. ggml_vk_host_get(ctx->device, sinks->data, d_S, s_buf_offset);
  6454. S_uma = d_S != nullptr;
  6455. }
  6456. }
  6457. ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6458. ggml_backend_vk_buffer_context * q_buf_ctx = (ggml_backend_vk_buffer_context *)q->buffer->context;
  6459. ggml_backend_vk_buffer_context * k_buf_ctx = (ggml_backend_vk_buffer_context *)k->buffer->context;
  6460. ggml_backend_vk_buffer_context * v_buf_ctx = (ggml_backend_vk_buffer_context *)v->buffer->context;
  6461. if (!Q_uma) {
  6462. d_Q = q_buf_ctx->dev_buffer;
  6463. q_buf_offset = vk_tensor_offset(q) + q->view_offs;
  6464. }
  6465. if (!K_uma) {
  6466. d_K = k_buf_ctx->dev_buffer;
  6467. k_buf_offset = vk_tensor_offset(k) + k->view_offs;
  6468. }
  6469. if (!V_uma) {
  6470. d_V = v_buf_ctx->dev_buffer;
  6471. v_buf_offset = vk_tensor_offset(v) + v->view_offs;
  6472. }
  6473. if (!D_uma) {
  6474. d_D = d_buf_ctx->dev_buffer;
  6475. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6476. }
  6477. if (!M_uma) {
  6478. d_M = d_Q;
  6479. m_buf_offset = q_buf_offset;
  6480. if (mask) {
  6481. ggml_backend_vk_buffer_context * m_buf_ctx = (ggml_backend_vk_buffer_context*)mask->buffer->context;
  6482. d_M = m_buf_ctx->dev_buffer;
  6483. m_buf_offset = vk_tensor_offset(mask) + mask->view_offs;
  6484. }
  6485. }
  6486. if (!S_uma) {
  6487. d_S = d_Q;
  6488. s_buf_offset = q_buf_offset;
  6489. if (sinks) {
  6490. ggml_backend_vk_buffer_context * s_buf_ctx = (ggml_backend_vk_buffer_context*)sinks->buffer->context;
  6491. d_S = s_buf_ctx->dev_buffer;
  6492. s_buf_offset = vk_tensor_offset(sinks) + sinks->view_offs;
  6493. }
  6494. }
  6495. uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | ((mask != nullptr) << 16) | n_head_log2;
  6496. const vk_flash_attn_push_constants pc = { N, KV,
  6497. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  6498. (uint32_t)neq2, (uint32_t)neq3,
  6499. (uint32_t)nek2, (uint32_t)nek3,
  6500. (uint32_t)nev2, (uint32_t)nev3,
  6501. nem1, nem2, nem3,
  6502. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  6503. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  6504. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  6505. scale, max_bias, logit_softcap,
  6506. mask_n_head_log2, m0, m1,
  6507. gqa_ratio, split_kv, split_k };
  6508. if (split_k > 1) {
  6509. if (ctx->prealloc_split_k_need_sync) {
  6510. ggml_vk_sync_buffers(ctx, subctx);
  6511. }
  6512. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6513. {
  6514. vk_subbuffer{d_Q, q_buf_offset, VK_WHOLE_SIZE},
  6515. vk_subbuffer{d_K, k_buf_offset, VK_WHOLE_SIZE},
  6516. vk_subbuffer{d_V, v_buf_offset, VK_WHOLE_SIZE},
  6517. vk_subbuffer{d_M, m_buf_offset, VK_WHOLE_SIZE},
  6518. vk_subbuffer{d_S, s_buf_offset, VK_WHOLE_SIZE},
  6519. vk_subbuffer{ctx->prealloc_split_k, 0, VK_WHOLE_SIZE},
  6520. },
  6521. // We only use split_k when group query attention is enabled, which means
  6522. // there's no more than one tile of rows (i.e. workgroups_x would have been
  6523. // one). We reuse workgroups_x to mean the number of splits, so we need to
  6524. // cancel out the divide by wg_denoms[0].
  6525. pc, { workgroups_x * pipeline->wg_denoms[0], workgroups_y, workgroups_z });
  6526. ggml_vk_sync_buffers(ctx, subctx);
  6527. const std::array<uint32_t, 5> pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne3, split_k, (sinks != nullptr) };
  6528. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce,
  6529. {
  6530. vk_subbuffer{ctx->prealloc_split_k, 0, VK_WHOLE_SIZE},
  6531. vk_subbuffer{d_S, s_buf_offset, VK_WHOLE_SIZE},
  6532. vk_subbuffer{d_D, d_buf_offset, VK_WHOLE_SIZE},
  6533. },
  6534. pc2, { (uint32_t)ne1, HSV, (uint32_t)ne3 });
  6535. ctx->prealloc_split_k_need_sync = true;
  6536. } else {
  6537. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6538. {
  6539. vk_subbuffer{d_Q, q_buf_offset, VK_WHOLE_SIZE},
  6540. vk_subbuffer{d_K, k_buf_offset, VK_WHOLE_SIZE},
  6541. vk_subbuffer{d_V, v_buf_offset, VK_WHOLE_SIZE},
  6542. vk_subbuffer{d_M, m_buf_offset, VK_WHOLE_SIZE},
  6543. vk_subbuffer{d_S, s_buf_offset, VK_WHOLE_SIZE},
  6544. vk_subbuffer{d_D, d_buf_offset, VK_WHOLE_SIZE},
  6545. },
  6546. pc, { workgroups_x, workgroups_y, workgroups_z });
  6547. }
  6548. }
  6549. static std::array<uint32_t, 3> ggml_vk_get_conv_elements(const ggml_tensor *dst) {
  6550. const ggml_tensor *src0 = dst->src[0];
  6551. const ggml_tensor *src1 = dst->src[1];
  6552. // src0 - kernel: [KW, KH, Cin, Cout]
  6553. // src1 - input: [W, H, Cin, N]
  6554. // dst - result: [OW, OH, Cout, N]
  6555. // Copied from ggml.c: int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d)
  6556. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6557. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  6558. };
  6559. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6560. int64_t W = src1->ne[0];
  6561. int64_t H = src1->ne[1];
  6562. int64_t KW = src0->ne[0];
  6563. int64_t KH = src0->ne[1];
  6564. int64_t Cout = src0->ne[3];
  6565. int64_t N = src1->ne[3];
  6566. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[1], dst->op_params[3], dst->op_params[5]);
  6567. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], dst->op_params[2], dst->op_params[4]);
  6568. int64_t NPQ = N * OW * OH;
  6569. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6570. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6571. return elements;
  6572. }
  6573. static std::array<uint32_t, 3> ggml_vk_get_conv_transpose_2d_elements(const ggml_tensor *dst) {
  6574. const ggml_tensor *src0 = dst->src[0];
  6575. const ggml_tensor *src1 = dst->src[1];
  6576. // src0 - kernel: [KW, KH, Cout, Cin]
  6577. // src1 - input: [W, H, Cin, N]
  6578. // dst - result: [OW, OH, Cout, N]
  6579. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6580. return (ins - 1) * s - 2 * p + (ks - 1) * d + 1;
  6581. };
  6582. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6583. int64_t W = src1->ne[0];
  6584. int64_t H = src1->ne[1];
  6585. int64_t KW = src0->ne[0];
  6586. int64_t KH = src0->ne[1];
  6587. int64_t Cout = src0->ne[2];
  6588. int64_t N = src1->ne[3];
  6589. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[0], 0, 1);
  6590. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], 0, 1);
  6591. int64_t NPQ = N * OW * OH;
  6592. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6593. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6594. return elements;
  6595. }
  6596. 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) {
  6597. switch (op) {
  6598. case GGML_OP_GET_ROWS:
  6599. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  6600. if (dst->type == GGML_TYPE_F16) {
  6601. return ctx->device->pipeline_get_rows[src0->type];
  6602. }
  6603. if (dst->type == GGML_TYPE_F32) {
  6604. return ctx->device->pipeline_get_rows_f32[src0->type];
  6605. }
  6606. return nullptr;
  6607. case GGML_OP_ACC:
  6608. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6609. return ctx->device->pipeline_acc_f32;
  6610. }
  6611. return nullptr;
  6612. case GGML_OP_ADD:
  6613. case GGML_OP_SUB:
  6614. case GGML_OP_MUL:
  6615. case GGML_OP_DIV:
  6616. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  6617. (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
  6618. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
  6619. return nullptr;
  6620. }
  6621. switch (op) {
  6622. case GGML_OP_ADD:
  6623. {
  6624. if (ctx->num_additional_fused_ops > 0) {
  6625. if (ctx->do_add_rms_partials) {
  6626. return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops];
  6627. } else {
  6628. return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  6629. }
  6630. }
  6631. if (ctx->do_add_rms_partials) {
  6632. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_rms_norepeat : ctx->device->pipeline_add_rms;
  6633. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6634. } else {
  6635. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add;
  6636. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6637. }
  6638. }
  6639. case GGML_OP_SUB:
  6640. {
  6641. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub;
  6642. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6643. }
  6644. case GGML_OP_MUL:
  6645. {
  6646. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul;
  6647. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6648. }
  6649. case GGML_OP_DIV:
  6650. {
  6651. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div;
  6652. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6653. }
  6654. default:
  6655. break;
  6656. }
  6657. return nullptr;
  6658. case GGML_OP_ADD_ID:
  6659. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) {
  6660. return ctx->device->pipeline_add_id_f32;
  6661. }
  6662. return nullptr;
  6663. case GGML_OP_CONCAT:
  6664. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6665. return ctx->device->pipeline_concat_f32;
  6666. }
  6667. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6668. return ctx->device->pipeline_concat_f16;
  6669. }
  6670. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  6671. return ctx->device->pipeline_concat_i32;
  6672. }
  6673. return nullptr;
  6674. case GGML_OP_UPSCALE:
  6675. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6676. int mode = ggml_get_op_params_i32(dst, 0);
  6677. switch (mode) {
  6678. case GGML_SCALE_MODE_NEAREST:
  6679. return ctx->device->pipeline_upscale_nearest_f32;
  6680. case GGML_SCALE_MODE_BILINEAR:
  6681. return ctx->device->pipeline_upscale_bilinear_f32;
  6682. case GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ALIGN_CORNERS:
  6683. return ctx->device->pipeline_upscale_bilinear_ac_f32;
  6684. }
  6685. }
  6686. return nullptr;
  6687. case GGML_OP_SCALE:
  6688. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6689. return ctx->device->pipeline_scale_f32;
  6690. }
  6691. return nullptr;
  6692. case GGML_OP_SQR:
  6693. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6694. return ctx->device->pipeline_sqr_f32;
  6695. }
  6696. return nullptr;
  6697. case GGML_OP_SQRT:
  6698. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6699. return ctx->device->pipeline_sqrt_f32;
  6700. }
  6701. return nullptr;
  6702. case GGML_OP_SIN:
  6703. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6704. return ctx->device->pipeline_sin_f32;
  6705. }
  6706. return nullptr;
  6707. case GGML_OP_COS:
  6708. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6709. return ctx->device->pipeline_cos_f32;
  6710. }
  6711. return nullptr;
  6712. case GGML_OP_CLAMP:
  6713. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6714. return ctx->device->pipeline_clamp_f32;
  6715. }
  6716. return nullptr;
  6717. case GGML_OP_PAD:
  6718. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6719. return ctx->device->pipeline_pad_f32;
  6720. }
  6721. return nullptr;
  6722. case GGML_OP_ROLL:
  6723. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6724. return ctx->device->pipeline_roll_f32;
  6725. }
  6726. return nullptr;
  6727. case GGML_OP_REPEAT:
  6728. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  6729. return ctx->device->pipeline_repeat_f32;
  6730. }
  6731. return nullptr;
  6732. case GGML_OP_REPEAT_BACK:
  6733. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6734. return ctx->device->pipeline_repeat_back_f32;
  6735. }
  6736. return nullptr;
  6737. case GGML_OP_CPY:
  6738. case GGML_OP_CONT:
  6739. case GGML_OP_DUP:
  6740. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  6741. case GGML_OP_SET_ROWS:
  6742. if (src1->type == GGML_TYPE_I64) {
  6743. return ctx->device->pipeline_set_rows_i64[dst->type];
  6744. } else {
  6745. return ctx->device->pipeline_set_rows_i32[dst->type];
  6746. }
  6747. case GGML_OP_SILU_BACK:
  6748. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6749. return ctx->device->pipeline_silu_back_f32;
  6750. }
  6751. return nullptr;
  6752. case GGML_OP_NORM:
  6753. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6754. return ctx->device->pipeline_norm_f32;
  6755. }
  6756. return nullptr;
  6757. case GGML_OP_GROUP_NORM:
  6758. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6759. return ctx->device->pipeline_group_norm_f32;
  6760. }
  6761. return nullptr;
  6762. case GGML_OP_RMS_NORM:
  6763. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6764. if (ctx->do_add_rms_partials) {
  6765. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32;
  6766. } else {
  6767. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32;
  6768. }
  6769. }
  6770. return nullptr;
  6771. case GGML_OP_RMS_NORM_BACK:
  6772. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6773. return ctx->device->pipeline_rms_norm_back_f32;
  6774. }
  6775. return nullptr;
  6776. case GGML_OP_L2_NORM:
  6777. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6778. return ctx->device->pipeline_l2_norm_f32;
  6779. }
  6780. return nullptr;
  6781. case GGML_OP_UNARY:
  6782. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  6783. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  6784. (src0->type != dst->type)) {
  6785. return nullptr;
  6786. }
  6787. switch (ggml_get_unary_op(dst)) {
  6788. case GGML_UNARY_OP_EXP:
  6789. return ctx->device->pipeline_exp[dst->type == GGML_TYPE_F16];
  6790. case GGML_UNARY_OP_SILU:
  6791. return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16];
  6792. case GGML_UNARY_OP_GELU:
  6793. return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16];
  6794. case GGML_UNARY_OP_GELU_ERF:
  6795. return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16];
  6796. case GGML_UNARY_OP_GELU_QUICK:
  6797. return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16];
  6798. case GGML_UNARY_OP_RELU:
  6799. return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16];
  6800. case GGML_UNARY_OP_TANH:
  6801. return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16];
  6802. case GGML_UNARY_OP_SIGMOID:
  6803. return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16];
  6804. case GGML_UNARY_OP_HARDSIGMOID:
  6805. return ctx->device->pipeline_hardsigmoid[dst->type == GGML_TYPE_F16];
  6806. case GGML_UNARY_OP_HARDSWISH:
  6807. return ctx->device->pipeline_hardswish[dst->type == GGML_TYPE_F16];
  6808. default:
  6809. break;
  6810. }
  6811. return nullptr;
  6812. case GGML_OP_GLU:
  6813. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  6814. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  6815. (src0->type != dst->type)) {
  6816. return nullptr;
  6817. }
  6818. switch (ggml_get_glu_op(dst)) {
  6819. case GGML_GLU_OP_GEGLU:
  6820. return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16];
  6821. case GGML_GLU_OP_REGLU:
  6822. return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16];
  6823. case GGML_GLU_OP_SWIGLU:
  6824. return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16];
  6825. case GGML_GLU_OP_SWIGLU_OAI:
  6826. return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16];
  6827. case GGML_GLU_OP_GEGLU_ERF:
  6828. return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16];
  6829. case GGML_GLU_OP_GEGLU_QUICK:
  6830. return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16];
  6831. default:
  6832. break;
  6833. }
  6834. return nullptr;
  6835. case GGML_OP_DIAG_MASK_INF:
  6836. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6837. return ctx->device->pipeline_diag_mask_inf_f32;
  6838. }
  6839. return nullptr;
  6840. case GGML_OP_SOFT_MAX:
  6841. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  6842. GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32);
  6843. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  6844. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  6845. }
  6846. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  6847. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  6848. }
  6849. return nullptr;
  6850. case GGML_OP_SOFT_MAX_BACK:
  6851. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6852. return ctx->device->pipeline_soft_max_back_f32;
  6853. }
  6854. return nullptr;
  6855. case GGML_OP_ROPE:
  6856. case GGML_OP_ROPE_BACK:
  6857. {
  6858. const int mode = ((const int32_t *) dst->op_params)[2];
  6859. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  6860. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  6861. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  6862. if (is_neox) {
  6863. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6864. return ctx->device->pipeline_rope_neox_f32;
  6865. }
  6866. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6867. return ctx->device->pipeline_rope_neox_f16;
  6868. }
  6869. } else if (is_mrope && !is_vision) {
  6870. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6871. return ctx->device->pipeline_rope_multi_f32;
  6872. }
  6873. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6874. return ctx->device->pipeline_rope_multi_f16;
  6875. }
  6876. } else if (is_vision) {
  6877. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6878. return ctx->device->pipeline_rope_vision_f32;
  6879. }
  6880. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6881. return ctx->device->pipeline_rope_vision_f16;
  6882. }
  6883. } else {
  6884. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6885. return ctx->device->pipeline_rope_norm_f32;
  6886. }
  6887. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6888. return ctx->device->pipeline_rope_norm_f16;
  6889. }
  6890. }
  6891. return nullptr;
  6892. }
  6893. case GGML_OP_ARGSORT:
  6894. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  6895. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  6896. return ctx->device->pipeline_argsort_f32[idx];
  6897. }
  6898. return nullptr;
  6899. case GGML_OP_SUM:
  6900. case GGML_OP_SUM_ROWS:
  6901. case GGML_OP_MEAN:
  6902. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6903. return ctx->device->pipeline_sum_rows_f32;
  6904. }
  6905. return nullptr;
  6906. case GGML_OP_ARGMAX:
  6907. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  6908. return ctx->device->pipeline_argmax_f32;
  6909. }
  6910. return nullptr;
  6911. case GGML_OP_COUNT_EQUAL:
  6912. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) {
  6913. return ctx->device->pipeline_count_equal_i32;
  6914. }
  6915. return nullptr;
  6916. case GGML_OP_IM2COL:
  6917. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6918. return ctx->device->pipeline_im2col_f32;
  6919. }
  6920. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  6921. return ctx->device->pipeline_im2col_f32_f16;
  6922. }
  6923. return nullptr;
  6924. case GGML_OP_IM2COL_3D:
  6925. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6926. return ctx->device->pipeline_im2col_3d_f32;
  6927. }
  6928. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  6929. return ctx->device->pipeline_im2col_3d_f32_f16;
  6930. }
  6931. return nullptr;
  6932. case GGML_OP_TIMESTEP_EMBEDDING:
  6933. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6934. return ctx->device->pipeline_timestep_embedding_f32;
  6935. }
  6936. return nullptr;
  6937. case GGML_OP_CONV_TRANSPOSE_1D:
  6938. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6939. return ctx->device->pipeline_conv_transpose_1d_f32;
  6940. }
  6941. return nullptr;
  6942. case GGML_OP_POOL_2D:
  6943. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6944. return ctx->device->pipeline_pool2d_f32;
  6945. }
  6946. return nullptr;
  6947. case GGML_OP_RWKV_WKV6:
  6948. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6949. return ctx->device->pipeline_rwkv_wkv6_f32;
  6950. }
  6951. return nullptr;
  6952. case GGML_OP_RWKV_WKV7:
  6953. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6954. return ctx->device->pipeline_rwkv_wkv7_f32;
  6955. }
  6956. return nullptr;
  6957. case GGML_OP_OPT_STEP_ADAMW:
  6958. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6959. return ctx->device->pipeline_opt_step_adamw_f32;
  6960. }
  6961. return nullptr;
  6962. case GGML_OP_OPT_STEP_SGD:
  6963. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6964. return ctx->device->pipeline_opt_step_sgd_f32;
  6965. }
  6966. return nullptr;
  6967. case GGML_OP_LEAKY_RELU:
  6968. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6969. return ctx->device->pipeline_leaky_relu_f32;
  6970. }
  6971. return nullptr;
  6972. case GGML_OP_CONV_2D:
  6973. case GGML_OP_CONV_TRANSPOSE_2D:
  6974. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 &&
  6975. ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst)) {
  6976. std::array<uint32_t, 3> elements;
  6977. if (op == GGML_OP_CONV_2D) elements = ggml_vk_get_conv_elements(dst);
  6978. else if (op == GGML_OP_CONV_TRANSPOSE_2D) elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  6979. vk_conv_shapes shape;
  6980. uint32_t tiles[CONV_SHAPE_COUNT];
  6981. for (uint32_t i = 0; i < CONV_SHAPE_COUNT; ++i) {
  6982. 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]);
  6983. }
  6984. // We can't query number of shader cores on Intel, use 32 as a placeholder
  6985. // so small convolutions will still choose a smaller tile.
  6986. const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32;
  6987. if (elements[0] > 64 && tiles[CONV_SHAPE_128x128] >= shader_core_count * 2) {
  6988. shape = CONV_SHAPE_128x128;
  6989. } else if (elements[0] <= 32 && tiles[CONV_SHAPE_32x256] >= shader_core_count * 2) {
  6990. shape = CONV_SHAPE_32x256;
  6991. } else {
  6992. shape = CONV_SHAPE_64x32;
  6993. }
  6994. if (op == GGML_OP_CONV_2D) {
  6995. if (src0->type == GGML_TYPE_F32) {
  6996. return ctx->device->pipeline_conv2d_f32[shape];
  6997. } else if (src0->type == GGML_TYPE_F16) {
  6998. return ctx->device->pipeline_conv2d_f16_f32[shape];
  6999. }
  7000. } else if (op == GGML_OP_CONV_TRANSPOSE_2D) {
  7001. if (src0->type == GGML_TYPE_F32) {
  7002. return ctx->device->pipeline_conv_transpose_2d_f32[shape];
  7003. } else if (src0->type == GGML_TYPE_F16) {
  7004. return ctx->device->pipeline_conv_transpose_2d_f16_f32[shape];
  7005. }
  7006. }
  7007. }
  7008. return nullptr;
  7009. case GGML_OP_CONV_2D_DW:
  7010. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7011. if (ggml_is_contiguous(src1)) {
  7012. return ctx->device->pipeline_conv2d_dw_whcn_f32;
  7013. } else if (ggml_is_contiguous_channels(src1)) {
  7014. return ctx->device->pipeline_conv2d_dw_cwhn_f32;
  7015. }
  7016. } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7017. if (ggml_is_contiguous(src1)) {
  7018. return ctx->device->pipeline_conv2d_dw_whcn_f16_f32;
  7019. } else if (ggml_is_contiguous_channels(src1)) {
  7020. return ctx->device->pipeline_conv2d_dw_cwhn_f16_f32;
  7021. }
  7022. }
  7023. return nullptr;
  7024. default:
  7025. return nullptr;
  7026. }
  7027. GGML_UNUSED(src2);
  7028. }
  7029. static bool ggml_vk_op_supports_incontiguous(ggml_op op) {
  7030. switch (op) {
  7031. case GGML_OP_CPY:
  7032. case GGML_OP_GET_ROWS:
  7033. case GGML_OP_ADD:
  7034. case GGML_OP_SUB:
  7035. case GGML_OP_MUL:
  7036. case GGML_OP_DIV:
  7037. case GGML_OP_ADD_ID:
  7038. case GGML_OP_CONCAT:
  7039. case GGML_OP_UPSCALE:
  7040. case GGML_OP_SQR:
  7041. case GGML_OP_SQRT:
  7042. case GGML_OP_SIN:
  7043. case GGML_OP_COS:
  7044. case GGML_OP_CLAMP:
  7045. case GGML_OP_PAD:
  7046. case GGML_OP_REPEAT:
  7047. case GGML_OP_REPEAT_BACK:
  7048. case GGML_OP_ROPE:
  7049. case GGML_OP_RMS_NORM:
  7050. case GGML_OP_CONV_2D_DW:
  7051. case GGML_OP_IM2COL:
  7052. case GGML_OP_IM2COL_3D:
  7053. case GGML_OP_SET_ROWS:
  7054. case GGML_OP_SUM:
  7055. case GGML_OP_SUM_ROWS:
  7056. case GGML_OP_MEAN:
  7057. return true;
  7058. default:
  7059. return false;
  7060. }
  7061. }
  7062. static uint32_t get_misalign_bytes(ggml_backend_vk_context * ctx, const ggml_tensor * t)
  7063. {
  7064. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  7065. }
  7066. 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) {
  7067. GGML_UNUSED(p);
  7068. GGML_UNUSED(src0);
  7069. GGML_UNUSED(src1);
  7070. GGML_UNUSED(src2);
  7071. GGML_UNUSED(dst);
  7072. static_assert(!std::is_const<T>::value, "unexpected type");
  7073. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  7074. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  7075. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  7076. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  7077. }
  7078. 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) {
  7079. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7080. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7081. p.misalign_offsets = (a_offset << 16) | d_offset;
  7082. GGML_UNUSED(src1);
  7083. GGML_UNUSED(src2);
  7084. }
  7085. 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) {
  7086. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7087. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7088. p.misalign_offsets = (a_offset << 16) | d_offset;
  7089. GGML_UNUSED(src1);
  7090. GGML_UNUSED(src2);
  7091. }
  7092. 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) {
  7093. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7094. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7095. p.misalign_offsets = (a_offset << 16) | d_offset;
  7096. GGML_UNUSED(src1);
  7097. GGML_UNUSED(src2);
  7098. }
  7099. 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) {
  7100. const uint32_t a_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7101. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7102. p.misalign_offsets = (a_offset << 16) | d_offset;
  7103. GGML_UNUSED(src0);
  7104. GGML_UNUSED(src2);
  7105. }
  7106. 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) {
  7107. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7108. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7109. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7110. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  7111. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  7112. GGML_UNUSED(src2);
  7113. }
  7114. 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) {
  7115. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7116. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7117. p.a_offset = a_offset;
  7118. p.d_offset = d_offset;
  7119. GGML_UNUSED(src1);
  7120. GGML_UNUSED(src2);
  7121. }
  7122. template<typename PC>
  7123. 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) {
  7124. 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];
  7125. if (src1 != nullptr) {
  7126. 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];
  7127. }
  7128. if (src2 != nullptr) {
  7129. 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];
  7130. }
  7131. 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];
  7132. std::cerr << "), " << ggml_op_name(op) << ", " << (dryrun ? "dryrun" : "") << ")");
  7133. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  7134. GGML_ASSERT(ggml_vk_op_supports_incontiguous(op) || ggml_vk_dim01_contiguous(src0)); // NOLINT
  7135. GGML_ASSERT(dst->buffer != nullptr);
  7136. const uint64_t ne00 = src0->ne[0];
  7137. const uint64_t ne01 = src0->ne[1];
  7138. const uint64_t ne02 = src0->ne[2];
  7139. const uint64_t ne03 = src0->ne[3];
  7140. const uint64_t ne0 = ne00 * ne01;
  7141. const bool use_src1 = src1 != nullptr;
  7142. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  7143. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  7144. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  7145. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  7146. const uint64_t ne1 = ne10 * ne11;
  7147. // const uint64_t nb10 = use_src1 ? src1->nb[0] : 0;
  7148. const bool use_src2 = src2 != nullptr;
  7149. const uint64_t ne20 = use_src2 ? src2->ne[0] : 0;
  7150. const uint64_t ne21 = use_src2 ? src2->ne[1] : 0;
  7151. const uint64_t ne22 = use_src2 ? src2->ne[2] : 0;
  7152. const uint64_t ne23 = use_src2 ? src2->ne[3] : 0;
  7153. const uint64_t ne2 = ne20 * ne21;
  7154. const uint64_t ned0 = dst->ne[0];
  7155. const uint64_t ned1 = dst->ne[1];
  7156. const uint64_t ned2 = dst->ne[2];
  7157. const uint64_t ned3 = dst->ne[3];
  7158. const uint64_t ned = ned0 * ned1;
  7159. init_pushconst_fastdiv(pc);
  7160. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  7161. if (pipeline == nullptr) {
  7162. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  7163. if (src1 != nullptr) {
  7164. std::cerr << " and " << ggml_type_name(src1->type);
  7165. }
  7166. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  7167. GGML_ABORT("fatal error");
  7168. }
  7169. if (dryrun) {
  7170. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7171. return;
  7172. }
  7173. const bool op_supports_incontiguous = ggml_vk_op_supports_incontiguous(op);
  7174. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  7175. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  7176. ggml_backend_vk_buffer_context * src1_buf_ctx = use_src1 ? (ggml_backend_vk_buffer_context *)src1->buffer->context : nullptr;
  7177. ggml_backend_vk_buffer_context * src2_buf_ctx = use_src2 ? (ggml_backend_vk_buffer_context *)src2->buffer->context : nullptr;
  7178. vk_buffer d_X = nullptr;
  7179. size_t x_buf_offset = 0;
  7180. vk_buffer d_Y = nullptr;
  7181. size_t y_buf_offset = 0;
  7182. vk_buffer d_Z = nullptr;
  7183. size_t z_buf_offset = 0;
  7184. bool src0_uma = false;
  7185. bool src1_uma = false;
  7186. bool src2_uma = false;
  7187. if (ctx->device->uma) {
  7188. ggml_vk_host_get(ctx->device, src0->data, d_X, x_buf_offset);
  7189. src0_uma = d_X != nullptr;
  7190. if (use_src1) {
  7191. ggml_vk_host_get(ctx->device, src1->data, d_Y, y_buf_offset);
  7192. src1_uma = d_Y != nullptr;
  7193. }
  7194. if (use_src2) {
  7195. ggml_vk_host_get(ctx->device, src2->data, d_Z, z_buf_offset);
  7196. src2_uma = d_Z != nullptr;
  7197. }
  7198. }
  7199. uint64_t x_sz = ggml_type_size(src0->type)/ggml_blck_size(src0->type) * ne0;
  7200. uint64_t y_sz = use_src1 ? ggml_type_size(src1->type) * ne1 : 0;
  7201. uint64_t z_sz = use_src2 ? ggml_type_size(src2->type) * ne2 : 0;
  7202. uint64_t d_sz = ggml_type_size(dst->type) * ned;
  7203. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  7204. // Workaround for tiny tensor inputs on ROPE
  7205. if (op == GGML_OP_ROPE && use_src1 && y_sz > d_D->size) {
  7206. y_sz = VK_WHOLE_SIZE;
  7207. }
  7208. GGML_ASSERT(d_D != nullptr);
  7209. uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  7210. if(!src0_uma) {
  7211. d_X = src0_buf_ctx->dev_buffer;
  7212. x_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  7213. GGML_ASSERT(d_X != nullptr);
  7214. }
  7215. if (use_src1 && !src1_uma) {
  7216. d_Y = src1_buf_ctx->dev_buffer;
  7217. y_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  7218. GGML_ASSERT(d_Y != nullptr);
  7219. }
  7220. if (use_src2 && !src2_uma) {
  7221. d_Z = src2_buf_ctx->dev_buffer;
  7222. z_buf_offset = vk_tensor_offset(src2) + src2->view_offs;
  7223. GGML_ASSERT(d_Z != nullptr);
  7224. }
  7225. // Compute misalignment offset for descriptors and store it in in push constants, then align the descriptor offsets.
  7226. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, dst);
  7227. x_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7228. y_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7229. z_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7230. d_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  7231. if (op_supports_incontiguous) {
  7232. x_sz = ggml_nbytes(src0) + get_misalign_bytes(ctx, src0);
  7233. y_sz = use_src1 ? ggml_nbytes(src1) + get_misalign_bytes(ctx, src1) : 0;
  7234. z_sz = use_src2 ? ggml_nbytes(src2) + get_misalign_bytes(ctx, src2) : 0;
  7235. d_sz = ggml_nbytes(dst) + get_misalign_bytes(ctx, dst);
  7236. if (x_buf_offset + x_sz >= d_X->size) {
  7237. x_sz = VK_WHOLE_SIZE;
  7238. }
  7239. if (use_src1 && y_buf_offset + y_sz >= d_Y->size) {
  7240. y_sz = VK_WHOLE_SIZE;
  7241. }
  7242. if (use_src2 && z_buf_offset + z_sz >= d_Z->size) {
  7243. z_sz = VK_WHOLE_SIZE;
  7244. }
  7245. if (d_buf_offset + d_sz >= d_D->size) {
  7246. d_sz = VK_WHOLE_SIZE;
  7247. }
  7248. }
  7249. std::array<uint32_t, 3> elements;
  7250. // Single call if dimension 2 is contiguous
  7251. GGML_ASSERT(op_supports_incontiguous || (ggml_is_contiguous(src0) && (src1 == nullptr || ggml_is_contiguous(src1))));
  7252. switch (op) {
  7253. case GGML_OP_NORM:
  7254. case GGML_OP_RMS_NORM_BACK:
  7255. case GGML_OP_L2_NORM:
  7256. case GGML_OP_SOFT_MAX:
  7257. case GGML_OP_SOFT_MAX_BACK:
  7258. case GGML_OP_SUM_ROWS:
  7259. case GGML_OP_MEAN:
  7260. case GGML_OP_ARGMAX:
  7261. {
  7262. const uint32_t nr = ggml_nrows(src0);
  7263. if (nr > 262144) {
  7264. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7265. } else if (nr > 512) {
  7266. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7267. } else {
  7268. elements = { nr, 1, 1 };
  7269. }
  7270. } break;
  7271. case GGML_OP_RMS_NORM:
  7272. if (ctx->do_add_rms_partials) {
  7273. // Run one element per thread, 128 threads per workgroup
  7274. elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 };
  7275. } else {
  7276. elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 };
  7277. }
  7278. break;
  7279. case GGML_OP_SUM:
  7280. // We use GGML_OP_SUM_ROWS with 1 row.
  7281. elements = { 1, 1, 1 };
  7282. break;
  7283. case GGML_OP_GROUP_NORM:
  7284. {
  7285. const uint32_t num_groups = dst->op_params[0];
  7286. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  7287. } break;
  7288. case GGML_OP_DIAG_MASK_INF:
  7289. case GGML_OP_ROPE:
  7290. case GGML_OP_ROPE_BACK:
  7291. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  7292. break;
  7293. case GGML_OP_GET_ROWS:
  7294. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  7295. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7296. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7297. break;
  7298. case GGML_OP_ARGSORT:
  7299. elements = { (uint32_t)ne00, (uint32_t)ggml_nrows(src0), 1 };
  7300. break;
  7301. case GGML_OP_IM2COL:
  7302. {
  7303. const bool is_2D = dst->op_params[6] == 1;
  7304. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  7305. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  7306. const uint32_t KW = src0->ne[0];
  7307. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  7308. const uint32_t OW = dst->ne[1];
  7309. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  7310. elements = { OW * KW * KH, OH, batch * IC };
  7311. } break;
  7312. case GGML_OP_IM2COL_3D:
  7313. {
  7314. const uint32_t IC = ((const uint32_t *)(dst->op_params))[9];
  7315. const uint32_t N = ne13 / IC;
  7316. const uint32_t KD = ne02;
  7317. const uint32_t KH = ne01;
  7318. const uint32_t KW = ne00;
  7319. const uint32_t OD = ned3 / N;
  7320. const uint32_t OH = ned2;
  7321. const uint32_t OW = ned1;
  7322. const uint32_t IC_KD_KH_KW = IC*KD*KH*KW;
  7323. const uint32_t N_OD_OH = N*OD*OH;
  7324. elements = { IC_KD_KH_KW, OW, N_OD_OH };
  7325. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7326. } break;
  7327. case GGML_OP_TIMESTEP_EMBEDDING:
  7328. {
  7329. const uint32_t dim = dst->op_params[0];
  7330. uint32_t half_ceil = (dim + 1) / 2;
  7331. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  7332. } break;
  7333. case GGML_OP_CONV_TRANSPOSE_1D:
  7334. {
  7335. elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1}
  7336. } break;
  7337. case GGML_OP_POOL_2D:
  7338. {
  7339. const uint32_t N = dst->ne[3];
  7340. const uint32_t OC = dst->ne[2];
  7341. const uint32_t OH = dst->ne[1];
  7342. const uint32_t OW = dst->ne[0];
  7343. elements = { N * OC * OH * OW, 1, 1};
  7344. } break;
  7345. case GGML_OP_CONV_2D:
  7346. {
  7347. elements = ggml_vk_get_conv_elements(dst);
  7348. } break;
  7349. case GGML_OP_CONV_TRANSPOSE_2D:
  7350. {
  7351. elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  7352. } break;
  7353. case GGML_OP_ADD:
  7354. case GGML_OP_SUB:
  7355. case GGML_OP_DIV:
  7356. case GGML_OP_MUL:
  7357. case GGML_OP_SCALE:
  7358. case GGML_OP_SQR:
  7359. case GGML_OP_SQRT:
  7360. case GGML_OP_SIN:
  7361. case GGML_OP_COS:
  7362. case GGML_OP_CLAMP:
  7363. case GGML_OP_PAD:
  7364. case GGML_OP_ROLL:
  7365. case GGML_OP_REPEAT:
  7366. case GGML_OP_REPEAT_BACK:
  7367. case GGML_OP_CPY:
  7368. case GGML_OP_CONCAT:
  7369. case GGML_OP_UPSCALE:
  7370. case GGML_OP_UNARY:
  7371. case GGML_OP_GLU:
  7372. case GGML_OP_CONV_2D_DW:
  7373. {
  7374. uint32_t ne = ggml_nelements(dst);
  7375. if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7376. // Convert from number of logical elements to 2- or 4-byte units.
  7377. ne /= ggml_blck_size(src0->type);
  7378. if ((ggml_type_size(src0->type) % 4) == 0) {
  7379. ne *= ggml_type_size(src0->type) / 4;
  7380. } else {
  7381. ne *= ggml_type_size(src0->type) / 2;
  7382. }
  7383. }
  7384. // copy_to_quant has block size of 32, and each thread does QUANT_K elements.
  7385. // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements.
  7386. // So divide by block size here before splitting into 512x512 groups.
  7387. if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7388. ne = CEIL_DIV(ne, ggml_blck_size(dst->type));
  7389. }
  7390. if (ne > 262144) {
  7391. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7392. } else if (ne > 512) {
  7393. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7394. } else {
  7395. elements = { ne, 1, 1 };
  7396. }
  7397. } break;
  7398. case GGML_OP_ADD_ID:
  7399. {
  7400. elements = { (uint32_t)ne01, (uint32_t)ne02, 1 };
  7401. } break;
  7402. case GGML_OP_SET_ROWS:
  7403. {
  7404. uint32_t ne = ggml_nelements(src0);
  7405. if (ggml_is_quantized(dst->type)) {
  7406. // quants run 32 threads each doing QUANT_K elements
  7407. ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type));
  7408. } else {
  7409. // scalar types do one element per thread, running 512 threads
  7410. ne = CEIL_DIV(ne, 512);
  7411. }
  7412. if (ne > 262144) {
  7413. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7414. } else if (ne > 512) {
  7415. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7416. } else {
  7417. elements = { ne, 1, 1 };
  7418. }
  7419. }
  7420. break;
  7421. default:
  7422. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  7423. break;
  7424. }
  7425. if (!op_supports_incontiguous) {
  7426. if (x_sz != VK_WHOLE_SIZE) {
  7427. x_sz *= ne02 * ne03;
  7428. }
  7429. if (use_src1 && y_sz != VK_WHOLE_SIZE) {
  7430. y_sz *= ne12 * ne13;
  7431. }
  7432. if (use_src2 && z_sz != VK_WHOLE_SIZE) {
  7433. z_sz *= ne22 * ne23;
  7434. }
  7435. if (d_sz != VK_WHOLE_SIZE) {
  7436. d_sz *= ned2 * ned3;
  7437. }
  7438. }
  7439. if (op == GGML_OP_ADD || op == GGML_OP_RMS_NORM) {
  7440. vk_buffer d_A = ctx->do_add_rms_partials ? ctx->prealloc_add_rms_partials : d_X;
  7441. size_t a_buf_offset = ctx->do_add_rms_partials ? ctx->prealloc_size_add_rms_partials_offset : 0;
  7442. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7443. { vk_subbuffer{ d_X, x_buf_offset, x_sz },
  7444. vk_subbuffer{ d_Y, y_buf_offset, y_sz },
  7445. vk_subbuffer{ d_D, d_buf_offset, d_sz },
  7446. vk_subbuffer{ d_A, a_buf_offset, VK_WHOLE_SIZE },
  7447. }, pc, elements);
  7448. } else if (op == GGML_OP_GLU) {
  7449. // Empty src1 is possible in glu, but the shader needs a buffer
  7450. vk_subbuffer subbuf_y;
  7451. if (use_src1) {
  7452. subbuf_y = { d_Y, y_buf_offset, y_sz };
  7453. } else {
  7454. subbuf_y = { d_X, 0, x_sz };
  7455. }
  7456. 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);
  7457. } else if (op == GGML_OP_SOFT_MAX) {
  7458. // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer
  7459. vk_subbuffer subbuf_y;
  7460. if (use_src1) {
  7461. subbuf_y = { d_Y, y_buf_offset, y_sz };
  7462. } else {
  7463. subbuf_y = { d_X, 0, x_sz };
  7464. }
  7465. vk_subbuffer subbuf_z;
  7466. if (use_src2) {
  7467. subbuf_z = { d_Z, z_buf_offset, z_sz };
  7468. } else {
  7469. subbuf_z = { d_X, 0, x_sz };
  7470. }
  7471. 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);
  7472. } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) {
  7473. // Empty src2 is possible in rope, but the shader needs a buffer
  7474. vk_subbuffer subbuf_z;
  7475. if (use_src2) {
  7476. subbuf_z = { d_Z, z_buf_offset, z_sz };
  7477. } else {
  7478. subbuf_z = { d_X, 0, x_sz };
  7479. }
  7480. 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);
  7481. } else if (op == GGML_OP_IM2COL || op == GGML_OP_IM2COL_3D) {
  7482. if (ctx->device->shader_int64 && ctx->device->buffer_device_address) {
  7483. // buffer device address path doesn't use dst buffer
  7484. d_sz = 1;
  7485. }
  7486. // im2col uses only src1 and dst buffers
  7487. 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);
  7488. } else if (op == GGML_OP_COUNT_EQUAL) {
  7489. // count_equal assumes that destination buffer is initialized with zeroes
  7490. ggml_vk_buffer_memset_async(subctx, d_D, d_buf_offset, 0, d_sz);
  7491. ggml_vk_sync_buffers(ctx, subctx);
  7492. 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);
  7493. } else if (op == GGML_OP_OPT_STEP_SGD) {
  7494. // OPT_STEP_SGD works on src0, it does not need dst
  7495. 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);
  7496. } else if (use_src2) {
  7497. 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);
  7498. } else if (use_src1) {
  7499. 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);
  7500. } else {
  7501. 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);
  7502. }
  7503. }
  7504. 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) {
  7505. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7506. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7507. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7508. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_GET_ROWS, {
  7509. (uint32_t)ggml_nelements(src0),
  7510. (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,
  7511. (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,
  7512. (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,
  7513. 0,
  7514. 0.0f, 0.0f, 0,
  7515. }, dryrun);
  7516. }
  7517. 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) {
  7518. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7519. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7520. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7521. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  7522. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  7523. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  7524. int offset = dst->op_params[3] / 4; // offset in bytes
  7525. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ACC, {
  7526. (uint32_t)ggml_nelements(src0),
  7527. (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,
  7528. (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,
  7529. (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,
  7530. 0,
  7531. 0.0f, 0.0f, offset,
  7532. }, dryrun);
  7533. }
  7534. static void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx, bool dryrun = false) {
  7535. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  7536. const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  7537. // Make a list of all the tensors used by the op.
  7538. // Last element of the list is the dest tensor.
  7539. const ggml_tensor *tensors[MAX_PARAMETER_COUNT];
  7540. uint32_t num_srcs = ctx->num_additional_fused_ops + 2;
  7541. uint32_t num_tensors = num_srcs + 1;
  7542. GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT);
  7543. tensors[0] = first_node->src[0];
  7544. tensors[1] = first_node->src[1];
  7545. for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) {
  7546. // check whether the previous result is src[0] or src[1]
  7547. if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) {
  7548. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1];
  7549. } else {
  7550. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0];
  7551. }
  7552. }
  7553. tensors[num_srcs] = dst;
  7554. vk_op_multi_add_push_constants pc;
  7555. pc.ne20 = (uint32_t)dst->ne[0];
  7556. pc.ne21 = (uint32_t)dst->ne[1];
  7557. pc.ne22 = (uint32_t)dst->ne[2];
  7558. pc.ne23 = (uint32_t)dst->ne[3];
  7559. for (uint32_t i = 0; i < num_tensors; ++i) {
  7560. const ggml_tensor *t = tensors[i];
  7561. pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float);
  7562. pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float);
  7563. pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float);
  7564. pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float);
  7565. }
  7566. pc.rms_partials = ctx->do_add_rms_partials;
  7567. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, tensors[0], tensors[1], nullptr, dst, dst->op);
  7568. if (pipeline == nullptr) {
  7569. std::cerr << "ggml_vulkan: Error: Missing multi_add";
  7570. GGML_ABORT("fatal error");
  7571. }
  7572. if (dryrun) {
  7573. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7574. return;
  7575. }
  7576. ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT];
  7577. vk_buffer buf[MAX_PARAMETER_COUNT];
  7578. size_t offset[MAX_PARAMETER_COUNT];
  7579. bool uma[MAX_PARAMETER_COUNT];
  7580. for (uint32_t i = 0; i < num_tensors; ++i) {
  7581. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  7582. buf[i] = nullptr;
  7583. offset[i] = 0;
  7584. uma[i] = false;
  7585. if (ctx->device->uma) {
  7586. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  7587. uma[i] = buf[i] != nullptr;
  7588. }
  7589. if (!uma[i]) {
  7590. buf[i] = buf_ctx[i]->dev_buffer;
  7591. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  7592. }
  7593. GGML_ASSERT(buf[i] != nullptr);
  7594. }
  7595. // If any remaining descriptors are unused, just point them at src[0]
  7596. for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) {
  7597. buf[i] = buf[0];
  7598. offset[i] = 0;
  7599. }
  7600. if (ctx->do_add_rms_partials) {
  7601. buf[num_tensors] = ctx->prealloc_add_rms_partials;
  7602. offset[num_tensors] = ctx->prealloc_size_add_rms_partials_offset;
  7603. }
  7604. std::array<uint32_t, 3> elements;
  7605. uint32_t ne = ggml_nelements(dst);
  7606. if (ne > 262144) {
  7607. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7608. } else if (ne > 512) {
  7609. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7610. } else {
  7611. elements = { ne, 1, 1 };
  7612. }
  7613. static_assert(MAX_PARAMETER_COUNT == 12);
  7614. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7615. {
  7616. vk_subbuffer{ buf[0], offset[0], VK_WHOLE_SIZE },
  7617. vk_subbuffer{ buf[1], offset[1], VK_WHOLE_SIZE },
  7618. vk_subbuffer{ buf[2], offset[2], VK_WHOLE_SIZE },
  7619. vk_subbuffer{ buf[3], offset[3], VK_WHOLE_SIZE },
  7620. vk_subbuffer{ buf[4], offset[4], VK_WHOLE_SIZE },
  7621. vk_subbuffer{ buf[5], offset[5], VK_WHOLE_SIZE },
  7622. vk_subbuffer{ buf[6], offset[6], VK_WHOLE_SIZE },
  7623. vk_subbuffer{ buf[7], offset[7], VK_WHOLE_SIZE },
  7624. vk_subbuffer{ buf[8], offset[8], VK_WHOLE_SIZE },
  7625. vk_subbuffer{ buf[9], offset[9], VK_WHOLE_SIZE },
  7626. vk_subbuffer{ buf[10], offset[10], VK_WHOLE_SIZE },
  7627. vk_subbuffer{ buf[11], offset[11], VK_WHOLE_SIZE },
  7628. }, pc, elements);
  7629. }
  7630. 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) {
  7631. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7632. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7633. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7634. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ADD, {
  7635. (uint32_t)ggml_nelements(src0),
  7636. (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,
  7637. (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,
  7638. (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,
  7639. 0,
  7640. 0.0f, 0.0f, ctx->do_add_rms_partials,
  7641. }, dryrun);
  7642. }
  7643. 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) {
  7644. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7645. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7646. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7647. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_SUB, {
  7648. (uint32_t)ggml_nelements(src0),
  7649. (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,
  7650. (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,
  7651. (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,
  7652. 0,
  7653. 0.0f, 0.0f, 0,
  7654. }, dryrun);
  7655. }
  7656. 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) {
  7657. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7658. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7659. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7660. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_MUL, {
  7661. (uint32_t)ggml_nelements(src0),
  7662. (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,
  7663. (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,
  7664. (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,
  7665. 0,
  7666. 0.0f, 0.0f, 0,
  7667. }, dryrun);
  7668. }
  7669. 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) {
  7670. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7671. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7672. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7673. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_DIV, {
  7674. (uint32_t)ggml_nelements(src0),
  7675. (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,
  7676. (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,
  7677. (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,
  7678. 0,
  7679. 0.0f, 0.0f, 0,
  7680. }, dryrun);
  7681. }
  7682. 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) {
  7683. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7684. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7685. const uint32_t src2_type_size = ggml_type_size(src2->type);
  7686. ggml_vk_op_f32<vk_op_add_id_push_constants>(ctx, subctx, src0, src1, src2, dst, GGML_OP_ADD_ID, {
  7687. (uint32_t)dst->ne[0],
  7688. (uint32_t)dst->ne[1],
  7689. (uint32_t)src0->nb[1] / src0_type_size,
  7690. (uint32_t)src0->nb[2] / src0_type_size,
  7691. (uint32_t)src1->nb[1] / src1_type_size,
  7692. (uint32_t)src2->nb[1] / src2_type_size,
  7693. }, dryrun);
  7694. }
  7695. 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) {
  7696. GGML_ASSERT(version == 6 || version == 7);
  7697. int num_srcs = version == 6 ? 6 : 7;
  7698. for (int i = 0; i < num_srcs; i++) {
  7699. GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type));
  7700. }
  7701. GGML_ASSERT(dst->buffer != nullptr);
  7702. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op);
  7703. GGML_ASSERT(pipeline != nullptr);
  7704. if (dryrun) {
  7705. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7706. return;
  7707. }
  7708. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  7709. ggml_backend_vk_buffer_context * src_buf_ctxs[7] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
  7710. for (int i = 0; i < num_srcs; i++) {
  7711. src_buf_ctxs[i] = (ggml_backend_vk_buffer_context *)dst->src[i]->buffer->context;
  7712. }
  7713. vk_buffer d_D = nullptr, d_srcs[7] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
  7714. size_t dst_offset = 0, src_offsets[7] = { 0, 0, 0, 0, 0, 0, 0 };
  7715. bool dst_uma = false, srcs_uma[7] = { false, false, false, false, false, false, false };
  7716. if (ctx->device->uma) {
  7717. for (int i = 0; i < num_srcs; i++) {
  7718. ggml_vk_host_get(ctx->device, dst->src[i]->data, d_srcs[i], src_offsets[i]);
  7719. srcs_uma[i] = d_srcs[i] != nullptr;
  7720. }
  7721. ggml_vk_host_get(ctx->device, dst->data, d_D, dst_offset);
  7722. dst_uma = d_D != nullptr;
  7723. }
  7724. uint64_t src_sizes[7] = { 0, 0, 0, 0, 0, 0, 0 };
  7725. for (int i = 0; i < num_srcs; i++) {
  7726. src_sizes[i] = ggml_nbytes(dst->src[i]);
  7727. if (!srcs_uma[i]) {
  7728. d_srcs[i] = src_buf_ctxs[i]->dev_buffer;
  7729. src_offsets[i] = vk_tensor_offset(dst->src[i]) + dst->src[i]->view_offs;
  7730. }
  7731. }
  7732. const uint64_t dst_size = ggml_nbytes(dst);
  7733. if (!dst_uma) {
  7734. d_D = dst_buf_ctx->dev_buffer;
  7735. dst_offset = vk_tensor_offset(dst) + dst->view_offs;
  7736. }
  7737. std::array<uint32_t, 3> elements = {
  7738. (uint32_t)(pc.B * pc.H),
  7739. 1,
  7740. 1
  7741. };
  7742. if (version == 6) {
  7743. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  7744. vk_subbuffer{ d_srcs[0], src_offsets[0], src_sizes[0] },
  7745. vk_subbuffer{ d_srcs[1], src_offsets[1], src_sizes[1] },
  7746. vk_subbuffer{ d_srcs[2], src_offsets[2], src_sizes[2] },
  7747. vk_subbuffer{ d_srcs[3], src_offsets[3], src_sizes[3] },
  7748. vk_subbuffer{ d_srcs[4], src_offsets[4], src_sizes[4] },
  7749. vk_subbuffer{ d_srcs[5], src_offsets[5], src_sizes[5] },
  7750. vk_subbuffer{ d_D, dst_offset, dst_size }
  7751. }, pc, elements);
  7752. } else if (version == 7) {
  7753. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  7754. vk_subbuffer{ d_srcs[0], src_offsets[0], src_sizes[0] },
  7755. vk_subbuffer{ d_srcs[1], src_offsets[1], src_sizes[1] },
  7756. vk_subbuffer{ d_srcs[2], src_offsets[2], src_sizes[2] },
  7757. vk_subbuffer{ d_srcs[3], src_offsets[3], src_sizes[3] },
  7758. vk_subbuffer{ d_srcs[4], src_offsets[4], src_sizes[4] },
  7759. vk_subbuffer{ d_srcs[5], src_offsets[5], src_sizes[5] },
  7760. vk_subbuffer{ d_srcs[6], src_offsets[6], src_sizes[6] },
  7761. vk_subbuffer{ d_D, dst_offset, dst_size }
  7762. }, pc, elements);
  7763. } else {
  7764. // shouldn't happen
  7765. GGML_ASSERT(false);
  7766. }
  7767. }
  7768. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  7769. const size_t seq_length = dst->src[0]->ne[2];
  7770. const size_t n_embed = dst->ne[0];
  7771. const size_t n_heads = dst->src[0]->ne[1];
  7772. const size_t n_seqs = dst->src[5]->ne[1];
  7773. ggml_vk_op_f32_wkv(
  7774. ctx, subctx, dst,
  7775. {
  7776. (uint32_t)n_seqs,
  7777. (uint32_t)seq_length,
  7778. (uint32_t)n_embed,
  7779. (uint32_t)n_heads,
  7780. },
  7781. 6,
  7782. dryrun
  7783. );
  7784. }
  7785. static void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  7786. const size_t seq_length = dst->src[0]->ne[2];
  7787. const size_t n_embed = dst->ne[0];
  7788. const size_t n_heads = dst->src[0]->ne[1];
  7789. const size_t n_seqs = dst->src[6]->ne[1];
  7790. ggml_vk_op_f32_wkv(
  7791. ctx, subctx, dst,
  7792. {
  7793. (uint32_t)n_seqs,
  7794. (uint32_t)seq_length,
  7795. (uint32_t)n_embed,
  7796. (uint32_t)n_heads,
  7797. },
  7798. 7,
  7799. dryrun
  7800. );
  7801. }
  7802. 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) {
  7803. const ggml_tensor * x = dst->src[0];
  7804. const ggml_tensor * g = dst->src[1];
  7805. const ggml_tensor * gm = dst->src[2];
  7806. const ggml_tensor * gv = dst->src[3];
  7807. const ggml_tensor * p = dst->src[4];
  7808. GGML_ASSERT(x->type == GGML_TYPE_F32);
  7809. GGML_ASSERT(g->type == GGML_TYPE_F32);
  7810. GGML_ASSERT(gm->type == GGML_TYPE_F32);
  7811. GGML_ASSERT(gv->type == GGML_TYPE_F32);
  7812. GGML_ASSERT(p->type == GGML_TYPE_F32);
  7813. GGML_ASSERT(dst->buffer != nullptr);
  7814. GGML_ASSERT(ggml_is_contiguous(x));
  7815. GGML_ASSERT(ggml_is_contiguous(g));
  7816. GGML_ASSERT(ggml_is_contiguous(gm));
  7817. GGML_ASSERT(ggml_is_contiguous(gv));
  7818. GGML_ASSERT(ggml_is_contiguous(p));
  7819. GGML_ASSERT(ggml_are_same_shape(x, g));
  7820. GGML_ASSERT(ggml_are_same_shape(x, gm));
  7821. GGML_ASSERT(ggml_are_same_shape(x, gv));
  7822. GGML_ASSERT(ggml_nelements(p) == 7);
  7823. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW);
  7824. GGML_ASSERT(pipeline != nullptr);
  7825. if (dryrun) {
  7826. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7827. return;
  7828. }
  7829. ggml_backend_vk_buffer_context * x_buf_ctx = (ggml_backend_vk_buffer_context *)x->buffer->context;
  7830. ggml_backend_vk_buffer_context * g_buf_ctx = (ggml_backend_vk_buffer_context *)g->buffer->context;
  7831. ggml_backend_vk_buffer_context * gm_buf_ctx = (ggml_backend_vk_buffer_context *)gm->buffer->context;
  7832. ggml_backend_vk_buffer_context * gv_buf_ctx = (ggml_backend_vk_buffer_context *)gv->buffer->context;
  7833. ggml_backend_vk_buffer_context * p_buf_ctx = (ggml_backend_vk_buffer_context *)p->buffer->context;
  7834. vk_buffer d_X = nullptr, d_G = nullptr, d_GM = nullptr, d_GV = nullptr, d_P = nullptr;
  7835. size_t x_offset = 0, g_offset = 0, gm_offset = 0, gv_offset = 0, p_offset = 0;
  7836. bool X_uma = false, G_uma = false, GM_uma = false, GV_uma = false, P_uma = false;
  7837. if (ctx->device->uma) {
  7838. ggml_vk_host_get(ctx->device, x->data, d_X, x_offset);
  7839. ggml_vk_host_get(ctx->device, g->data, d_G, g_offset);
  7840. ggml_vk_host_get(ctx->device, gm->data, d_GM, gm_offset);
  7841. ggml_vk_host_get(ctx->device, gv->data, d_GV, gv_offset);
  7842. ggml_vk_host_get(ctx->device, p->data, d_P, p_offset);
  7843. X_uma = d_X != nullptr;
  7844. G_uma = d_G != nullptr;
  7845. GM_uma = d_GM != nullptr;
  7846. GV_uma = d_GV != nullptr;
  7847. P_uma = d_P != nullptr;
  7848. }
  7849. if (!X_uma) {
  7850. d_X = x_buf_ctx->dev_buffer;
  7851. x_offset = vk_tensor_offset(x) + x->view_offs;
  7852. }
  7853. if (!G_uma) {
  7854. d_G = g_buf_ctx->dev_buffer;
  7855. g_offset = vk_tensor_offset(g) + g->view_offs;
  7856. }
  7857. if (!GM_uma) {
  7858. d_GM = gm_buf_ctx->dev_buffer;
  7859. gm_offset = vk_tensor_offset(gm) + gm->view_offs;
  7860. }
  7861. if (!GV_uma) {
  7862. d_GV = gv_buf_ctx->dev_buffer;
  7863. gv_offset = vk_tensor_offset(gv) + gv->view_offs;
  7864. }
  7865. if (!P_uma) {
  7866. d_P = p_buf_ctx->dev_buffer;
  7867. p_offset = vk_tensor_offset(p) + p->view_offs;
  7868. }
  7869. const uint64_t x_size = ggml_nbytes(x);
  7870. const uint64_t g_size = ggml_nbytes(g);
  7871. const uint64_t gm_size = ggml_nbytes(gm);
  7872. const uint64_t gv_size = ggml_nbytes(gv);
  7873. const uint64_t p_size = ggml_nbytes(p);
  7874. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(x), 1, 1 };
  7875. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  7876. vk_subbuffer{ d_X, x_offset, x_size },
  7877. vk_subbuffer{ d_G, g_offset, g_size },
  7878. vk_subbuffer{ d_GM, gm_offset, gm_size },
  7879. vk_subbuffer{ d_GV, gv_offset, gv_size },
  7880. vk_subbuffer{ d_P, p_offset, p_size },
  7881. }, pc, elements);
  7882. }
  7883. static void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  7884. const size_t n = ggml_nelements(dst->src[0]);
  7885. ggml_vk_op_f32_opt_step_adamw(
  7886. ctx, subctx, dst,
  7887. { (uint32_t)n, 0, 0.0f, 0.0f },
  7888. dryrun
  7889. );
  7890. }
  7891. 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) {
  7892. const size_t n = ggml_nelements(dst->src[0]);
  7893. 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);
  7894. }
  7895. 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) {
  7896. int * op_params = (int *)dst->op_params;
  7897. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7898. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7899. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7900. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONCAT, {
  7901. (uint32_t)ggml_nelements(dst),
  7902. (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,
  7903. (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,
  7904. (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,
  7905. 0,
  7906. 0.0f, 0.0f, op_params[0],
  7907. }, dryrun);
  7908. }
  7909. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7910. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7911. const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0);
  7912. float sf0 = (float)dst->ne[0] / src0->ne[0];
  7913. float sf1 = (float)dst->ne[1] / src0->ne[1];
  7914. float sf2 = (float)dst->ne[2] / src0->ne[2];
  7915. float sf3 = (float)dst->ne[3] / src0->ne[3];
  7916. if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) {
  7917. sf0 = (float)(dst->ne[0] - 1) / (src0->ne[0] - 1);
  7918. sf1 = (float)(dst->ne[1] - 1) / (src0->ne[1] - 1);
  7919. }
  7920. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  7921. (uint32_t)ggml_nelements(dst), 0, 0,
  7922. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1],
  7923. (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,
  7924. (uint32_t)dst->ne[0], (uint32_t)dst->ne[1], (uint32_t)dst->ne[2],(uint32_t)dst->ne[3],
  7925. sf0, sf1, sf2, sf3,
  7926. }, dryrun);
  7927. }
  7928. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7929. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  7930. p.param1 = ggml_get_op_params_f32(dst, 0);
  7931. p.param2 = ggml_get_op_params_f32(dst, 1);
  7932. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p), dryrun);
  7933. }
  7934. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7935. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst), dryrun);
  7936. }
  7937. static void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7938. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst), dryrun);
  7939. }
  7940. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7941. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst), dryrun);
  7942. }
  7943. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7944. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst), dryrun);
  7945. }
  7946. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7947. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  7948. p.param1 = ggml_get_op_params_f32(dst, 0);
  7949. p.param2 = ggml_get_op_params_f32(dst, 1);
  7950. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p), dryrun);
  7951. }
  7952. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7953. vk_op_pad_push_constants p = vk_op_pad_push_constants_init(src0, dst);
  7954. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p), dryrun);
  7955. }
  7956. static void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7957. const int32_t s0 = ggml_get_op_params_i32(dst, 0);
  7958. const int32_t s1 = ggml_get_op_params_i32(dst, 1);
  7959. const int32_t s2 = ggml_get_op_params_i32(dst, 2);
  7960. const int32_t s3 = ggml_get_op_params_i32(dst, 3);
  7961. const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
  7962. const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
  7963. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  7964. memcpy(&p.param1, &s01_packed, sizeof(float));
  7965. memcpy(&p.param2, &s23_packed, sizeof(float));
  7966. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p), dryrun);
  7967. }
  7968. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7969. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  7970. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p), dryrun);
  7971. }
  7972. static void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7973. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  7974. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p), dryrun);
  7975. }
  7976. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7977. uint32_t ne = (uint32_t)ggml_nelements(src0);
  7978. if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7979. // Convert from number of logical elements to 2- or 4-byte units.
  7980. ne /= ggml_blck_size(src0->type);
  7981. if ((ggml_type_size(src0->type) % 4) == 0) {
  7982. ne *= ggml_type_size(src0->type) / 4;
  7983. } else {
  7984. ne *= ggml_type_size(src0->type) / 2;
  7985. }
  7986. }
  7987. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne);
  7988. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p), dryrun);
  7989. }
  7990. 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) {
  7991. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7992. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7993. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7994. // Skip empty skip_rows operations. For most ops the empty check at the start
  7995. // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst
  7996. // with empty srcs.
  7997. if (ggml_is_empty(src0) || ggml_is_empty(src1)) {
  7998. return;
  7999. }
  8000. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_SET_ROWS, {
  8001. (uint32_t)ggml_nelements(src0),
  8002. (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,
  8003. (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,
  8004. (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,
  8005. 0,
  8006. 0.0f, 0.0f, 0,
  8007. }, dryrun);
  8008. }
  8009. 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) {
  8010. 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);
  8011. }
  8012. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8013. float * op_params = (float *)dst->op_params;
  8014. 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);
  8015. }
  8016. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8017. const int * int_op_params = (const int *)dst->op_params;
  8018. const float * float_op_params = (const float *)dst->op_params;
  8019. const uint32_t num_groups = int_op_params[0];
  8020. const float eps = float_op_params[1];
  8021. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  8022. 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);
  8023. }
  8024. static uint32_t ggml_vk_rms_num_partials(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8025. const uint32_t ne = (uint32_t)node->ne[0];
  8026. const uint32_t denom = ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0];
  8027. const uint32_t num_partials = CEIL_DIV(ne, denom);
  8028. return num_partials;
  8029. }
  8030. static uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8031. const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node);
  8032. const uint32_t num_bytes = ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment);
  8033. return num_bytes;
  8034. }
  8035. 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) {
  8036. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8037. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8038. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8039. uint32_t param3 = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0;
  8040. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_RMS_NORM, {
  8041. (uint32_t)ggml_nelements(src0),
  8042. (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,
  8043. (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,
  8044. (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,
  8045. 0,
  8046. op_params[0], 0.0f, (int32_t)param3,
  8047. }, dryrun);
  8048. if (ctx->do_add_rms_partials) {
  8049. ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0);
  8050. ctx->do_add_rms_partials = false;
  8051. }
  8052. }
  8053. 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) {
  8054. float * op_params = (float *)dst->op_params;
  8055. 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);
  8056. }
  8057. static void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8058. float * op_params = (float *)dst->op_params;
  8059. 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);
  8060. }
  8061. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8062. 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);
  8063. }
  8064. 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) {
  8065. const float * op_params_f = (const float *)dst->op_params;
  8066. const bool swapped = (bool)dst->op_params[1];
  8067. const bool split = src1 != nullptr;
  8068. const float alpha = op_params_f[2];
  8069. const float limit = op_params_f[3];
  8070. GGML_ASSERT(ggml_is_contiguous(src0));
  8071. if (!split) {
  8072. GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]);
  8073. } else {
  8074. GGML_ASSERT(src0->ne[0] == src1->ne[0]);
  8075. GGML_ASSERT(src0->ne[0] == dst->ne[0]);
  8076. GGML_ASSERT(src0->type == src1->type);
  8077. }
  8078. const uint32_t mode = split ? 2 : (swapped ? 1 : 0);
  8079. ggml_vk_op_f32<vk_op_glu_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_GLU,
  8080. {
  8081. (uint32_t)ggml_nelements(dst),
  8082. (uint32_t)src0->ne[0],
  8083. (uint32_t)dst->ne[0],
  8084. mode,
  8085. alpha,
  8086. limit
  8087. }, dryrun);
  8088. }
  8089. 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) {
  8090. int32_t * op_params = (int32_t *)dst->op_params;
  8091. 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);
  8092. }
  8093. 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) {
  8094. float * op_params = (float *)dst->op_params;
  8095. float scale = op_params[0];
  8096. float max_bias = op_params[1];
  8097. const uint32_t ncols = (uint32_t)src0->ne[0];
  8098. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  8099. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  8100. const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u;
  8101. const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u;
  8102. const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u;
  8103. const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u;
  8104. const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u;
  8105. const uint32_t n_head_kv = src0->ne[2];
  8106. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  8107. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  8108. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  8109. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, dst, GGML_OP_SOFT_MAX, {
  8110. ncols,
  8111. src1 != nullptr ? nrows_y : (uint32_t)0,
  8112. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],
  8113. ne12, ne13,
  8114. nb11, nb12, nb13,
  8115. scale, max_bias,
  8116. m0, m1,
  8117. n_head_log2,
  8118. nrows_x,
  8119. src2 != nullptr
  8120. }, dryrun);
  8121. }
  8122. 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) {
  8123. float * op_params = (float *)dst->op_params;
  8124. 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);
  8125. }
  8126. 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) {
  8127. const int n_dims = ((int32_t *) dst->op_params)[1];
  8128. const int mode = ((int32_t *) dst->op_params)[2];
  8129. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  8130. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  8131. const float freq_base = ((float *) dst->op_params)[5];
  8132. const float freq_scale = ((float *) dst->op_params)[6];
  8133. const float ext_factor = ((float *) dst->op_params)[7];
  8134. const float attn_factor = ((float *) dst->op_params)[8];
  8135. const float beta_fast = ((float *) dst->op_params)[9];
  8136. const float beta_slow = ((float *) dst->op_params)[10];
  8137. int sections[4] {};
  8138. if (mode & GGML_ROPE_TYPE_MROPE) {
  8139. memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4);
  8140. }
  8141. float corr_dims[2];
  8142. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8143. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  8144. uint32_t s1 = src0->nb[1] / ggml_type_size(src0->type);
  8145. uint32_t s2 = src0->nb[2] / ggml_type_size(src0->type);
  8146. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, dst, GGML_OP_ROPE, {
  8147. (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  8148. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  8149. src2 != nullptr, (uint32_t)src0->ne[2], s1, s2,
  8150. { sections[0], sections[1], sections[2], sections[3] }, backprop
  8151. }, dryrun);
  8152. }
  8153. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8154. int32_t * op_params = (int32_t *)dst->op_params;
  8155. uint32_t ncols = src0->ne[0];
  8156. ggml_vk_op_f32<vk_op_argsort_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_ARGSORT, {
  8157. ncols,
  8158. op_params[0],
  8159. }, dryrun);
  8160. }
  8161. static void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8162. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, ggml_nelements(src0));
  8163. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SUM, p, dryrun);
  8164. }
  8165. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8166. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8167. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, p, dryrun);
  8168. }
  8169. static void ggml_vk_mean(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8170. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8171. p.weight = 1.0f / (float)src0->ne[0];
  8172. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_MEAN, p, dryrun);
  8173. }
  8174. static void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8175. 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);
  8176. }
  8177. 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) {
  8178. 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);
  8179. }
  8180. 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) {
  8181. const int32_t s0 = dst->op_params[0];
  8182. const int32_t s1 = dst->op_params[1];
  8183. const int32_t p0 = dst->op_params[2];
  8184. const int32_t p1 = dst->op_params[3];
  8185. const int32_t d0 = dst->op_params[4];
  8186. const int32_t d1 = dst->op_params[5];
  8187. const bool is_2D = dst->op_params[6] == 1;
  8188. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  8189. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  8190. const uint32_t IW = src1->ne[0];
  8191. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  8192. const uint32_t KW = src0->ne[0];
  8193. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  8194. const uint32_t OW = dst->ne[1];
  8195. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  8196. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  8197. const uint32_t pelements = OW * KW * KH;
  8198. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8199. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  8200. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  8201. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_IM2COL, {
  8202. dst_addr,
  8203. batch_offset, offset_delta,
  8204. IC, IW, IH, OW, OH, KW, KH,
  8205. pelements,
  8206. IC * KH * KW,
  8207. s0, s1, p0, p1, d0, d1,
  8208. }, dryrun);
  8209. }
  8210. 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) {
  8211. GGML_TENSOR_BINARY_OP_LOCALS
  8212. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  8213. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  8214. const int32_t s2 = ((const int32_t *)(dst->op_params))[2];
  8215. const int32_t p0 = ((const int32_t *)(dst->op_params))[3];
  8216. const int32_t p1 = ((const int32_t *)(dst->op_params))[4];
  8217. const int32_t p2 = ((const int32_t *)(dst->op_params))[5];
  8218. const int32_t d0 = ((const int32_t *)(dst->op_params))[6];
  8219. const int32_t d1 = ((const int32_t *)(dst->op_params))[7];
  8220. const int32_t d2 = ((const int32_t *)(dst->op_params))[8];
  8221. const int32_t IC = ((const int32_t *)(dst->op_params))[9];
  8222. const int64_t N = ne13 / IC;
  8223. const int64_t ID = ne12;
  8224. const int64_t IH = ne11;
  8225. const int64_t IW = ne10;
  8226. const int64_t KD = ne02;
  8227. const int64_t KH = ne01;
  8228. const int64_t KW = ne00;
  8229. const int64_t OD = ne3 / N;
  8230. const int64_t OH = ne2;
  8231. const int64_t OW = ne1;
  8232. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8233. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  8234. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  8235. vk_op_im2col_3d_push_constants pc {};
  8236. pc.dst_addr = dst_addr;
  8237. pc.nb10 = nb10 / ggml_type_size(src1->type);
  8238. pc.nb11 = nb11 / ggml_type_size(src1->type);
  8239. pc.nb12 = nb12 / ggml_type_size(src1->type);
  8240. pc.nb13 = nb13 / ggml_type_size(src1->type);
  8241. pc.s0 = s0;
  8242. pc.s1 = s1;
  8243. pc.s2 = s2;
  8244. pc.p0 = p0;
  8245. pc.p1 = p1;
  8246. pc.p2 = p2;
  8247. pc.d0 = d0;
  8248. pc.d1 = d1;
  8249. pc.d2 = d2;
  8250. pc.IW = IW;
  8251. pc.IH = IH;
  8252. pc.ID = ID;
  8253. pc.IC = IC;
  8254. pc.KW = KW;
  8255. pc.OH = OH;
  8256. pc.KD_KH_KW = KD*KH*KW;
  8257. pc.KH_KW = KH*KW;
  8258. pc.IC_KD_KH_KW = IC*KD*KH*KW;
  8259. pc.N_OD_OH = N*OD*OH;
  8260. pc.OD_OH = OD*OH;
  8261. pc.OD_OH_OW_IC_KD_KH_KW = OD*OH*OW*IC*KD*KH*KW;
  8262. pc.OH_OW_IC_KD_KH_KW = OH*OW*IC*KD*KH*KW;
  8263. pc.OW_IC_KD_KH_KW = OW*IC*KD*KH*KW;
  8264. ggml_vk_op_f32<vk_op_im2col_3d_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_IM2COL_3D, std::move(pc), dryrun);
  8265. }
  8266. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8267. const uint32_t dim = dst->op_params[0];
  8268. const uint32_t max_period = dst->op_params[1];
  8269. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  8270. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  8271. nb1, dim, max_period,
  8272. }, dryrun);
  8273. }
  8274. 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) {
  8275. // src0: (K, Cout, Cin, 1) -- kernel
  8276. // src1: (L, Cin, 1, 1) -- input
  8277. // dst: (*, Cout, 1, 1)
  8278. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  8279. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8280. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  8281. GGML_TENSOR_BINARY_OP_LOCALS
  8282. GGML_ASSERT(nb00 == sizeof(float));
  8283. GGML_ASSERT(nb10 == sizeof(float));
  8284. const int32_t s0 = dst->op_params[0];
  8285. vk_op_conv_transpose_1d_push_constants p{};
  8286. p.Cout = static_cast<uint32_t>(ne01);
  8287. p.Cin = static_cast<uint32_t>(ne02);
  8288. p.K = static_cast<uint32_t>(ne00);
  8289. p.L = static_cast<uint32_t>(ne10);
  8290. p.KL = static_cast<uint32_t>(ne0);
  8291. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8292. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8293. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8294. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8295. p.s0 = static_cast<uint32_t>(s0);
  8296. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p), dryrun);
  8297. }
  8298. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8299. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  8300. const int32_t k1 = dst->op_params[1];
  8301. const int32_t k0 = dst->op_params[2];
  8302. const int32_t s1 = dst->op_params[3];
  8303. const int32_t s0 = dst->op_params[4];
  8304. const int32_t p1 = dst->op_params[5];
  8305. const int32_t p0 = dst->op_params[6];
  8306. const uint32_t IH = src0->ne[1];
  8307. const uint32_t IW = src0->ne[0];
  8308. const uint32_t N = dst->ne[3];
  8309. const uint32_t OC = dst->ne[2];
  8310. const uint32_t OH = dst->ne[1];
  8311. const uint32_t OW = dst->ne[0];
  8312. const uint32_t parallel_elements = N * OC * OH * OW;
  8313. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  8314. IW, IH, OW, OH, OC,
  8315. parallel_elements,
  8316. op,
  8317. k0, k1, s0, s1, p0, p1,
  8318. }, dryrun);
  8319. }
  8320. static void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8321. const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8322. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8323. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8324. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8325. GGML_TENSOR_BINARY_OP_LOCALS
  8326. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8327. GGML_ASSERT(nb10 == sizeof(float));
  8328. GGML_ASSERT(nb0 == sizeof(float));
  8329. vk_op_conv2d_push_constants p{};
  8330. p.Cout = static_cast<uint32_t>(ne03);
  8331. p.Cin = static_cast<uint32_t>(ne02);
  8332. p.N = static_cast<uint32_t>(ne13);
  8333. p.KW = static_cast<uint32_t>(ne00);
  8334. p.KH = static_cast<uint32_t>(ne01);
  8335. p.W = static_cast<uint32_t>(ne10);
  8336. p.H = static_cast<uint32_t>(ne11);
  8337. p.OW = static_cast<uint32_t>(ne0);
  8338. p.OH = static_cast<uint32_t>(ne1);
  8339. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8340. p.s1 = static_cast<uint32_t>(dst->op_params[1]);
  8341. p.p0 = static_cast<uint32_t>(dst->op_params[2]);
  8342. p.p1 = static_cast<uint32_t>(dst->op_params[3]);
  8343. p.d0 = static_cast<uint32_t>(dst->op_params[4]);
  8344. p.d1 = static_cast<uint32_t>(dst->op_params[5]);
  8345. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8346. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8347. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  8348. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8349. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  8350. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  8351. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8352. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  8353. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  8354. GGML_ASSERT(ne03 == ne2);
  8355. GGML_ASSERT(ne02 == ne12);
  8356. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONV_2D, std::move(p), dryrun);
  8357. }
  8358. static void ggml_vk_conv_transpose_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8359. const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  8360. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8361. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8362. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8363. GGML_TENSOR_BINARY_OP_LOCALS
  8364. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8365. GGML_ASSERT(nb10 == sizeof(float));
  8366. GGML_ASSERT(nb0 == sizeof(float));
  8367. vk_op_conv_transpose_2d_push_constants p{};
  8368. p.Cout = static_cast<uint32_t>(ne02);
  8369. p.Cin = static_cast<uint32_t>(ne03);
  8370. p.N = static_cast<uint32_t>(ne13);
  8371. p.KW = static_cast<uint32_t>(ne00);
  8372. p.KH = static_cast<uint32_t>(ne01);
  8373. p.W = static_cast<uint32_t>(ne10);
  8374. p.H = static_cast<uint32_t>(ne11);
  8375. p.OW = static_cast<uint32_t>(ne0);
  8376. p.OH = static_cast<uint32_t>(ne1);
  8377. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8378. p.s1 = static_cast<uint32_t>(dst->op_params[0]);
  8379. p.p0 = 0;
  8380. p.p1 = 0;
  8381. p.d0 = 1;
  8382. p.d1 = 1;
  8383. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8384. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8385. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  8386. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8387. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  8388. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  8389. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8390. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  8391. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  8392. GGML_ASSERT(ne02 == ne2);
  8393. GGML_ASSERT(ne03 == ne12);
  8394. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONV_TRANSPOSE_2D, std::move(p), dryrun);
  8395. }
  8396. 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) {
  8397. vk_op_conv2d_dw_push_constants p{};
  8398. p.ne = ggml_nelements(dst);
  8399. p.channels = dst->ne[2];
  8400. p.batches = dst->ne[3];
  8401. p.dst_w = dst->ne[0];
  8402. p.dst_h = dst->ne[1];
  8403. p.src_w = src1->ne[0];
  8404. p.src_h = src1->ne[1];
  8405. p.knl_w = src0->ne[0];
  8406. p.knl_h = src0->ne[1];
  8407. p.stride_x = dst->op_params[0];
  8408. p.stride_y = dst->op_params[1];
  8409. p.pad_x = dst->op_params[2];
  8410. p.pad_y = dst->op_params[3];
  8411. p.dilation_x = dst->op_params[4];
  8412. p.dilation_y = dst->op_params[5];
  8413. GGML_ASSERT(src0->ne[3] == p.channels);
  8414. GGML_ASSERT(src1->ne[3] == p.batches);
  8415. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p), dryrun);
  8416. }
  8417. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  8418. const float * op_params = (const float *)dst->op_params;
  8419. 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);
  8420. }
  8421. #ifdef GGML_VULKAN_RUN_TESTS
  8422. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  8423. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  8424. return;
  8425. }
  8426. i0 = std::max(i0, 5);
  8427. i1 = std::max(i1, 5);
  8428. i2 = std::max(i2, 0);
  8429. fprintf(stderr, " ");
  8430. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8431. fprintf(stderr, "%7d ", idx1);
  8432. }
  8433. fprintf(stderr, "\n");
  8434. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  8435. fprintf(stderr, "%7d: ", idx0);
  8436. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8437. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  8438. float val;
  8439. if (type == GGML_TYPE_F32) {
  8440. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  8441. } else if (type == GGML_TYPE_F16) {
  8442. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  8443. } else {
  8444. GGML_ABORT("fatal error");
  8445. }
  8446. fprintf(stderr, "% 7.2f ", val);
  8447. } else {
  8448. fprintf(stderr, " ");
  8449. }
  8450. }
  8451. fprintf(stderr, "\n");
  8452. }
  8453. }
  8454. template <typename X_TYPE, typename Y_TYPE>
  8455. 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) {
  8456. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  8457. const size_t x_ne = m * k * batch;
  8458. const size_t y_ne = k * n * batch;
  8459. const size_t d_ne = m * n * batch;
  8460. vk_pipeline p;
  8461. std::string shname;
  8462. if (shader_size == 0) {
  8463. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8464. p = ctx->device->pipeline_matmul_f32->a_s;
  8465. shname = "F32_ALIGNED_S";
  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->a_s;
  8468. shname = "F32_F16_ALIGNED_S";
  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->a_s;
  8471. shname = "F16_F32_ALIGNED_S";
  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->a_s;
  8474. shname = "F16_ALIGNED_S";
  8475. } else {
  8476. GGML_ABORT("fatal error");
  8477. }
  8478. } else if (shader_size == 1) {
  8479. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8480. p = ctx->device->pipeline_matmul_f32->a_m;
  8481. shname = "F32_ALIGNED_M";
  8482. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8483. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  8484. shname = "F32_F16_ALIGNED_M";
  8485. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8486. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  8487. shname = "F16_F32_ALIGNED_M";
  8488. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8489. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  8490. shname = "F16_ALIGNED_M";
  8491. } else {
  8492. GGML_ABORT("fatal error");
  8493. }
  8494. } else if (shader_size == 2) {
  8495. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8496. p = ctx->device->pipeline_matmul_f32->a_l;
  8497. shname = "F32_ALIGNED_L";
  8498. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8499. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  8500. shname = "F32_F16_ALIGNED_L";
  8501. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8502. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  8503. shname = "F16_F32_ALIGNED_L";
  8504. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8505. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  8506. shname = "F16_ALIGNED_L";
  8507. } else {
  8508. GGML_ABORT("fatal error");
  8509. }
  8510. } else {
  8511. GGML_ASSERT(0);
  8512. }
  8513. const size_t kpad = ggml_vk_align_size(k, p->align);
  8514. if (k != kpad) {
  8515. if (shader_size == 0) {
  8516. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8517. p = ctx->device->pipeline_matmul_f32->s;
  8518. shname = "F32_S";
  8519. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8520. p = ctx->device->pipeline_matmul_f32_f16->s;
  8521. shname = "F32_F16_S";
  8522. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8523. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  8524. shname = "F16_F32_S";
  8525. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8526. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  8527. shname = "F16_S";
  8528. }
  8529. } else if (shader_size == 1) {
  8530. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8531. p = ctx->device->pipeline_matmul_f32->m;
  8532. shname = "F32_M";
  8533. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8534. p = ctx->device->pipeline_matmul_f32_f16->m;
  8535. shname = "F32_F16_M";
  8536. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8537. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  8538. shname = "F16_F32_M";
  8539. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8540. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  8541. shname = "F16_M";
  8542. }
  8543. } else if (shader_size == 2) {
  8544. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8545. p = ctx->device->pipeline_matmul_f32->l;
  8546. shname = "F32_L";
  8547. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8548. p = ctx->device->pipeline_matmul_f32_f16->l;
  8549. shname = "F32_F16_L";
  8550. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8551. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  8552. shname = "F16_F32_L";
  8553. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8554. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  8555. shname = "F16_L";
  8556. }
  8557. }
  8558. }
  8559. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  8560. if (split_k > 1) {
  8561. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  8562. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  8563. // Resize buffer
  8564. if (ctx->prealloc_split_k != nullptr) {
  8565. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  8566. }
  8567. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8568. }
  8569. }
  8570. if (ctx->device->need_compiles) {
  8571. ggml_vk_load_shaders(ctx->device);
  8572. }
  8573. ggml_pipeline_allocate_descriptor_sets(ctx);
  8574. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8575. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8576. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8577. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  8578. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  8579. float* d = (float *) malloc(sizeof(float) * d_ne);
  8580. for (size_t i = 0; i < x_ne; i++) {
  8581. if (std::is_same<float, X_TYPE>()) {
  8582. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  8583. // x[i] = 1.0f;
  8584. // x[i] = i + 1;
  8585. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  8586. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  8587. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  8588. // x[i] = ggml_fp32_to_fp16(1.0f);
  8589. // x[i] = ggml_fp32_to_fp16(i + 1);
  8590. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  8591. } else {
  8592. GGML_ABORT("fatal error");
  8593. }
  8594. }
  8595. for (size_t i = 0; i < y_ne; i++) {
  8596. if (std::is_same<float, Y_TYPE>()) {
  8597. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  8598. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  8599. // y[i] = i + 1;
  8600. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8601. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  8602. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  8603. // y[i] = ggml_fp32_to_fp16(i + 1);
  8604. } else {
  8605. GGML_ABORT("fatal error");
  8606. }
  8607. }
  8608. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  8609. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  8610. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  8611. ggml_vk_ctx_begin(ctx->device, subctx);
  8612. for (size_t i = 0; i < num_it; i++) {
  8613. ggml_vk_matmul(
  8614. 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),
  8615. m, n, k,
  8616. k, k, m, k*m, k*n, m*n,
  8617. split_k, batch, batch, batch, 1, 1, n
  8618. );
  8619. }
  8620. ggml_vk_ctx_end(subctx);
  8621. auto begin = std::chrono::high_resolution_clock::now();
  8622. ggml_vk_submit(subctx, ctx->fence);
  8623. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  8624. ctx->device->device.resetFences({ ctx->fence });
  8625. ggml_vk_queue_command_pools_cleanup(ctx->device);
  8626. auto end = std::chrono::high_resolution_clock::now();
  8627. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  8628. // copy dst to host
  8629. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  8630. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  8631. ggml_init_params iparams = {
  8632. /*.mem_size =*/ 1024*1024*1024,
  8633. /*.mem_buffer =*/ NULL,
  8634. /*.no_alloc =*/ true,
  8635. };
  8636. ggml_context * ggml_ctx = ggml_init(iparams);
  8637. ggml_type src0_type;
  8638. ggml_type src1_type;
  8639. if (std::is_same<float, X_TYPE>()) {
  8640. src0_type = GGML_TYPE_F32;
  8641. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  8642. src0_type = GGML_TYPE_F16;
  8643. } else {
  8644. GGML_ABORT("fatal error");
  8645. }
  8646. if (std::is_same<float, Y_TYPE>()) {
  8647. src1_type = GGML_TYPE_F32;
  8648. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8649. src1_type = GGML_TYPE_F16;
  8650. } else {
  8651. GGML_ABORT("fatal error");
  8652. }
  8653. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  8654. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  8655. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  8656. src0_ggml->data = x;
  8657. src1_ggml->data = y;
  8658. tensor_ggml->data = d_chk;
  8659. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  8660. ggml_build_forward_expand(cgraph, tensor_ggml);
  8661. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  8662. ggml_free(ggml_ctx);
  8663. double avg_err = 0.0;
  8664. int first_err_n = -1;
  8665. int first_err_m = -1;
  8666. int first_err_b = -1;
  8667. for (size_t i = 0; i < m*n*batch; i++) {
  8668. double err = std::fabs(d[i] - d_chk[i]);
  8669. avg_err += err;
  8670. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  8671. first_err_b = i / (m * n);
  8672. first_err_n = (i % (m * n)) / m;
  8673. first_err_m = (i % (m * n)) % m;
  8674. }
  8675. }
  8676. avg_err /= m * n;
  8677. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  8678. 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;
  8679. if (avg_err > 0.1 || std::isnan(avg_err)) {
  8680. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  8681. std::cerr << "Actual result: " << std::endl << std::endl;
  8682. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  8683. std::cerr << "Expected result: " << std::endl << std::endl;
  8684. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  8685. if (split_k > 1) {
  8686. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  8687. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  8688. std::cerr << "d_buf0: " << std::endl << std::endl;
  8689. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  8690. std::cerr << "d_buf1: " << std::endl << std::endl;
  8691. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  8692. std::cerr << "d_buf2: " << std::endl << std::endl;
  8693. 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);
  8694. std::cerr << "d_buf3: " << std::endl << std::endl;
  8695. 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);
  8696. free(split_k_buf);
  8697. }
  8698. }
  8699. free(d_chk);
  8700. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  8701. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  8702. ggml_vk_destroy_buffer(d_X);
  8703. ggml_vk_destroy_buffer(d_Y);
  8704. ggml_vk_destroy_buffer(d_D);
  8705. free(x);
  8706. free(y);
  8707. free(d);
  8708. }
  8709. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  8710. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  8711. return;
  8712. }
  8713. i0 = std::max(i0, 5);
  8714. i1 = std::max(i1, 5);
  8715. i2 = std::max(i2, 0);
  8716. i3 = std::max(i3, 0);
  8717. fprintf(stderr, " ");
  8718. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8719. fprintf(stderr, "%7d ", idx1);
  8720. }
  8721. fprintf(stderr, "\n");
  8722. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  8723. fprintf(stderr, "%7d: ", idx0);
  8724. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8725. 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]) {
  8726. float val;
  8727. if (tensor->type == GGML_TYPE_F32) {
  8728. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  8729. } else if (tensor->type == GGML_TYPE_F16) {
  8730. 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]));
  8731. } else {
  8732. GGML_ABORT("fatal error");
  8733. }
  8734. fprintf(stderr, "% 7.2f ", val);
  8735. } else {
  8736. fprintf(stderr, " ");
  8737. }
  8738. }
  8739. fprintf(stderr, "\n");
  8740. }
  8741. }
  8742. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  8743. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  8744. }
  8745. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  8746. if (quant == GGML_TYPE_F32) {
  8747. memcpy(to, from, sizeof(float) * ne);
  8748. return;
  8749. }
  8750. const auto * tt = ggml_get_type_traits(quant);
  8751. ggml_to_float_t dequant_fn = tt->to_float;
  8752. dequant_fn(from, to, ne);
  8753. }
  8754. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  8755. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  8756. const size_t x_sz = sizeof(float) * ne;
  8757. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  8758. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  8759. float * x = (float *) malloc(x_sz);
  8760. void * qx = malloc(qx_sz);
  8761. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8762. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8763. float * x_ref = (float *) malloc(x_sz);
  8764. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  8765. for (size_t i = 0; i < ne; i++) {
  8766. x[i] = rand() / (float)RAND_MAX;
  8767. }
  8768. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  8769. ggml_vk_quantize_data(x, qx, ne, quant);
  8770. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  8771. ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  8772. if (ctx->device->need_compiles) {
  8773. ggml_vk_load_shaders(ctx->device);
  8774. }
  8775. ggml_pipeline_allocate_descriptor_sets(ctx);
  8776. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  8777. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  8778. ggml_vk_ctx_begin(ctx->device, subctx);
  8779. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  8780. 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});
  8781. ggml_vk_ctx_end(subctx);
  8782. auto begin = std::chrono::high_resolution_clock::now();
  8783. ggml_vk_submit(subctx, ctx->fence);
  8784. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  8785. ctx->device->device.resetFences({ ctx->fence });
  8786. ggml_vk_queue_command_pools_cleanup(ctx->device);
  8787. auto end = std::chrono::high_resolution_clock::now();
  8788. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  8789. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  8790. int first_err = -1;
  8791. double avg_err = 0.0;
  8792. for (size_t i = 0; i < ne; i++) {
  8793. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  8794. avg_err += error;
  8795. if (first_err < 0 && error > 0.05) {
  8796. first_err = i;
  8797. }
  8798. }
  8799. avg_err /= ne;
  8800. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  8801. if (avg_err > 0.1) {
  8802. std::cerr << "first_error = " << first_err << std::endl;
  8803. std::cerr << "Actual result: " << std::endl << std::endl;
  8804. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  8805. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  8806. }
  8807. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  8808. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  8809. std::cerr << x_ref[i] << ", ";
  8810. }
  8811. std::cerr << std::endl;
  8812. }
  8813. ggml_vk_destroy_buffer(x_buf);
  8814. ggml_vk_destroy_buffer(qx_buf);
  8815. free(x);
  8816. free(qx);
  8817. free(x_ref);
  8818. free(x_chk);
  8819. }
  8820. // This does not work without ggml q8_1 quantization support
  8821. //
  8822. // typedef uint16_t ggml_half;
  8823. // typedef uint32_t ggml_half2;
  8824. //
  8825. // #define QK8_1 32
  8826. // typedef struct {
  8827. // union {
  8828. // struct {
  8829. // ggml_half d; // delta
  8830. // ggml_half s; // d * sum(qs[i])
  8831. // } GGML_COMMON_AGGR_S;
  8832. // ggml_half2 ds;
  8833. // } GGML_COMMON_AGGR_U;
  8834. // int8_t qs[QK8_1]; // quants
  8835. // } block_q8_1;
  8836. //
  8837. // static void ggml_vk_test_quantize(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  8838. // VK_LOG_DEBUG("ggml_vk_test_quantize(" << ne << ")");
  8839. // GGML_ASSERT(quant == GGML_TYPE_Q8_1);
  8840. //
  8841. // const size_t x_sz = sizeof(float) * ne;
  8842. // const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  8843. // float * x = (float *) malloc(x_sz);
  8844. // block_q8_1 * qx = (block_q8_1 *)malloc(qx_sz);
  8845. // block_q8_1 * qx_res = (block_q8_1 *)malloc(qx_sz);
  8846. // vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8847. // vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8848. //
  8849. // for (size_t i = 0; i < ne; i++) {
  8850. // x[i] = rand() / (float)RAND_MAX;
  8851. // }
  8852. //
  8853. // vk_pipeline p = ggml_vk_get_quantize_pipeline(ctx, quant);
  8854. //
  8855. // ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  8856. //
  8857. // if (ctx->device->need_compiles) {
  8858. // ggml_vk_load_shaders(ctx->device);
  8859. // }
  8860. //
  8861. // ggml_pipeline_allocate_descriptor_sets(ctx);
  8862. //
  8863. // ggml_vk_buffer_write(x_buf, 0, x, x_sz);
  8864. //
  8865. // vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  8866. // ggml_vk_ctx_begin(ctx->device, subctx);
  8867. // ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(x_buf), ggml_vk_subbuffer(qx_buf), ne);
  8868. // ggml_vk_ctx_end(subctx);
  8869. //
  8870. // auto begin = std::chrono::high_resolution_clock::now();
  8871. //
  8872. // ggml_vk_submit(subctx, ctx->fence);
  8873. // VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_quantize waitForFences");
  8874. // ctx->device->device.resetFences({ ctx->fence });
  8875. // ggml_vk_queue_command_pools_cleanup(ctx->device);
  8876. //
  8877. // auto end = std::chrono::high_resolution_clock::now();
  8878. //
  8879. // double ms_quant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  8880. // ggml_vk_buffer_read(qx_buf, 0, qx, qx_sz);
  8881. //
  8882. // ggml_vk_quantize_data(x, qx_res, ne, quant);
  8883. //
  8884. // int first_err = -1;
  8885. //
  8886. // for (size_t i = 0; i < ne / 32; i++) {
  8887. // 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));
  8888. //
  8889. // if (first_err < 0 && error > 0.1) {
  8890. // first_err = i;
  8891. // }
  8892. //
  8893. // 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));
  8894. //
  8895. // if (first_err < 0 && error > 0.1) {
  8896. // first_err = i;
  8897. // }
  8898. //
  8899. // for (size_t j = 0; j < 32; j++) {
  8900. // uint64_t error = std::abs(qx_res[i].qs[j] - qx[i].qs[j]);
  8901. //
  8902. // if (first_err < 0 && error > 1) {
  8903. // first_err = i;
  8904. // }
  8905. // }
  8906. // }
  8907. //
  8908. // std::cerr << "TEST QUANTIZE " << ggml_type_name(quant) << " time=" << ms_quant << "ms " << (first_err == -1 ? "CORRECT" : "INCORRECT") << std::endl;
  8909. //
  8910. // if (first_err != -1) {
  8911. // std::cerr << "first_error = " << first_err << std::endl;
  8912. // std::cerr << "Actual result: " << std::endl << std::endl;
  8913. // 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) << " ";
  8914. // for (size_t j = 0; j < 32; j++) {
  8915. // std::cout << " qs" << j << "=" << (uint32_t)qx[first_err].qs[j] << " ";
  8916. // }
  8917. // std::cerr << std::endl << std::endl << "Expected result: " << std::endl << std::endl;
  8918. // 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) << " ";
  8919. // for (size_t j = 0; j < 32; j++) {
  8920. // std::cout << " qs" << j << "=" << (uint32_t)qx_res[first_err].qs[j] << " ";
  8921. // }
  8922. // std::cerr << std::endl;
  8923. // }
  8924. //
  8925. // ggml_vk_destroy_buffer(x_buf);
  8926. // ggml_vk_destroy_buffer(qx_buf);
  8927. //
  8928. // free(x);
  8929. // free(qx);
  8930. // free(qx_res);
  8931. // }
  8932. 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) {
  8933. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  8934. const size_t x_ne = m * k * batch;
  8935. const size_t y_ne = k * n * batch;
  8936. const size_t d_ne = m * n * batch;
  8937. vk_matmul_pipeline2 * pipelines;
  8938. if (mmq) {
  8939. pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1;
  8940. } else {
  8941. pipelines = ctx->device->pipeline_dequant_mul_mat_mat;
  8942. }
  8943. const bool fp16acc = ctx->device->fp16;
  8944. vk_pipeline p;
  8945. std::string shname;
  8946. if (shader_size == 0) {
  8947. p = fp16acc ? pipelines[quant].f16acc->a_s : pipelines[quant].f32acc->a_s;
  8948. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  8949. } else if (shader_size == 1) {
  8950. p = fp16acc ? pipelines[quant].f16acc->a_m : pipelines[quant].f32acc->a_m;
  8951. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  8952. } else if (shader_size == 2) {
  8953. p = fp16acc ? pipelines[quant].f16acc->a_l : pipelines[quant].f32acc->a_l;
  8954. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  8955. } else {
  8956. GGML_ASSERT(0);
  8957. }
  8958. const size_t kpad = mmq ? 0 : ggml_vk_align_size(k, p->align);
  8959. if (mmq || k != kpad) {
  8960. if (shader_size == 0) {
  8961. p = fp16acc ? pipelines[quant].f16acc->s : pipelines[quant].f32acc->s;
  8962. shname = std::string(ggml_type_name(quant)) + "_S";
  8963. } else if (shader_size == 1) {
  8964. p = fp16acc ? pipelines[quant].f16acc->m : pipelines[quant].f32acc->m;
  8965. shname = std::string(ggml_type_name(quant)) + "_M";
  8966. } else if (shader_size == 2) {
  8967. p = fp16acc ? pipelines[quant].f16acc->l : pipelines[quant].f32acc->l;
  8968. shname = std::string(ggml_type_name(quant)) + "_L";
  8969. } else {
  8970. GGML_ASSERT(0);
  8971. }
  8972. }
  8973. if (p == nullptr) {
  8974. std::cerr << "error: no pipeline for ggml_vk_test_dequant_matmul " << ggml_type_name(quant) << std::endl;
  8975. return;
  8976. }
  8977. const size_t x_sz = sizeof(float) * x_ne;
  8978. const size_t y_sz = sizeof(float) * y_ne;
  8979. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  8980. const size_t qy_sz = mmq ? y_ne * ggml_type_size(GGML_TYPE_Q8_1)/ggml_blck_size(GGML_TYPE_Q8_1) : y_sz;
  8981. const size_t d_sz = sizeof(float) * d_ne;
  8982. float * x = (float *) malloc(x_sz);
  8983. float * y = (float *) malloc(y_sz);
  8984. void * qx = malloc(qx_sz);
  8985. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8986. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8987. vk_buffer qy_buf = ggml_vk_create_buffer_check(ctx->device, qy_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8988. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  8989. float * d = (float *) malloc(d_sz);
  8990. float * d_chk = (float *) malloc(d_sz);
  8991. for (size_t i = 0; i < x_ne; i++) {
  8992. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  8993. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  8994. // x[i] = i % k;
  8995. }
  8996. ggml_vk_quantize_data(x, qx, x_ne, quant);
  8997. for (size_t i = 0; i < y_ne; i++) {
  8998. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  8999. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9000. // y[i] = i % k;
  9001. }
  9002. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9003. if (split_k > 1) {
  9004. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9005. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9006. // Resize buffer
  9007. if (ctx->prealloc_split_k != nullptr) {
  9008. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9009. }
  9010. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9011. }
  9012. }
  9013. if (mmq) {
  9014. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_quantize_q8_1, num_it);
  9015. }
  9016. if (ctx->device->need_compiles) {
  9017. ggml_vk_load_shaders(ctx->device);
  9018. }
  9019. ggml_pipeline_allocate_descriptor_sets(ctx);
  9020. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9021. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  9022. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9023. ggml_vk_ctx_begin(ctx->device, subctx);
  9024. if (mmq) {
  9025. for (size_t i = 0; i < num_it; i++) {
  9026. ggml_vk_quantize_q8_1(ctx, subctx, { y_buf, 0, y_sz }, { qy_buf, 0, qy_sz }, y_ne);
  9027. ggml_vk_matmul(
  9028. 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 },
  9029. m, n, k,
  9030. k, k, m, k*m, k*n, m*n,
  9031. split_k, batch, batch, batch, 1, 1, n
  9032. );
  9033. }
  9034. } else {
  9035. for (size_t i = 0; i < num_it; i++) {
  9036. ggml_vk_matmul(
  9037. 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 },
  9038. m, n, k,
  9039. k, k, m, k*m, k*n, m*n,
  9040. split_k, batch, batch, batch, 1, 1, n
  9041. );
  9042. }
  9043. }
  9044. ggml_vk_ctx_end(subctx);
  9045. auto begin = std::chrono::high_resolution_clock::now();
  9046. ggml_vk_submit(subctx, ctx->fence);
  9047. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9048. ctx->device->device.resetFences({ ctx->fence });
  9049. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9050. auto end = std::chrono::high_resolution_clock::now();
  9051. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9052. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  9053. ggml_init_params iparams = {
  9054. /*.mem_size =*/ 1024*1024*1024,
  9055. /*.mem_buffer =*/ NULL,
  9056. /*.no_alloc =*/ true,
  9057. };
  9058. ggml_context * ggml_ctx = ggml_init(iparams);
  9059. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  9060. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  9061. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9062. src0_ggml->data = qx;
  9063. src1_ggml->data = y;
  9064. tensor_ggml->data = d_chk;
  9065. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9066. ggml_build_forward_expand(cgraph, tensor_ggml);
  9067. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9068. ggml_free(ggml_ctx);
  9069. double avg_err = 0.0;
  9070. int first_err_n = -1;
  9071. int first_err_m = -1;
  9072. int first_err_b = -1;
  9073. for (size_t i = 0; i < m*n*batch; i++) {
  9074. double err = std::fabs(d[i] - d_chk[i]);
  9075. avg_err += err;
  9076. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9077. first_err_b = i / (m * n);
  9078. first_err_n = (i % (m * n)) / m;
  9079. first_err_m = (i % (m * n)) % m;
  9080. }
  9081. }
  9082. avg_err /= m * n;
  9083. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9084. std::cerr << "TEST dequant matmul " << shname;
  9085. if (mmq) {
  9086. std::cerr << " mmq";
  9087. }
  9088. 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;
  9089. if (avg_err > 0.01 || std::isnan(avg_err)) {
  9090. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9091. std::cerr << "Actual result: " << std::endl << std::endl;
  9092. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9093. std::cerr << std::endl;
  9094. std::cerr << "Expected result: " << std::endl << std::endl;
  9095. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9096. std::cerr << "src0: " << std::endl << std::endl;
  9097. ggml_vk_print_matrix_area(x, GGML_TYPE_F32, k, m, first_err_m, first_err_n, first_err_b);
  9098. std::cerr << std::endl;
  9099. std::cerr << "src1: " << std::endl << std::endl;
  9100. ggml_vk_print_matrix_area(y, GGML_TYPE_F32, k, n, first_err_m, first_err_n, first_err_b);
  9101. if (split_k > 1) {
  9102. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9103. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9104. std::cerr << "d_buf0: " << std::endl << std::endl;
  9105. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9106. std::cerr << "d_buf1: " << std::endl << std::endl;
  9107. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9108. std::cerr << "d_buf2: " << std::endl << std::endl;
  9109. 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);
  9110. std::cerr << "d_buf3: " << std::endl << std::endl;
  9111. 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);
  9112. free(split_k_buf);
  9113. }
  9114. }
  9115. ggml_vk_destroy_buffer(qx_buf);
  9116. ggml_vk_destroy_buffer(y_buf);
  9117. ggml_vk_destroy_buffer(qy_buf);
  9118. ggml_vk_destroy_buffer(d_buf);
  9119. free(x);
  9120. free(qx);
  9121. free(y);
  9122. free(d);
  9123. free(d_chk);
  9124. }
  9125. #endif
  9126. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx) {
  9127. #if defined(GGML_VULKAN_RUN_TESTS)
  9128. const std::vector<size_t> vals {
  9129. 512, 512, 128,
  9130. 128, 512, 512,
  9131. 4096, 512, 4096,
  9132. 11008, 512, 4096,
  9133. 4096, 512, 11008,
  9134. 32000, 512, 4096,
  9135. 8, 8, 8,
  9136. 100, 46, 576,
  9137. 623, 111, 128,
  9138. 100, 46, 558,
  9139. 512, 1, 256,
  9140. 128, 110, 622,
  9141. 511, 511, 127,
  9142. 511, 511, 7,
  9143. 511, 511, 17,
  9144. 49, 49, 128,
  9145. 128, 49, 49,
  9146. 4096, 49, 4096,
  9147. };
  9148. const size_t num_it = 100;
  9149. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9150. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9151. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9152. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true);
  9153. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true);
  9154. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true);
  9155. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0);
  9156. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0);
  9157. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0);
  9158. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true);
  9159. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true);
  9160. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true);
  9161. abort();
  9162. for (size_t i = 0; i < vals.size(); i += 3) {
  9163. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  9164. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  9165. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  9166. std::cerr << '\n';
  9167. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  9168. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  9169. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  9170. std::cerr << '\n';
  9171. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  9172. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  9173. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  9174. std::cerr << '\n' << std::endl;
  9175. if (vals[i + 2] % 32 == 0) {
  9176. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9177. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9178. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9179. std::cerr << '\n';
  9180. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  9181. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  9182. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  9183. std::cerr << '\n';
  9184. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  9185. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  9186. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  9187. std::cerr << '\n' << std::endl;
  9188. }
  9189. if (vals[i + 2] % 256 == 0) {
  9190. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  9191. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  9192. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  9193. std::cerr << '\n';
  9194. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  9195. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  9196. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  9197. std::cerr << '\n';
  9198. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  9199. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  9200. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  9201. std::cerr << '\n' << std::endl;
  9202. }
  9203. }
  9204. GGML_ABORT("fatal error");
  9205. #endif
  9206. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  9207. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  9208. // Resize buffer
  9209. if (ctx->prealloc_x != nullptr) {
  9210. ggml_vk_destroy_buffer(ctx->prealloc_x);
  9211. }
  9212. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  9213. }
  9214. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  9215. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  9216. // Resize buffer
  9217. if (ctx->prealloc_y != nullptr) {
  9218. ggml_vk_destroy_buffer(ctx->prealloc_y);
  9219. }
  9220. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  9221. }
  9222. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  9223. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  9224. // Resize buffer
  9225. if (ctx->prealloc_split_k != nullptr) {
  9226. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9227. }
  9228. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  9229. }
  9230. 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)) {
  9231. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")");
  9232. // Resize buffer
  9233. if (ctx->prealloc_add_rms_partials != nullptr) {
  9234. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  9235. }
  9236. ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials);
  9237. }
  9238. }
  9239. 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);
  9240. // Returns true if node has enqueued work into the queue, false otherwise
  9241. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  9242. 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){
  9243. ggml_tensor * node = cgraph->nodes[node_idx];
  9244. if (ggml_is_empty(node) || !node->buffer) {
  9245. return false;
  9246. }
  9247. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  9248. ctx->semaphore_idx = 0;
  9249. ggml_tensor * src0 = node->src[0];
  9250. ggml_tensor * src1 = node->src[1];
  9251. ggml_tensor * src2 = node->src[2];
  9252. ggml_tensor * src3 = node->src[3];
  9253. switch (node->op) {
  9254. // Return on empty ops to avoid generating a compute_ctx and setting exit_tensor
  9255. case GGML_OP_RESHAPE:
  9256. case GGML_OP_VIEW:
  9257. case GGML_OP_PERMUTE:
  9258. case GGML_OP_TRANSPOSE:
  9259. case GGML_OP_NONE:
  9260. return false;
  9261. case GGML_OP_UNARY:
  9262. switch (ggml_get_unary_op(node)) {
  9263. case GGML_UNARY_OP_EXP:
  9264. case GGML_UNARY_OP_SILU:
  9265. case GGML_UNARY_OP_GELU:
  9266. case GGML_UNARY_OP_GELU_ERF:
  9267. case GGML_UNARY_OP_GELU_QUICK:
  9268. case GGML_UNARY_OP_RELU:
  9269. case GGML_UNARY_OP_TANH:
  9270. case GGML_UNARY_OP_SIGMOID:
  9271. case GGML_UNARY_OP_HARDSIGMOID:
  9272. case GGML_UNARY_OP_HARDSWISH:
  9273. break;
  9274. default:
  9275. return false;
  9276. }
  9277. break;
  9278. case GGML_OP_GLU:
  9279. switch (ggml_get_glu_op(node)) {
  9280. case GGML_GLU_OP_GEGLU:
  9281. case GGML_GLU_OP_REGLU:
  9282. case GGML_GLU_OP_SWIGLU:
  9283. case GGML_GLU_OP_SWIGLU_OAI:
  9284. case GGML_GLU_OP_GEGLU_ERF:
  9285. case GGML_GLU_OP_GEGLU_QUICK:
  9286. break;
  9287. default:
  9288. return false;
  9289. }
  9290. break;
  9291. case GGML_OP_ADD:
  9292. {
  9293. int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops;
  9294. if (next_node_idx < cgraph->n_nodes &&
  9295. cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM &&
  9296. cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] &&
  9297. ggml_nrows(cgraph->nodes[next_node_idx]) == 1 &&
  9298. ctx->device->add_rms_fusion) {
  9299. if (dryrun) {
  9300. ctx->prealloc_size_add_rms_partials += ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]);
  9301. }
  9302. ctx->do_add_rms_partials = true;
  9303. }
  9304. } break;
  9305. case GGML_OP_REPEAT:
  9306. case GGML_OP_REPEAT_BACK:
  9307. case GGML_OP_GET_ROWS:
  9308. case GGML_OP_ADD_ID:
  9309. case GGML_OP_ACC:
  9310. case GGML_OP_SUB:
  9311. case GGML_OP_MUL:
  9312. case GGML_OP_DIV:
  9313. case GGML_OP_CONCAT:
  9314. case GGML_OP_UPSCALE:
  9315. case GGML_OP_SCALE:
  9316. case GGML_OP_SQR:
  9317. case GGML_OP_SQRT:
  9318. case GGML_OP_SIN:
  9319. case GGML_OP_COS:
  9320. case GGML_OP_CLAMP:
  9321. case GGML_OP_PAD:
  9322. case GGML_OP_ROLL:
  9323. case GGML_OP_CPY:
  9324. case GGML_OP_SET_ROWS:
  9325. case GGML_OP_CONT:
  9326. case GGML_OP_DUP:
  9327. case GGML_OP_SILU_BACK:
  9328. case GGML_OP_NORM:
  9329. case GGML_OP_GROUP_NORM:
  9330. case GGML_OP_RMS_NORM:
  9331. case GGML_OP_RMS_NORM_BACK:
  9332. case GGML_OP_L2_NORM:
  9333. case GGML_OP_DIAG_MASK_INF:
  9334. case GGML_OP_SOFT_MAX:
  9335. case GGML_OP_SOFT_MAX_BACK:
  9336. case GGML_OP_ROPE:
  9337. case GGML_OP_ROPE_BACK:
  9338. case GGML_OP_MUL_MAT:
  9339. case GGML_OP_MUL_MAT_ID:
  9340. case GGML_OP_ARGSORT:
  9341. case GGML_OP_SUM:
  9342. case GGML_OP_SUM_ROWS:
  9343. case GGML_OP_MEAN:
  9344. case GGML_OP_ARGMAX:
  9345. case GGML_OP_COUNT_EQUAL:
  9346. case GGML_OP_IM2COL:
  9347. case GGML_OP_IM2COL_3D:
  9348. case GGML_OP_TIMESTEP_EMBEDDING:
  9349. case GGML_OP_CONV_TRANSPOSE_1D:
  9350. case GGML_OP_POOL_2D:
  9351. case GGML_OP_CONV_2D:
  9352. case GGML_OP_CONV_TRANSPOSE_2D:
  9353. case GGML_OP_CONV_2D_DW:
  9354. case GGML_OP_RWKV_WKV6:
  9355. case GGML_OP_RWKV_WKV7:
  9356. case GGML_OP_LEAKY_RELU:
  9357. case GGML_OP_FLASH_ATTN_EXT:
  9358. case GGML_OP_OPT_STEP_ADAMW:
  9359. case GGML_OP_OPT_STEP_SGD:
  9360. break;
  9361. default:
  9362. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(node->op) << std::endl;
  9363. GGML_ABORT("fatal error");
  9364. }
  9365. vk_context compute_ctx;
  9366. if (!dryrun) {
  9367. if (ctx->compute_ctx.expired()) {
  9368. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9369. ctx->compute_ctx = compute_ctx;
  9370. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  9371. } else {
  9372. compute_ctx = ctx->compute_ctx.lock();
  9373. }
  9374. } else {
  9375. switch (node->op) {
  9376. case GGML_OP_REPEAT:
  9377. case GGML_OP_REPEAT_BACK:
  9378. case GGML_OP_ACC:
  9379. case GGML_OP_GET_ROWS:
  9380. case GGML_OP_ADD:
  9381. case GGML_OP_SUB:
  9382. case GGML_OP_MUL:
  9383. case GGML_OP_DIV:
  9384. case GGML_OP_CONCAT:
  9385. case GGML_OP_UPSCALE:
  9386. case GGML_OP_SCALE:
  9387. case GGML_OP_SQR:
  9388. case GGML_OP_SQRT:
  9389. case GGML_OP_SIN:
  9390. case GGML_OP_COS:
  9391. case GGML_OP_CLAMP:
  9392. case GGML_OP_PAD:
  9393. case GGML_OP_CPY:
  9394. case GGML_OP_SET_ROWS:
  9395. case GGML_OP_CONT:
  9396. case GGML_OP_DUP:
  9397. case GGML_OP_SILU_BACK:
  9398. case GGML_OP_NORM:
  9399. case GGML_OP_GROUP_NORM:
  9400. case GGML_OP_RMS_NORM:
  9401. case GGML_OP_RMS_NORM_BACK:
  9402. case GGML_OP_L2_NORM:
  9403. case GGML_OP_UNARY:
  9404. case GGML_OP_GLU:
  9405. case GGML_OP_DIAG_MASK_INF:
  9406. case GGML_OP_SOFT_MAX:
  9407. case GGML_OP_SOFT_MAX_BACK:
  9408. case GGML_OP_ROPE:
  9409. case GGML_OP_ROPE_BACK:
  9410. case GGML_OP_ARGSORT:
  9411. case GGML_OP_SUM:
  9412. case GGML_OP_SUM_ROWS:
  9413. case GGML_OP_MEAN:
  9414. case GGML_OP_ARGMAX:
  9415. case GGML_OP_COUNT_EQUAL:
  9416. case GGML_OP_IM2COL:
  9417. case GGML_OP_IM2COL_3D:
  9418. case GGML_OP_TIMESTEP_EMBEDDING:
  9419. case GGML_OP_CONV_TRANSPOSE_1D:
  9420. case GGML_OP_POOL_2D:
  9421. case GGML_OP_CONV_2D:
  9422. case GGML_OP_CONV_TRANSPOSE_2D:
  9423. case GGML_OP_CONV_2D_DW:
  9424. case GGML_OP_LEAKY_RELU:
  9425. case GGML_OP_OPT_STEP_SGD:
  9426. {
  9427. // These operations all go through ggml_vk_op_f32, so short-circuit and
  9428. // do the only thing needed for the dryrun.
  9429. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, node, node->op);
  9430. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  9431. if (node->op == GGML_OP_RMS_NORM) {
  9432. ctx->do_add_rms_partials = false;
  9433. }
  9434. return false;
  9435. }
  9436. default:
  9437. break;
  9438. }
  9439. }
  9440. if (!dryrun) {
  9441. // This logic detects dependencies between modes in the graph and calls ggml_vk_sync_buffers
  9442. // to synchronize them. This handles most "normal" synchronization when computing the graph, and when
  9443. // there is no auxiliary memory use, it shouldn't be necessary to call ggml_vk_sync_buffers
  9444. // outside of this logic. When a node uses one of the prealloc buffers for something like
  9445. // dequantization or split_k, additional synchronization is needed between those passes.
  9446. bool need_sync = false;
  9447. // Check whether "node" requires synchronization. The node requires synchronization if it
  9448. // overlaps in memory with another unsynchronized node and at least one of them is a write.
  9449. // Destination nodes are checked against both the written/read lists. Source nodes are only
  9450. // checked against the written list. Two nodes overlap in memory if they come from the same
  9451. // buffer and the tensor or view ranges overlap.
  9452. auto const &overlaps_unsynced = [&](const ggml_tensor *node, const std::vector<const ggml_tensor *> &unsynced_nodes) -> bool {
  9453. if (unsynced_nodes.size() == 0) {
  9454. return false;
  9455. }
  9456. auto n_base = vk_tensor_offset(node) + node->view_offs;
  9457. auto n_size = ggml_nbytes(node);
  9458. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context;
  9459. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  9460. for (auto &other : unsynced_nodes) {
  9461. ggml_backend_vk_buffer_context * o_buf_ctx = (ggml_backend_vk_buffer_context *)other->buffer->context;
  9462. vk_buffer o_buf = o_buf_ctx->dev_buffer;
  9463. if (a_buf == o_buf) {
  9464. auto o_base = vk_tensor_offset(other) + other->view_offs;
  9465. auto o_size = ggml_nbytes(other);
  9466. if ((o_base <= n_base && n_base < o_base + o_size) ||
  9467. (n_base <= o_base && o_base < n_base + n_size)) {
  9468. return true;
  9469. }
  9470. }
  9471. }
  9472. return false;
  9473. };
  9474. // For all fused ops, check if the destination node or any of the source
  9475. // nodes require synchronization.
  9476. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) {
  9477. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  9478. if (overlaps_unsynced(cur_node, ctx->unsynced_nodes_read) || overlaps_unsynced(cur_node, ctx->unsynced_nodes_written)) {
  9479. need_sync = true;
  9480. break;
  9481. }
  9482. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  9483. if (!cur_node->src[j]) {
  9484. continue;
  9485. }
  9486. if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) {
  9487. need_sync = true;
  9488. break;
  9489. }
  9490. }
  9491. }
  9492. if (need_sync) {
  9493. ctx->unsynced_nodes_written.clear();
  9494. ctx->unsynced_nodes_read.clear();
  9495. ggml_vk_sync_buffers(ctx, compute_ctx);
  9496. }
  9497. // Add the last fused node and all fused source nodes to the unsynchronized list.
  9498. const ggml_tensor * last_node = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  9499. ctx->unsynced_nodes_written.push_back(last_node);
  9500. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  9501. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  9502. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  9503. if (!cur_node->src[j]) {
  9504. continue;
  9505. }
  9506. ctx->unsynced_nodes_read.push_back(cur_node->src[j]);
  9507. }
  9508. }
  9509. }
  9510. switch (node->op) {
  9511. case GGML_OP_REPEAT:
  9512. ggml_vk_repeat(ctx, compute_ctx, src0, node, dryrun);
  9513. break;
  9514. case GGML_OP_REPEAT_BACK:
  9515. ggml_vk_repeat_back(ctx, compute_ctx, src0, node, dryrun);
  9516. break;
  9517. case GGML_OP_ACC:
  9518. ggml_vk_acc(ctx, compute_ctx, src0, src1, node, dryrun);
  9519. break;
  9520. case GGML_OP_GET_ROWS:
  9521. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node, dryrun);
  9522. break;
  9523. case GGML_OP_ADD:
  9524. if (ctx->num_additional_fused_ops) {
  9525. ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx, dryrun);
  9526. } else {
  9527. ggml_vk_add(ctx, compute_ctx, src0, src1, node, dryrun);
  9528. }
  9529. break;
  9530. case GGML_OP_SUB:
  9531. ggml_vk_sub(ctx, compute_ctx, src0, src1, node, dryrun);
  9532. break;
  9533. case GGML_OP_MUL:
  9534. ggml_vk_mul(ctx, compute_ctx, src0, src1, node, dryrun);
  9535. break;
  9536. case GGML_OP_DIV:
  9537. ggml_vk_div(ctx, compute_ctx, src0, src1, node, dryrun);
  9538. break;
  9539. case GGML_OP_ADD_ID:
  9540. ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  9541. break;
  9542. case GGML_OP_CONCAT:
  9543. ggml_vk_concat(ctx, compute_ctx, src0, src1, node, dryrun);
  9544. break;
  9545. case GGML_OP_UPSCALE:
  9546. ggml_vk_upscale(ctx, compute_ctx, src0, node, dryrun);
  9547. break;
  9548. case GGML_OP_SCALE:
  9549. ggml_vk_scale(ctx, compute_ctx, src0, node, dryrun);
  9550. break;
  9551. case GGML_OP_SQR:
  9552. ggml_vk_sqr(ctx, compute_ctx, src0, node, dryrun);
  9553. break;
  9554. case GGML_OP_SQRT:
  9555. ggml_vk_sqrt(ctx, compute_ctx, src0, node, dryrun);
  9556. break;
  9557. case GGML_OP_SIN:
  9558. ggml_vk_sin(ctx, compute_ctx, src0, node, dryrun);
  9559. break;
  9560. case GGML_OP_COS:
  9561. ggml_vk_cos(ctx, compute_ctx, src0, node, dryrun);
  9562. break;
  9563. case GGML_OP_CLAMP:
  9564. ggml_vk_clamp(ctx, compute_ctx, src0, node, dryrun);
  9565. break;
  9566. case GGML_OP_PAD:
  9567. ggml_vk_pad(ctx, compute_ctx, src0, node, dryrun);
  9568. break;
  9569. case GGML_OP_ROLL:
  9570. ggml_vk_roll(ctx, compute_ctx, src0, node, dryrun);
  9571. break;
  9572. case GGML_OP_CPY:
  9573. case GGML_OP_CONT:
  9574. case GGML_OP_DUP:
  9575. ggml_vk_cpy(ctx, compute_ctx, src0, node, dryrun);
  9576. break;
  9577. case GGML_OP_SET_ROWS:
  9578. ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node, dryrun);
  9579. break;
  9580. case GGML_OP_SILU_BACK:
  9581. ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node, dryrun);
  9582. break;
  9583. case GGML_OP_NORM:
  9584. ggml_vk_norm(ctx, compute_ctx, src0, node, dryrun);
  9585. break;
  9586. case GGML_OP_GROUP_NORM:
  9587. ggml_vk_group_norm(ctx, compute_ctx, src0, node, dryrun);
  9588. break;
  9589. case GGML_OP_RMS_NORM:
  9590. if (ctx->num_additional_fused_ops > 0) {
  9591. // fused rms_norm + mul
  9592. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  9593. ggml_tensor *other_src = mul->src[0] == node ? mul->src[1] : mul->src[0];
  9594. ggml_vk_rms_norm(ctx, compute_ctx, src0, other_src, mul, (float *)node->op_params, dryrun);
  9595. } else {
  9596. ggml_vk_rms_norm(ctx, compute_ctx, src0, src0, node, (float *)node->op_params, dryrun);
  9597. }
  9598. break;
  9599. case GGML_OP_RMS_NORM_BACK:
  9600. ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node, dryrun);
  9601. break;
  9602. case GGML_OP_L2_NORM:
  9603. ggml_vk_l2_norm(ctx, compute_ctx, src0, node, dryrun);
  9604. break;
  9605. case GGML_OP_UNARY:
  9606. switch (ggml_get_unary_op(node)) {
  9607. case GGML_UNARY_OP_EXP:
  9608. case GGML_UNARY_OP_SILU:
  9609. case GGML_UNARY_OP_GELU:
  9610. case GGML_UNARY_OP_GELU_ERF:
  9611. case GGML_UNARY_OP_GELU_QUICK:
  9612. case GGML_UNARY_OP_RELU:
  9613. case GGML_UNARY_OP_TANH:
  9614. case GGML_UNARY_OP_SIGMOID:
  9615. case GGML_UNARY_OP_HARDSIGMOID:
  9616. case GGML_UNARY_OP_HARDSWISH:
  9617. ggml_vk_unary(ctx, compute_ctx, src0, node, dryrun);
  9618. break;
  9619. default:
  9620. return false;
  9621. }
  9622. break;
  9623. case GGML_OP_GLU:
  9624. switch (ggml_get_glu_op(node)) {
  9625. case GGML_GLU_OP_GEGLU:
  9626. case GGML_GLU_OP_REGLU:
  9627. case GGML_GLU_OP_SWIGLU:
  9628. case GGML_GLU_OP_SWIGLU_OAI:
  9629. case GGML_GLU_OP_GEGLU_ERF:
  9630. case GGML_GLU_OP_GEGLU_QUICK:
  9631. ggml_vk_glu(ctx, compute_ctx, src0, src1, node, dryrun);
  9632. break;
  9633. default:
  9634. return false;
  9635. }
  9636. break;
  9637. case GGML_OP_DIAG_MASK_INF:
  9638. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node, dryrun);
  9639. break;
  9640. case GGML_OP_SOFT_MAX:
  9641. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  9642. break;
  9643. case GGML_OP_SOFT_MAX_BACK:
  9644. ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node, dryrun);
  9645. break;
  9646. case GGML_OP_ROPE:
  9647. ggml_vk_rope(ctx, compute_ctx, src0, src1, src2, node, false, dryrun);
  9648. break;
  9649. case GGML_OP_ROPE_BACK:
  9650. ggml_vk_rope(ctx, compute_ctx, src0, src1, src2, node, true, dryrun);
  9651. break;
  9652. case GGML_OP_ARGSORT:
  9653. ggml_vk_argsort(ctx, compute_ctx, src0, node, dryrun);
  9654. break;
  9655. case GGML_OP_SUM:
  9656. ggml_vk_sum(ctx, compute_ctx, src0, node, dryrun);
  9657. break;
  9658. case GGML_OP_SUM_ROWS:
  9659. ggml_vk_sum_rows(ctx, compute_ctx, src0, node, dryrun);
  9660. break;
  9661. case GGML_OP_MEAN:
  9662. ggml_vk_mean(ctx, compute_ctx, src0, node, dryrun);
  9663. break;
  9664. case GGML_OP_ARGMAX:
  9665. ggml_vk_argmax(ctx, compute_ctx, src0, node, dryrun);
  9666. break;
  9667. case GGML_OP_COUNT_EQUAL:
  9668. ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node, dryrun);
  9669. break;
  9670. case GGML_OP_IM2COL:
  9671. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node, dryrun);
  9672. break;
  9673. case GGML_OP_IM2COL_3D:
  9674. ggml_vk_im2col_3d(ctx, compute_ctx, src0, src1, node, dryrun);
  9675. break;
  9676. case GGML_OP_TIMESTEP_EMBEDDING:
  9677. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node, dryrun);
  9678. break;
  9679. case GGML_OP_CONV_TRANSPOSE_1D:
  9680. ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node, dryrun);
  9681. break;
  9682. case GGML_OP_POOL_2D:
  9683. ggml_vk_pool_2d(ctx, compute_ctx, src0, node, dryrun);
  9684. break;
  9685. case GGML_OP_CONV_2D:
  9686. ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node, dryrun);
  9687. break;
  9688. case GGML_OP_CONV_TRANSPOSE_2D:
  9689. ggml_vk_conv_transpose_2d(ctx, compute_ctx, src0, src1, node, dryrun);
  9690. break;
  9691. case GGML_OP_CONV_2D_DW:
  9692. ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node, dryrun);
  9693. break;
  9694. case GGML_OP_LEAKY_RELU:
  9695. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node, dryrun);
  9696. break;
  9697. case GGML_OP_MUL_MAT:
  9698. ggml_vk_mul_mat(ctx, compute_ctx, src0, src1, node, dryrun);
  9699. break;
  9700. case GGML_OP_MUL_MAT_ID:
  9701. ggml_vk_mul_mat_id(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  9702. break;
  9703. case GGML_OP_FLASH_ATTN_EXT:
  9704. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node, dryrun);
  9705. break;
  9706. case GGML_OP_RWKV_WKV6:
  9707. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node, dryrun);
  9708. break;
  9709. case GGML_OP_RWKV_WKV7:
  9710. ggml_vk_rwkv_wkv7(ctx, compute_ctx, node, dryrun);
  9711. break;
  9712. case GGML_OP_OPT_STEP_ADAMW:
  9713. ggml_vk_opt_step_adamw(ctx, compute_ctx, node, dryrun);
  9714. break;
  9715. case GGML_OP_OPT_STEP_SGD:
  9716. ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  9717. break;
  9718. default:
  9719. return false;
  9720. }
  9721. if (dryrun) {
  9722. return false;
  9723. }
  9724. ctx->tensor_ctxs[node_idx] = compute_ctx;
  9725. #if defined(GGML_VULKAN_CHECK_RESULTS)
  9726. // Force context reset on each node so that each tensor ends up in its own context
  9727. // and can be run and compared to its CPU equivalent separately
  9728. last_node = true;
  9729. #endif
  9730. if (submit || last_node) {
  9731. ggml_vk_ctx_end(compute_ctx);
  9732. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  9733. if (last_node) {
  9734. compute_ctx->exit_tensor_idx = node_idx_begin;
  9735. }
  9736. else {
  9737. compute_ctx->exit_tensor_idx = -1;
  9738. }
  9739. ctx->compute_ctx.reset();
  9740. bool ok = ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, false, almost_ready);
  9741. if (!ok) {
  9742. if (node->op == GGML_OP_UNARY) {
  9743. 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;
  9744. } else if (node->op == GGML_OP_GLU) {
  9745. 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;
  9746. } else {
  9747. std::cerr << __func__ << ": error: op not supported " << node->name << " (" << ggml_op_name(node->op) << ")" << std::endl;
  9748. }
  9749. }
  9750. }
  9751. return true;
  9752. }
  9753. 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) {
  9754. GGML_UNUSED(cgraph);
  9755. ggml_backend_buffer * buf = nullptr;
  9756. switch (tensor->op) {
  9757. case GGML_OP_ADD:
  9758. case GGML_OP_ACC:
  9759. case GGML_OP_GET_ROWS:
  9760. case GGML_OP_SUB:
  9761. case GGML_OP_MUL:
  9762. case GGML_OP_DIV:
  9763. case GGML_OP_ADD_ID:
  9764. case GGML_OP_CONCAT:
  9765. case GGML_OP_UPSCALE:
  9766. case GGML_OP_SCALE:
  9767. case GGML_OP_SQR:
  9768. case GGML_OP_SQRT:
  9769. case GGML_OP_SIN:
  9770. case GGML_OP_COS:
  9771. case GGML_OP_CLAMP:
  9772. case GGML_OP_PAD:
  9773. case GGML_OP_ROLL:
  9774. case GGML_OP_CPY:
  9775. case GGML_OP_SET_ROWS:
  9776. case GGML_OP_CONT:
  9777. case GGML_OP_DUP:
  9778. case GGML_OP_SILU_BACK:
  9779. case GGML_OP_NORM:
  9780. case GGML_OP_GROUP_NORM:
  9781. case GGML_OP_RMS_NORM:
  9782. case GGML_OP_RMS_NORM_BACK:
  9783. case GGML_OP_L2_NORM:
  9784. case GGML_OP_DIAG_MASK_INF:
  9785. case GGML_OP_SOFT_MAX:
  9786. case GGML_OP_SOFT_MAX_BACK:
  9787. case GGML_OP_ROPE:
  9788. case GGML_OP_ROPE_BACK:
  9789. case GGML_OP_RESHAPE:
  9790. case GGML_OP_VIEW:
  9791. case GGML_OP_PERMUTE:
  9792. case GGML_OP_TRANSPOSE:
  9793. case GGML_OP_NONE:
  9794. case GGML_OP_ARGSORT:
  9795. case GGML_OP_SUM:
  9796. case GGML_OP_SUM_ROWS:
  9797. case GGML_OP_MEAN:
  9798. case GGML_OP_ARGMAX:
  9799. case GGML_OP_COUNT_EQUAL:
  9800. case GGML_OP_IM2COL:
  9801. case GGML_OP_IM2COL_3D:
  9802. case GGML_OP_TIMESTEP_EMBEDDING:
  9803. case GGML_OP_CONV_TRANSPOSE_1D:
  9804. case GGML_OP_POOL_2D:
  9805. case GGML_OP_CONV_2D:
  9806. case GGML_OP_CONV_TRANSPOSE_2D:
  9807. case GGML_OP_CONV_2D_DW:
  9808. case GGML_OP_RWKV_WKV6:
  9809. case GGML_OP_RWKV_WKV7:
  9810. case GGML_OP_LEAKY_RELU:
  9811. case GGML_OP_REPEAT:
  9812. case GGML_OP_REPEAT_BACK:
  9813. case GGML_OP_OPT_STEP_ADAMW:
  9814. case GGML_OP_OPT_STEP_SGD:
  9815. buf = tensor->buffer;
  9816. break;
  9817. case GGML_OP_UNARY:
  9818. switch (ggml_get_unary_op(tensor)) {
  9819. case GGML_UNARY_OP_EXP:
  9820. case GGML_UNARY_OP_SILU:
  9821. case GGML_UNARY_OP_GELU:
  9822. case GGML_UNARY_OP_GELU_ERF:
  9823. case GGML_UNARY_OP_GELU_QUICK:
  9824. case GGML_UNARY_OP_RELU:
  9825. case GGML_UNARY_OP_TANH:
  9826. case GGML_UNARY_OP_SIGMOID:
  9827. case GGML_UNARY_OP_HARDSIGMOID:
  9828. case GGML_UNARY_OP_HARDSWISH:
  9829. buf = tensor->buffer;
  9830. break;
  9831. default:
  9832. return false;
  9833. }
  9834. break;
  9835. case GGML_OP_GLU:
  9836. switch (ggml_get_glu_op(tensor)) {
  9837. case GGML_GLU_OP_GEGLU:
  9838. case GGML_GLU_OP_REGLU:
  9839. case GGML_GLU_OP_SWIGLU:
  9840. case GGML_GLU_OP_SWIGLU_OAI:
  9841. case GGML_GLU_OP_GEGLU_ERF:
  9842. case GGML_GLU_OP_GEGLU_QUICK:
  9843. buf = tensor->buffer;
  9844. break;
  9845. default:
  9846. return false;
  9847. }
  9848. break;
  9849. case GGML_OP_MUL_MAT:
  9850. case GGML_OP_MUL_MAT_ID:
  9851. case GGML_OP_FLASH_ATTN_EXT:
  9852. buf = tensor->buffer;
  9853. break;
  9854. default:
  9855. return false;
  9856. }
  9857. if (buf == nullptr) {
  9858. return false;
  9859. }
  9860. 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 << ")");
  9861. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  9862. // always wait for the GPU work to be done for the last submit
  9863. if (tensor_idx == subctx->exit_tensor_idx) {
  9864. use_fence = true;
  9865. }
  9866. // Only run if ctx hasn't been submitted yet
  9867. if (!subctx->seqs.empty()) {
  9868. #ifdef GGML_VULKAN_CHECK_RESULTS
  9869. ggml_vk_check_results_0(ctx, cgraph, tensor_idx);
  9870. use_fence = true;
  9871. #endif
  9872. // Do staging buffer copies
  9873. for (auto& cpy : subctx->in_memcpys) {
  9874. memcpy(cpy.dst, cpy.src, cpy.n);
  9875. }
  9876. for (auto& mset : subctx->memsets) {
  9877. memset(mset.dst, mset.val, mset.n);
  9878. }
  9879. if (almost_ready && !ctx->almost_ready_fence_pending && !use_fence) {
  9880. ggml_vk_submit(subctx, ctx->almost_ready_fence);
  9881. ctx->almost_ready_fence_pending = true;
  9882. } else {
  9883. ggml_vk_submit(subctx, use_fence ? ctx->fence : vk::Fence{});
  9884. }
  9885. if (use_fence) {
  9886. ggml_vk_wait_for_fence(ctx);
  9887. }
  9888. #ifdef GGML_VULKAN_CHECK_RESULTS
  9889. ggml_vk_check_results_1(ctx, cgraph, tensor_idx);
  9890. #endif
  9891. }
  9892. if (tensor_idx == subctx->exit_tensor_idx) {
  9893. // Do staging buffer copies
  9894. for (auto& cpy : subctx->out_memcpys) {
  9895. memcpy(cpy.dst, cpy.src, cpy.n);
  9896. }
  9897. subctx->in_memcpys.clear();
  9898. subctx->out_memcpys.clear();
  9899. subctx->memsets.clear();
  9900. }
  9901. return true;
  9902. }
  9903. // Clean up after graph processing is done
  9904. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  9905. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  9906. for (auto& buffer : ctx->gc.temp_buffers) {
  9907. ggml_vk_pool_free(ctx, buffer);
  9908. }
  9909. ctx->gc.temp_buffers.clear();
  9910. ctx->prealloc_y_last_pipeline_used = {};
  9911. ctx->unsynced_nodes_written.clear();
  9912. ctx->unsynced_nodes_read.clear();
  9913. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  9914. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  9915. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  9916. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  9917. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  9918. }
  9919. ctx->gc.semaphores.clear();
  9920. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  9921. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  9922. }
  9923. ctx->gc.tl_semaphores.clear();
  9924. ctx->semaphore_idx = 0;
  9925. ctx->event_idx = 0;
  9926. for (auto& event : ctx->gc.events) {
  9927. ctx->device->device.resetEvent(event);
  9928. }
  9929. ctx->tensor_ctxs.clear();
  9930. ctx->gc.contexts.clear();
  9931. ctx->pipeline_descriptor_set_requirements = 0;
  9932. ctx->descriptor_set_idx = 0;
  9933. }
  9934. // Clean up on backend free
  9935. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  9936. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  9937. ggml_vk_graph_cleanup(ctx);
  9938. ggml_vk_destroy_buffer(ctx->prealloc_x);
  9939. ggml_vk_destroy_buffer(ctx->prealloc_y);
  9940. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9941. ctx->prealloc_y_last_pipeline_used = nullptr;
  9942. for (auto& buffer : ctx->buffer_pool) {
  9943. ggml_vk_destroy_buffer(buffer);
  9944. }
  9945. ctx->prealloc_size_x = 0;
  9946. ctx->prealloc_size_y = 0;
  9947. ctx->prealloc_size_split_k = 0;
  9948. for (auto& event : ctx->gc.events) {
  9949. ctx->device->device.destroyEvent(event);
  9950. }
  9951. ctx->gc.events.clear();
  9952. ctx->device->device.destroyFence(ctx->fence);
  9953. ctx->device->device.destroyFence(ctx->almost_ready_fence);
  9954. for (auto& pool : ctx->descriptor_pools) {
  9955. ctx->device->device.destroyDescriptorPool(pool);
  9956. }
  9957. ctx->descriptor_pools.clear();
  9958. ctx->descriptor_sets.clear();
  9959. ctx->compute_cmd_pool.destroy(ctx->device->device);
  9960. ctx->transfer_cmd_pool.destroy(ctx->device->device);
  9961. }
  9962. static int ggml_vk_get_device_count() {
  9963. ggml_vk_instance_init();
  9964. return vk_instance.device_indices.size();
  9965. }
  9966. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  9967. ggml_vk_instance_init();
  9968. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  9969. vk::PhysicalDeviceProperties props;
  9970. devices[device].getProperties(&props);
  9971. snprintf(description, description_size, "%s", props.deviceName.data());
  9972. }
  9973. // backend interface
  9974. #define UNUSED GGML_UNUSED
  9975. // device backend
  9976. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  9977. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  9978. }
  9979. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  9980. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  9981. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  9982. ggml_vk_destroy_buffer(ctx->dev_buffer);
  9983. delete ctx;
  9984. }
  9985. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  9986. return vk_ptr_base;
  9987. UNUSED(buffer);
  9988. }
  9989. static enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  9990. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  9991. if (tensor->view_src != nullptr) {
  9992. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  9993. }
  9994. return GGML_STATUS_SUCCESS;
  9995. }
  9996. 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) {
  9997. VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")");
  9998. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  9999. vk_buffer buf = buf_ctx->dev_buffer;
  10000. uint32_t val32 = (uint32_t)value * 0x01010101;
  10001. ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size);
  10002. }
  10003. 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) {
  10004. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10005. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10006. vk_buffer buf = buf_ctx->dev_buffer;
  10007. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10008. }
  10009. 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) {
  10010. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10011. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10012. vk_buffer buf = buf_ctx->dev_buffer;
  10013. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10014. }
  10015. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  10016. if (ggml_backend_buffer_is_vk(src->buffer)) {
  10017. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10018. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10019. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10020. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10021. 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));
  10022. return true;
  10023. }
  10024. return false;
  10025. UNUSED(buffer);
  10026. }
  10027. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  10028. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10029. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  10030. }
  10031. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  10032. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  10033. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  10034. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  10035. /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor,
  10036. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  10037. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  10038. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  10039. /* .clear = */ ggml_backend_vk_buffer_clear,
  10040. /* .reset = */ NULL,
  10041. };
  10042. // vk buffer type
  10043. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10044. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  10045. return ctx->name.c_str();
  10046. }
  10047. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10048. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  10049. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10050. vk_buffer dev_buffer = nullptr;
  10051. try {
  10052. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  10053. } catch (const vk::SystemError& e) {
  10054. return nullptr;
  10055. }
  10056. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  10057. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  10058. }
  10059. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10060. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10061. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  10062. }
  10063. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10064. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10065. return ctx->device->suballocation_block_size;
  10066. }
  10067. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  10068. return ggml_nbytes(tensor);
  10069. UNUSED(buft);
  10070. }
  10071. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  10072. ggml_vk_instance_init();
  10073. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  10074. vk_device dev = ggml_vk_get_device(dev_num);
  10075. return &dev->buffer_type;
  10076. }
  10077. // host buffer type
  10078. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10079. return GGML_VK_NAME "_Host";
  10080. UNUSED(buft);
  10081. }
  10082. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  10083. return GGML_VK_NAME "_Host";
  10084. UNUSED(buffer);
  10085. }
  10086. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10087. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  10088. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  10089. }
  10090. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10091. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  10092. size += 32; // Behave like the CPU buffer type
  10093. void * ptr = nullptr;
  10094. try {
  10095. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  10096. } catch (vk::SystemError& e) {
  10097. GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory (%s)\n", e.what());
  10098. // fallback to cpu buffer
  10099. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  10100. }
  10101. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  10102. buffer->buft = buft;
  10103. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  10104. return buffer;
  10105. UNUSED(buft);
  10106. }
  10107. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10108. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  10109. UNUSED(buft);
  10110. }
  10111. static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10112. return vk_instance.devices[0]->suballocation_block_size;
  10113. UNUSED(buft);
  10114. }
  10115. // Should be changed to return device-specific host buffer type
  10116. // but that probably requires changes in llama.cpp
  10117. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  10118. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  10119. /* .iface = */ {
  10120. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  10121. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  10122. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  10123. /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size,
  10124. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  10125. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  10126. },
  10127. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  10128. /* .context = */ nullptr,
  10129. };
  10130. // Make sure device 0 is initialized
  10131. ggml_vk_instance_init();
  10132. ggml_vk_get_device(0);
  10133. return &ggml_backend_vk_buffer_type_host;
  10134. }
  10135. // backend
  10136. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  10137. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10138. return ctx->name.c_str();
  10139. }
  10140. static void ggml_backend_vk_free(ggml_backend_t backend) {
  10141. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10142. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  10143. ggml_vk_cleanup(ctx);
  10144. delete ctx;
  10145. delete backend;
  10146. }
  10147. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  10148. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10149. return &ctx->device->buffer_type;
  10150. }
  10151. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  10152. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  10153. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10154. 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");
  10155. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10156. vk_context transfer_ctx;
  10157. if (ctx->transfer_ctx.expired()) {
  10158. // Initialize new transfer context
  10159. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10160. ctx->transfer_ctx = transfer_ctx;
  10161. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10162. } else {
  10163. transfer_ctx = ctx->transfer_ctx.lock();
  10164. }
  10165. vk_buffer buf = buf_ctx->dev_buffer;
  10166. ggml_vk_buffer_write_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10167. }
  10168. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  10169. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  10170. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10171. 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");
  10172. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10173. vk_context transfer_ctx;
  10174. if (ctx->transfer_ctx.expired()) {
  10175. // Initialize new transfer context
  10176. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10177. ctx->transfer_ctx = transfer_ctx;
  10178. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10179. } else {
  10180. transfer_ctx = ctx->transfer_ctx.lock();
  10181. }
  10182. vk_buffer buf = buf_ctx->dev_buffer;
  10183. ggml_vk_buffer_read_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10184. }
  10185. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  10186. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  10187. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10188. 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)) {
  10189. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10190. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10191. vk_context transfer_ctx;
  10192. if (ctx->transfer_ctx.expired()) {
  10193. // Initialize new transfer context
  10194. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  10195. ctx->transfer_ctx = transfer_ctx;
  10196. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10197. } else {
  10198. transfer_ctx = ctx->transfer_ctx.lock();
  10199. }
  10200. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10201. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10202. 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));
  10203. return true;
  10204. }
  10205. return false;
  10206. }
  10207. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  10208. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  10209. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10210. if(ctx->transfer_ctx.expired()) {
  10211. return;
  10212. }
  10213. vk_context transfer_ctx = ctx->transfer_ctx.lock();
  10214. ggml_vk_ctx_end(transfer_ctx);
  10215. for (auto& cpy : transfer_ctx->in_memcpys) {
  10216. memcpy(cpy.dst, cpy.src, cpy.n);
  10217. }
  10218. ggml_vk_submit(transfer_ctx, ctx->fence);
  10219. ggml_vk_wait_for_fence(ctx);
  10220. for (auto& cpy : transfer_ctx->out_memcpys) {
  10221. memcpy(cpy.dst, cpy.src, cpy.n);
  10222. }
  10223. ctx->transfer_ctx.reset();
  10224. }
  10225. static bool ggml_vk_is_empty(ggml_tensor * node) {
  10226. 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;
  10227. }
  10228. static bool ggml_vk_can_fuse(const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list<enum ggml_op> ops) {
  10229. if (!ggml_can_fuse(cgraph, node_idx, ops)) {
  10230. return false;
  10231. }
  10232. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
  10233. // additional constraints specific to this fusion
  10234. const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
  10235. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10236. GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
  10237. GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
  10238. // rms_norm only supports f32
  10239. if (mul->src[0]->type != GGML_TYPE_F32 ||
  10240. mul->src[1]->type != GGML_TYPE_F32 ||
  10241. mul->type != GGML_TYPE_F32) {
  10242. return false;
  10243. }
  10244. // if rms_norm is the B operand, then we don't handle broadcast
  10245. if (rms_norm == mul->src[1] &&
  10246. !ggml_are_same_shape(mul->src[0], rms_norm)) {
  10247. return false;
  10248. }
  10249. // rms_norm shader assumes contiguous rows
  10250. if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
  10251. return false;
  10252. }
  10253. }
  10254. return true;
  10255. }
  10256. static uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) {
  10257. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  10258. if (first_node->op != GGML_OP_ADD) {
  10259. return 0;
  10260. }
  10261. if (!ctx->device->multi_add) {
  10262. return 0;
  10263. }
  10264. int32_t num_adds = 1;
  10265. while (node_idx + num_adds < cgraph->n_nodes &&
  10266. cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD &&
  10267. num_adds < MAX_FUSED_ADDS) {
  10268. num_adds++;
  10269. }
  10270. // The shader currently requires same shapes (but different strides are allowed),
  10271. // everything f32, and no misalignment
  10272. for (int32_t i = 0; i < num_adds; ++i) {
  10273. const ggml_tensor *next_node = cgraph->nodes[node_idx + i];
  10274. if (!ggml_are_same_shape(first_node, next_node->src[0]) ||
  10275. !ggml_are_same_shape(first_node, next_node->src[1]) ||
  10276. next_node->type != GGML_TYPE_F32 ||
  10277. next_node->src[0]->type != GGML_TYPE_F32 ||
  10278. next_node->src[1]->type != GGML_TYPE_F32 ||
  10279. get_misalign_bytes(ctx, next_node) ||
  10280. get_misalign_bytes(ctx, next_node->src[0]) ||
  10281. get_misalign_bytes(ctx, next_node->src[1])) {
  10282. num_adds = i;
  10283. }
  10284. }
  10285. // Verify we can fuse these
  10286. ggml_op adds[MAX_FUSED_ADDS];
  10287. for (int32_t i = 0; i < num_adds; ++i) {
  10288. adds[i] = GGML_OP_ADD;
  10289. }
  10290. // decrease num_adds if they can't all be fused
  10291. while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) {
  10292. num_adds--;
  10293. }
  10294. // a single add is not "fused", so just return zero
  10295. if (num_adds == 1) {
  10296. return 0;
  10297. }
  10298. return num_adds;
  10299. }
  10300. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  10301. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  10302. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10303. if (vk_instance.debug_utils_support) {
  10304. vk::DebugUtilsLabelEXT dul = {};
  10305. dul.pLabelName = "ggml_backend_vk_graph_compute";
  10306. dul.color = std::array<float,4>{1.0f, 1.0f, 1.0f, 1.0f};
  10307. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(ctx->device->compute_queue.queue, reinterpret_cast<VkDebugUtilsLabelEXT*>(&dul));
  10308. }
  10309. ctx->prealloc_size_add_rms_partials = 0;
  10310. ctx->prealloc_size_add_rms_partials_offset = 0;
  10311. ctx->do_add_rms_partials = false;
  10312. uint64_t total_mat_mul_bytes = 0;
  10313. for (int i = 0; i < cgraph->n_nodes; i++) {
  10314. if (!ctx->device->disable_fusion) {
  10315. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  10316. if (num_adds) {
  10317. ctx->num_additional_fused_ops = num_adds - 1;
  10318. } else if (ggml_vk_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  10319. ctx->num_additional_fused_ops = 1;
  10320. }
  10321. }
  10322. ggml_vk_build_graph(ctx, cgraph, i, nullptr, 0, true, false, false, false);
  10323. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  10324. total_mat_mul_bytes += ggml_nbytes(cgraph->nodes[i]->src[0]);
  10325. } else if (cgraph->nodes[i]->op == GGML_OP_CONV_2D || cgraph->nodes[i]->op == GGML_OP_CONV_TRANSPOSE_2D) {
  10326. // Return CRSxNPQxsizeof(*) to account as many bytes as mul_mat has in im2col->mul_mat mode.
  10327. auto CRS_size =
  10328. cgraph->nodes[i]->src[0]->ne[0] * cgraph->nodes[i]->src[0]->ne[1] * cgraph->nodes[i]->src[1]->ne[2];
  10329. auto NPQ_size = cgraph->nodes[i]->ne[0] * cgraph->nodes[i]->ne[1] * cgraph->nodes[i]->ne[3];
  10330. total_mat_mul_bytes += NPQ_size * CRS_size * ggml_type_size(cgraph->nodes[i]->type);
  10331. }
  10332. i += ctx->num_additional_fused_ops;
  10333. ctx->num_additional_fused_ops = 0;
  10334. }
  10335. if (ctx->device->need_compiles) {
  10336. ggml_vk_load_shaders(ctx->device);
  10337. }
  10338. ggml_vk_preallocate_buffers(ctx);
  10339. ggml_pipeline_allocate_descriptor_sets(ctx);
  10340. int last_node = cgraph->n_nodes - 1;
  10341. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  10342. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  10343. last_node -= 1;
  10344. }
  10345. // Reserve tensor context space for all nodes
  10346. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  10347. bool first_node_in_batch = true; // true if next node will be first node in a batch
  10348. int submit_node_idx = 0; // index to first node in a batch
  10349. vk_context compute_ctx;
  10350. if (vk_perf_logger_enabled) {
  10351. // allocate/resize the query pool
  10352. if (ctx->device->num_queries < cgraph->n_nodes + 1) {
  10353. if (ctx->device->query_pool) {
  10354. ctx->device->device.destroyQueryPool(ctx->device->query_pool);
  10355. }
  10356. vk::QueryPoolCreateInfo query_create_info;
  10357. query_create_info.queryType = vk::QueryType::eTimestamp;
  10358. query_create_info.queryCount = cgraph->n_nodes + 100;
  10359. ctx->device->query_pool = ctx->device->device.createQueryPool(query_create_info);
  10360. ctx->device->num_queries = query_create_info.queryCount;
  10361. }
  10362. ctx->device->device.resetQueryPool(ctx->device->query_pool, 0, cgraph->n_nodes+1);
  10363. GGML_ASSERT(ctx->compute_ctx.expired());
  10364. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10365. ctx->compute_ctx = compute_ctx;
  10366. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10367. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, 0);
  10368. }
  10369. ctx->prealloc_y_last_pipeline_used = nullptr;
  10370. ctx->prealloc_y_last_tensor_used = nullptr;
  10371. if (ctx->prealloc_size_add_rms_partials) {
  10372. if (ctx->compute_ctx.expired()) {
  10373. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10374. ctx->compute_ctx = compute_ctx;
  10375. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10376. } else {
  10377. compute_ctx = ctx->compute_ctx.lock();
  10378. }
  10379. // initialize partial sums to zero.
  10380. ggml_vk_buffer_memset_async(compute_ctx, ctx->prealloc_add_rms_partials, 0, 0, ctx->prealloc_size_add_rms_partials);
  10381. ggml_vk_sync_buffers(ctx, compute_ctx);
  10382. }
  10383. // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution.
  10384. // Estimate the amount of matmul work by looking at the weight matrix size, and submit every 100MB
  10385. // (and scaled down based on model size, so smaller models submit earlier).
  10386. // Also submit at least every 100 nodes, in case there are workloads without as much matmul.
  10387. int nodes_per_submit = 100;
  10388. int submitted_nodes = 0;
  10389. int submit_count = 0;
  10390. uint64_t mul_mat_bytes = 0;
  10391. uint64_t mul_mat_bytes_per_submit = std::min(uint64_t(100*1000*1000), total_mat_mul_bytes / 40u);
  10392. for (int i = 0; i < cgraph->n_nodes; i++) {
  10393. if (first_node_in_batch) {
  10394. submit_node_idx = i;
  10395. }
  10396. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  10397. mul_mat_bytes += ggml_nbytes(cgraph->nodes[i]->src[0]);
  10398. }
  10399. if (!ctx->device->disable_fusion) {
  10400. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  10401. if (num_adds) {
  10402. ctx->num_additional_fused_ops = num_adds - 1;
  10403. } else if (ggml_vk_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  10404. ctx->num_additional_fused_ops = 1;
  10405. }
  10406. }
  10407. // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining)
  10408. bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5;
  10409. bool submit = (submitted_nodes >= nodes_per_submit) ||
  10410. (mul_mat_bytes >= mul_mat_bytes_per_submit) ||
  10411. (i + ctx->num_additional_fused_ops == last_node) ||
  10412. (almost_ready && !ctx->almost_ready_fence_pending);
  10413. 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);
  10414. if (vk_perf_logger_enabled) {
  10415. if (ctx->compute_ctx.expired()) {
  10416. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10417. ctx->compute_ctx = compute_ctx;
  10418. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  10419. } else {
  10420. compute_ctx = ctx->compute_ctx.lock();
  10421. }
  10422. // If there are fused ops, just write out timestamps for all nodes to keep the accounting simple
  10423. for (int j = 0; j < ctx->num_additional_fused_ops + 1; ++j) {
  10424. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, i+j+1);
  10425. }
  10426. }
  10427. if (enqueued) {
  10428. ++submitted_nodes;
  10429. #ifndef GGML_VULKAN_CHECK_RESULTS
  10430. if (first_node_in_batch) {
  10431. first_node_in_batch = false;
  10432. }
  10433. #endif
  10434. }
  10435. if (submit && enqueued) {
  10436. first_node_in_batch = true;
  10437. submitted_nodes = 0;
  10438. mul_mat_bytes = 0;
  10439. if (submit_count < 3) {
  10440. mul_mat_bytes_per_submit *= 2;
  10441. }
  10442. submit_count++;
  10443. }
  10444. i += ctx->num_additional_fused_ops;
  10445. ctx->num_additional_fused_ops = 0;
  10446. }
  10447. if (vk_perf_logger_enabled) {
  10448. // End the command buffer and submit/wait
  10449. GGML_ASSERT(!ctx->compute_ctx.expired());
  10450. compute_ctx = ctx->compute_ctx.lock();
  10451. ggml_vk_ctx_end(compute_ctx);
  10452. ggml_vk_submit(compute_ctx, ctx->device->fence);
  10453. VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences");
  10454. ctx->device->device.resetFences({ ctx->device->fence });
  10455. // Get the results and pass them to the logger
  10456. std::vector<uint64_t> timestamps(cgraph->n_nodes + 1);
  10457. 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");
  10458. for (int i = 0; i < cgraph->n_nodes; i++) {
  10459. if (!ggml_vk_is_empty(cgraph->nodes[i])) {
  10460. ctx->device->perf_logger->log_timing(cgraph->nodes[i], uint64_t((timestamps[i+1] - timestamps[i]) * ctx->device->properties.limits.timestampPeriod));
  10461. }
  10462. }
  10463. ctx->device->perf_logger->print_timings();
  10464. }
  10465. ggml_vk_graph_cleanup(ctx);
  10466. return GGML_STATUS_SUCCESS;
  10467. UNUSED(backend);
  10468. }
  10469. // Sort the graph for improved parallelism.
  10470. static void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph)
  10471. {
  10472. VK_LOG_DEBUG("ggml_vk_graph_optimize(" << graph->n_nodes << " nodes)");
  10473. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10474. if (ctx->device->disable_graph_optimize) {
  10475. return;
  10476. }
  10477. auto const &is_empty = [](ggml_tensor * node) -> bool {
  10478. 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;
  10479. };
  10480. auto const &is_src_of = [](const ggml_tensor *dst, const ggml_tensor *src) -> bool {
  10481. for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) {
  10482. if (dst->src[s] == src) {
  10483. return true;
  10484. }
  10485. }
  10486. // implicit dependency if they view the same tensor
  10487. const ggml_tensor *dst2 = dst->view_src ? dst->view_src : dst;
  10488. const ggml_tensor *src2 = src->view_src ? src->view_src : src;
  10489. if (dst2 == src2) {
  10490. return true;
  10491. }
  10492. return false;
  10493. };
  10494. // This function tries to reorder the graph to allow nodes to run in parallel.
  10495. // This helps with small batches, but for large batches its a slowdown, probably
  10496. // due to cache contention. So only reorder if the majority of nodes have few rows.
  10497. int num_small_nodes = 0;
  10498. int num_counted_nodes = 0;
  10499. for (int i = 0; i < graph->n_nodes; ++i) {
  10500. if (!is_empty(graph->nodes[i]) &&
  10501. graph->nodes[i]->op != GGML_OP_SET_ROWS) {
  10502. if (ggml_nrows(graph->nodes[i]) <= 8) {
  10503. num_small_nodes++;
  10504. }
  10505. num_counted_nodes++;
  10506. }
  10507. }
  10508. if (num_small_nodes < num_counted_nodes / 2) {
  10509. return;
  10510. }
  10511. std::vector<ggml_tensor *> new_order;
  10512. std::vector<bool> used(graph->n_nodes, false);
  10513. int first_unused = 0;
  10514. while (first_unused < graph->n_nodes) {
  10515. std::vector<int> current_set;
  10516. // First, grab the next unused node.
  10517. current_set.push_back(first_unused);
  10518. // Loop through the next N nodes. Grab any that don't depend on other nodes that
  10519. // haven't already been run. Nodes that have already been run have used[i] set
  10520. // to true. Allow nodes that depend on the previous node if it's a fusion pattern
  10521. // that we support (e.g. RMS_NORM + MUL).
  10522. // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes.
  10523. // The goal is to not interleave real and view nodes in a way that breaks fusion.
  10524. const int NUM_TO_CHECK = 20;
  10525. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  10526. if (used[j]) {
  10527. continue;
  10528. }
  10529. if (is_empty(graph->nodes[j])) {
  10530. continue;
  10531. }
  10532. bool ok = true;
  10533. for (int c = first_unused; c < j; ++c) {
  10534. if (!used[c] &&
  10535. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  10536. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL)) {
  10537. ok = false;
  10538. break;
  10539. }
  10540. }
  10541. if (ok) {
  10542. current_set.push_back(j);
  10543. }
  10544. }
  10545. // Second pass grabs view nodes.
  10546. // Skip this if it would break a fusion optimization (don't split up add->rms_norm or add->add).
  10547. if (graph->nodes[current_set.back()]->op != GGML_OP_ADD) {
  10548. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  10549. if (used[j]) {
  10550. continue;
  10551. }
  10552. if (!is_empty(graph->nodes[j])) {
  10553. continue;
  10554. }
  10555. bool ok = true;
  10556. for (int c = first_unused; c < j; ++c) {
  10557. bool c_in_current_set = std::find(current_set.begin(), current_set.end(), c) != current_set.end();
  10558. // skip views whose srcs haven't been processed.
  10559. if (!used[c] &&
  10560. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  10561. !c_in_current_set) {
  10562. ok = false;
  10563. break;
  10564. }
  10565. }
  10566. if (ok) {
  10567. current_set.push_back(j);
  10568. }
  10569. }
  10570. }
  10571. // Push the current set into new_order
  10572. for (auto c : current_set) {
  10573. new_order.push_back(graph->nodes[c]);
  10574. used[c] = true;
  10575. }
  10576. while (first_unused < graph->n_nodes && used[first_unused]) {
  10577. first_unused++;
  10578. }
  10579. }
  10580. // Replace the graph with the new order.
  10581. for (int i = 0; i < graph->n_nodes; ++i) {
  10582. graph->nodes[i] = new_order[i];
  10583. }
  10584. }
  10585. // TODO: enable async and synchronize
  10586. static ggml_backend_i ggml_backend_vk_interface = {
  10587. /* .get_name = */ ggml_backend_vk_name,
  10588. /* .free = */ ggml_backend_vk_free,
  10589. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  10590. /* .get_tensor_async = */ NULL, // ggml_backend_vk_get_tensor_async,
  10591. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  10592. /* .synchronize = */ NULL, // ggml_backend_vk_synchronize,
  10593. /* .graph_plan_create = */ NULL,
  10594. /* .graph_plan_free = */ NULL,
  10595. /* .graph_plan_update = */ NULL,
  10596. /* .graph_plan_compute = */ NULL,
  10597. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  10598. /* .event_record = */ NULL,
  10599. /* .event_wait = */ NULL,
  10600. /* .graph_optimize = */ ggml_vk_graph_optimize,
  10601. };
  10602. static ggml_guid_t ggml_backend_vk_guid() {
  10603. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  10604. return &guid;
  10605. }
  10606. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  10607. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  10608. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  10609. ggml_vk_init(ctx, dev_num);
  10610. ggml_backend_t vk_backend = new ggml_backend {
  10611. /* .guid = */ ggml_backend_vk_guid(),
  10612. /* .iface = */ ggml_backend_vk_interface,
  10613. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  10614. /* .context = */ ctx,
  10615. };
  10616. return vk_backend;
  10617. }
  10618. bool ggml_backend_is_vk(ggml_backend_t backend) {
  10619. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  10620. }
  10621. int ggml_backend_vk_get_device_count() {
  10622. return ggml_vk_get_device_count();
  10623. }
  10624. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  10625. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  10626. int dev_idx = vk_instance.device_indices[device];
  10627. ggml_vk_get_device_description(dev_idx, description, description_size);
  10628. }
  10629. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  10630. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  10631. GGML_ASSERT(device < (int) vk_instance.device_supports_membudget.size());
  10632. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  10633. vk::PhysicalDeviceMemoryBudgetPropertiesEXT budgetprops;
  10634. vk::PhysicalDeviceMemoryProperties2 memprops = {};
  10635. bool membudget_supported = vk_instance.device_supports_membudget[device];
  10636. if (membudget_supported) {
  10637. memprops.pNext = &budgetprops;
  10638. }
  10639. vkdev.getMemoryProperties2(&memprops);
  10640. for (uint32_t i = 0; i < memprops.memoryProperties.memoryHeapCount; ++i) {
  10641. const vk::MemoryHeap & heap = memprops.memoryProperties.memoryHeaps[i];
  10642. if (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
  10643. *total = heap.size;
  10644. if (membudget_supported && i < budgetprops.heapUsage.size()) {
  10645. *free = budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
  10646. } else {
  10647. *free = heap.size;
  10648. }
  10649. break;
  10650. }
  10651. }
  10652. }
  10653. static vk::PhysicalDeviceType ggml_backend_vk_get_device_type(int device_idx) {
  10654. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  10655. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  10656. vk::PhysicalDeviceProperties2 props = {};
  10657. device.getProperties2(&props);
  10658. return props.properties.deviceType;
  10659. }
  10660. static std::string ggml_backend_vk_get_device_pci_id(int device_idx) {
  10661. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  10662. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  10663. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  10664. bool ext_support = false;
  10665. for (const auto& properties : ext_props) {
  10666. if (strcmp("VK_EXT_pci_bus_info", properties.extensionName) == 0) {
  10667. ext_support = true;
  10668. break;
  10669. }
  10670. }
  10671. if (!ext_support) {
  10672. return "";
  10673. }
  10674. vk::PhysicalDeviceProperties2 props = {};
  10675. vk::PhysicalDevicePCIBusInfoPropertiesEXT pci_bus_info = {};
  10676. props.pNext = &pci_bus_info;
  10677. device.getProperties2(&props);
  10678. const uint32_t pci_domain = pci_bus_info.pciDomain;
  10679. const uint32_t pci_bus = pci_bus_info.pciBus;
  10680. const uint32_t pci_device = pci_bus_info.pciDevice;
  10681. const uint8_t pci_function = (uint8_t) pci_bus_info.pciFunction; // pci function is between 0 and 7, prevent printf overflow warning
  10682. char pci_bus_id[16] = {};
  10683. snprintf(pci_bus_id, sizeof(pci_bus_id), "%04x:%02x:%02x.%x", pci_domain, pci_bus, pci_device, pci_function);
  10684. return std::string(pci_bus_id);
  10685. }
  10686. //////////////////////////
  10687. struct ggml_backend_vk_device_context {
  10688. size_t device;
  10689. std::string name;
  10690. std::string description;
  10691. bool is_integrated_gpu;
  10692. std::string pci_bus_id;
  10693. };
  10694. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  10695. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10696. return ctx->name.c_str();
  10697. }
  10698. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  10699. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10700. return ctx->description.c_str();
  10701. }
  10702. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  10703. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  10704. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  10705. }
  10706. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  10707. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10708. return ggml_backend_vk_buffer_type(ctx->device);
  10709. }
  10710. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  10711. UNUSED(dev);
  10712. return ggml_backend_vk_host_buffer_type();
  10713. }
  10714. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  10715. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10716. return ctx->is_integrated_gpu ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
  10717. }
  10718. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  10719. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10720. props->name = ggml_backend_vk_device_get_name(dev);
  10721. props->description = ggml_backend_vk_device_get_description(dev);
  10722. props->type = ggml_backend_vk_device_get_type(dev);
  10723. props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str();
  10724. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  10725. props->caps = {
  10726. /* .async = */ false,
  10727. /* .host_buffer = */ true,
  10728. /* .buffer_from_host_ptr = */ false,
  10729. /* .events = */ false,
  10730. };
  10731. }
  10732. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  10733. UNUSED(params);
  10734. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10735. return ggml_backend_vk_init(ctx->device);
  10736. }
  10737. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  10738. switch (op->op) {
  10739. case GGML_OP_UNARY:
  10740. switch (ggml_get_unary_op(op)) {
  10741. case GGML_UNARY_OP_EXP:
  10742. case GGML_UNARY_OP_GELU:
  10743. case GGML_UNARY_OP_GELU_ERF:
  10744. case GGML_UNARY_OP_GELU_QUICK:
  10745. case GGML_UNARY_OP_SILU:
  10746. case GGML_UNARY_OP_RELU:
  10747. case GGML_UNARY_OP_TANH:
  10748. case GGML_UNARY_OP_SIGMOID:
  10749. case GGML_UNARY_OP_HARDSIGMOID:
  10750. case GGML_UNARY_OP_HARDSWISH:
  10751. return ggml_is_contiguous(op->src[0]) &&
  10752. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  10753. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  10754. (op->src[0]->type == op->type);
  10755. default:
  10756. return false;
  10757. }
  10758. case GGML_OP_GLU:
  10759. switch (ggml_get_glu_op(op)) {
  10760. case GGML_GLU_OP_GEGLU:
  10761. case GGML_GLU_OP_REGLU:
  10762. case GGML_GLU_OP_SWIGLU:
  10763. case GGML_GLU_OP_SWIGLU_OAI:
  10764. case GGML_GLU_OP_GEGLU_ERF:
  10765. case GGML_GLU_OP_GEGLU_QUICK:
  10766. return ggml_is_contiguous(op->src[0]) &&
  10767. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  10768. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  10769. (op->src[0]->type == op->type);
  10770. default:
  10771. return false;
  10772. }
  10773. case GGML_OP_MUL_MAT:
  10774. case GGML_OP_MUL_MAT_ID:
  10775. {
  10776. ggml_type src0_type = op->src[0]->type;
  10777. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10778. const vk_device& device = ggml_vk_get_device(ctx->device);
  10779. if (op->op == GGML_OP_MUL_MAT_ID) {
  10780. if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) {
  10781. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  10782. return false;
  10783. }
  10784. }
  10785. switch (src0_type) {
  10786. case GGML_TYPE_F32:
  10787. case GGML_TYPE_F16:
  10788. case GGML_TYPE_BF16:
  10789. case GGML_TYPE_Q4_0:
  10790. case GGML_TYPE_Q4_1:
  10791. case GGML_TYPE_Q5_0:
  10792. case GGML_TYPE_Q5_1:
  10793. case GGML_TYPE_Q8_0:
  10794. case GGML_TYPE_Q2_K:
  10795. case GGML_TYPE_Q3_K:
  10796. case GGML_TYPE_Q4_K:
  10797. case GGML_TYPE_Q5_K:
  10798. case GGML_TYPE_Q6_K:
  10799. case GGML_TYPE_IQ1_S:
  10800. case GGML_TYPE_IQ1_M:
  10801. case GGML_TYPE_IQ2_XXS:
  10802. case GGML_TYPE_IQ2_XS:
  10803. case GGML_TYPE_IQ2_S:
  10804. case GGML_TYPE_IQ3_XXS:
  10805. case GGML_TYPE_IQ3_S:
  10806. case GGML_TYPE_IQ4_XS:
  10807. case GGML_TYPE_IQ4_NL:
  10808. case GGML_TYPE_MXFP4:
  10809. break;
  10810. default:
  10811. return false;
  10812. }
  10813. struct ggml_tensor * a;
  10814. struct ggml_tensor * b;
  10815. if (op->op == GGML_OP_MUL_MAT) {
  10816. a = op->src[0];
  10817. b = op->src[1];
  10818. } else {
  10819. a = op->src[2];
  10820. b = op->src[1];
  10821. }
  10822. if (a->ne[3] != b->ne[3]) {
  10823. return false;
  10824. }
  10825. 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) ||
  10826. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  10827. return false;
  10828. }
  10829. if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) {
  10830. // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader.
  10831. // So don't support this combination for now.
  10832. return false;
  10833. }
  10834. return true;
  10835. }
  10836. case GGML_OP_FLASH_ATTN_EXT:
  10837. {
  10838. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  10839. auto device = ggml_vk_get_device(ctx->device);
  10840. bool coopmat2 = device->coopmat2;
  10841. uint32_t HSK = op->src[1]->ne[0];
  10842. uint32_t HSV = op->src[2]->ne[0];
  10843. if ((HSK % 8) != 0 || (HSV % 8) != 0) {
  10844. return false;
  10845. }
  10846. if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) {
  10847. return false;
  10848. }
  10849. if (op->src[0]->type != GGML_TYPE_F32) {
  10850. return false;
  10851. }
  10852. if (op->type != GGML_TYPE_F32) {
  10853. return false;
  10854. }
  10855. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  10856. return false;
  10857. }
  10858. // It's straightforward to support different K/V dequant, but would
  10859. // significantly increase the number of pipelines
  10860. if (op->src[1]->type != op->src[2]->type) {
  10861. return false;
  10862. }
  10863. switch (op->src[1]->type) {
  10864. case GGML_TYPE_F16:
  10865. case GGML_TYPE_Q4_0:
  10866. case GGML_TYPE_Q8_0:
  10867. // supported in scalar and coopmat2 paths
  10868. break;
  10869. case GGML_TYPE_Q4_1:
  10870. case GGML_TYPE_Q5_0:
  10871. case GGML_TYPE_Q5_1:
  10872. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  10873. //case GGML_TYPE_Q2_K:
  10874. //case GGML_TYPE_Q3_K:
  10875. //case GGML_TYPE_Q4_K:
  10876. //case GGML_TYPE_Q5_K:
  10877. //case GGML_TYPE_Q6_K:
  10878. //case GGML_TYPE_IQ1_S:
  10879. //case GGML_TYPE_IQ1_M:
  10880. //case GGML_TYPE_IQ2_XXS:
  10881. //case GGML_TYPE_IQ2_XS:
  10882. //case GGML_TYPE_IQ2_S:
  10883. //case GGML_TYPE_IQ3_XXS:
  10884. //case GGML_TYPE_IQ3_S:
  10885. //case GGML_TYPE_IQ4_XS:
  10886. case GGML_TYPE_IQ4_NL:
  10887. // currently supported only in coopmat2 path
  10888. if (!coopmat2) {
  10889. return false;
  10890. }
  10891. break;
  10892. default:
  10893. return false;
  10894. }
  10895. if (!coopmat2 && !device->subgroup_shuffle) {
  10896. // scalar FA uses subgroupShuffle
  10897. return false;
  10898. }
  10899. return true;
  10900. }
  10901. case GGML_OP_GET_ROWS:
  10902. {
  10903. switch (op->src[0]->type) {
  10904. case GGML_TYPE_F32:
  10905. case GGML_TYPE_F16:
  10906. case GGML_TYPE_BF16:
  10907. case GGML_TYPE_Q4_0:
  10908. case GGML_TYPE_Q4_1:
  10909. case GGML_TYPE_Q5_0:
  10910. case GGML_TYPE_Q5_1:
  10911. case GGML_TYPE_Q8_0:
  10912. case GGML_TYPE_Q2_K:
  10913. case GGML_TYPE_Q3_K:
  10914. case GGML_TYPE_Q4_K:
  10915. case GGML_TYPE_Q5_K:
  10916. case GGML_TYPE_Q6_K:
  10917. case GGML_TYPE_IQ1_S:
  10918. case GGML_TYPE_IQ1_M:
  10919. case GGML_TYPE_IQ2_XXS:
  10920. case GGML_TYPE_IQ2_XS:
  10921. case GGML_TYPE_IQ2_S:
  10922. case GGML_TYPE_IQ3_XXS:
  10923. case GGML_TYPE_IQ3_S:
  10924. case GGML_TYPE_IQ4_XS:
  10925. case GGML_TYPE_IQ4_NL:
  10926. case GGML_TYPE_MXFP4:
  10927. return true;
  10928. default:
  10929. return false;
  10930. }
  10931. }
  10932. case GGML_OP_SET_ROWS:
  10933. {
  10934. switch (op->type) {
  10935. case GGML_TYPE_F32:
  10936. case GGML_TYPE_F16:
  10937. case GGML_TYPE_BF16:
  10938. case GGML_TYPE_Q4_0:
  10939. case GGML_TYPE_Q4_1:
  10940. case GGML_TYPE_Q5_0:
  10941. case GGML_TYPE_Q5_1:
  10942. case GGML_TYPE_Q8_0:
  10943. case GGML_TYPE_IQ4_NL:
  10944. return true;
  10945. default:
  10946. return false;
  10947. }
  10948. }
  10949. case GGML_OP_CONT:
  10950. case GGML_OP_CPY:
  10951. case GGML_OP_DUP:
  10952. {
  10953. ggml_type src0_type = op->src[0]->type;
  10954. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  10955. if (src0_type == GGML_TYPE_F32) {
  10956. switch (src1_type) {
  10957. case GGML_TYPE_F32:
  10958. case GGML_TYPE_F16:
  10959. case GGML_TYPE_BF16:
  10960. case GGML_TYPE_Q4_0:
  10961. case GGML_TYPE_Q4_1:
  10962. case GGML_TYPE_Q5_0:
  10963. case GGML_TYPE_Q5_1:
  10964. case GGML_TYPE_Q8_0:
  10965. case GGML_TYPE_IQ4_NL:
  10966. return true;
  10967. default:
  10968. break;
  10969. }
  10970. }
  10971. if (src1_type == GGML_TYPE_F32) {
  10972. switch (src0_type) {
  10973. case GGML_TYPE_F16:
  10974. case GGML_TYPE_Q4_0:
  10975. case GGML_TYPE_Q4_1:
  10976. case GGML_TYPE_Q5_0:
  10977. case GGML_TYPE_Q5_1:
  10978. case GGML_TYPE_Q8_0:
  10979. case GGML_TYPE_IQ4_NL:
  10980. return true;
  10981. default:
  10982. break;
  10983. }
  10984. }
  10985. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  10986. return true;
  10987. }
  10988. if (
  10989. (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) ||
  10990. (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32)
  10991. ) {
  10992. return true;
  10993. }
  10994. // We can handle copying from a type to the same type if it's
  10995. // contiguous (memcpy). We use f16 or f32 shaders to do the copy,
  10996. // so the type/block size must be a multiple of 4.
  10997. if (src0_type == src1_type &&
  10998. ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op) &&
  10999. (ggml_type_size(src0_type) % 2) == 0) {
  11000. return true;
  11001. }
  11002. return false;
  11003. }
  11004. case GGML_OP_REPEAT:
  11005. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  11006. case GGML_OP_REPEAT_BACK:
  11007. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32;
  11008. case GGML_OP_ROPE:
  11009. case GGML_OP_ROPE_BACK:
  11010. case GGML_OP_NONE:
  11011. case GGML_OP_RESHAPE:
  11012. case GGML_OP_VIEW:
  11013. case GGML_OP_PERMUTE:
  11014. case GGML_OP_TRANSPOSE:
  11015. case GGML_OP_RMS_NORM:
  11016. return true;
  11017. case GGML_OP_NORM:
  11018. case GGML_OP_GROUP_NORM:
  11019. case GGML_OP_L2_NORM:
  11020. return ggml_is_contiguous(op->src[0]);
  11021. case GGML_OP_ADD:
  11022. case GGML_OP_SUB:
  11023. case GGML_OP_MUL:
  11024. case GGML_OP_DIV:
  11025. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11026. (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
  11027. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  11028. case GGML_OP_ADD_ID:
  11029. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 &&
  11030. op->type == GGML_TYPE_F32;
  11031. case GGML_OP_SILU_BACK:
  11032. case GGML_OP_RMS_NORM_BACK:
  11033. case GGML_OP_SQR:
  11034. case GGML_OP_SQRT:
  11035. case GGML_OP_SIN:
  11036. case GGML_OP_COS:
  11037. case GGML_OP_CLAMP:
  11038. case GGML_OP_LEAKY_RELU:
  11039. case GGML_OP_OPT_STEP_ADAMW:
  11040. case GGML_OP_OPT_STEP_SGD:
  11041. return op->src[0]->type == GGML_TYPE_F32;
  11042. case GGML_OP_ARGSORT:
  11043. return op->ne[0] <= max_argsort_cols;
  11044. case GGML_OP_UPSCALE:
  11045. case GGML_OP_ACC:
  11046. case GGML_OP_CONCAT:
  11047. case GGML_OP_SCALE:
  11048. case GGML_OP_PAD:
  11049. case GGML_OP_ROLL:
  11050. case GGML_OP_DIAG_MASK_INF:
  11051. case GGML_OP_SOFT_MAX:
  11052. case GGML_OP_SOFT_MAX_BACK:
  11053. return true;
  11054. case GGML_OP_SUM:
  11055. case GGML_OP_SUM_ROWS:
  11056. case GGML_OP_MEAN:
  11057. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  11058. case GGML_OP_ARGMAX:
  11059. case GGML_OP_COUNT_EQUAL:
  11060. case GGML_OP_IM2COL:
  11061. case GGML_OP_IM2COL_3D:
  11062. case GGML_OP_TIMESTEP_EMBEDDING:
  11063. case GGML_OP_CONV_2D_DW:
  11064. case GGML_OP_POOL_2D:
  11065. case GGML_OP_RWKV_WKV6:
  11066. case GGML_OP_RWKV_WKV7:
  11067. return true;
  11068. case GGML_OP_CONV_TRANSPOSE_1D:
  11069. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  11070. case GGML_OP_CONV_2D:
  11071. case GGML_OP_CONV_TRANSPOSE_2D:
  11072. {
  11073. // Op is disabled for Apple because it segfaults at pipeline create time on MoltenVK
  11074. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11075. const vk_device& device = ggml_vk_get_device(ctx->device);
  11076. if (op->op == GGML_OP_CONV_TRANSPOSE_2D &&
  11077. device->properties.limits.maxPushConstantsSize < sizeof(vk_op_conv_transpose_2d_push_constants)) {
  11078. return false;
  11079. }
  11080. // Channel-contiguous format is not supported yet.
  11081. return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11082. op->src[1]->type == GGML_TYPE_F32 &&
  11083. op->type == GGML_TYPE_F32 &&
  11084. ggml_is_contiguous(op->src[0]) &&
  11085. ggml_is_contiguous(op->src[1]) &&
  11086. ggml_is_contiguous(op));
  11087. }
  11088. default:
  11089. return false;
  11090. }
  11091. UNUSED(dev);
  11092. }
  11093. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  11094. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  11095. return false;
  11096. }
  11097. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11098. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  11099. return buft_ctx->device->idx == ctx->device;
  11100. }
  11101. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  11102. const int min_batch_size = 32;
  11103. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  11104. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  11105. UNUSED(dev);
  11106. }
  11107. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  11108. /* .get_name = */ ggml_backend_vk_device_get_name,
  11109. /* .get_description = */ ggml_backend_vk_device_get_description,
  11110. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  11111. /* .get_type = */ ggml_backend_vk_device_get_type,
  11112. /* .get_props = */ ggml_backend_vk_device_get_props,
  11113. /* .init_backend = */ ggml_backend_vk_device_init,
  11114. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  11115. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  11116. /* .buffer_from_host_ptr = */ NULL,
  11117. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  11118. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  11119. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  11120. /* .event_new = */ NULL,
  11121. /* .event_free = */ NULL,
  11122. /* .event_synchronize = */ NULL,
  11123. };
  11124. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  11125. UNUSED(reg);
  11126. return GGML_VK_NAME;
  11127. }
  11128. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  11129. UNUSED(reg);
  11130. return ggml_backend_vk_get_device_count();
  11131. }
  11132. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  11133. static std::vector<ggml_backend_dev_t> devices;
  11134. static bool initialized = false;
  11135. {
  11136. static std::mutex mutex;
  11137. std::lock_guard<std::mutex> lock(mutex);
  11138. if (!initialized) {
  11139. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  11140. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  11141. char desc[256];
  11142. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  11143. ctx->device = i;
  11144. ctx->name = GGML_VK_NAME + std::to_string(i);
  11145. ctx->description = desc;
  11146. ctx->is_integrated_gpu = ggml_backend_vk_get_device_type(i) == vk::PhysicalDeviceType::eIntegratedGpu;
  11147. ctx->pci_bus_id = ggml_backend_vk_get_device_pci_id(i);
  11148. devices.push_back(new ggml_backend_device {
  11149. /* .iface = */ ggml_backend_vk_device_i,
  11150. /* .reg = */ reg,
  11151. /* .context = */ ctx,
  11152. });
  11153. }
  11154. initialized = true;
  11155. }
  11156. }
  11157. GGML_ASSERT(device < devices.size());
  11158. return devices[device];
  11159. }
  11160. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  11161. /* .get_name = */ ggml_backend_vk_reg_get_name,
  11162. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  11163. /* .get_device = */ ggml_backend_vk_reg_get_device,
  11164. /* .get_proc_address = */ NULL,
  11165. };
  11166. ggml_backend_reg_t ggml_backend_vk_reg() {
  11167. static ggml_backend_reg reg = {
  11168. /* .api_version = */ GGML_BACKEND_API_VERSION,
  11169. /* .iface = */ ggml_backend_vk_reg_i,
  11170. /* .context = */ nullptr,
  11171. };
  11172. try {
  11173. ggml_vk_instance_init();
  11174. return &reg;
  11175. } catch (const vk::SystemError& e) {
  11176. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what());
  11177. return nullptr;
  11178. } catch (const std::exception &e) {
  11179. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: " << e.what());
  11180. return nullptr;
  11181. } catch (...) {
  11182. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: unknown exception during Vulkan init");
  11183. return nullptr;
  11184. }
  11185. }
  11186. // Extension availability
  11187. static bool ggml_vk_instance_validation_ext_available() {
  11188. #ifdef GGML_VULKAN_VALIDATE
  11189. // Check if validation layer provides the extension
  11190. const std::string layer_name = "VK_LAYER_KHRONOS_validation";
  11191. for (const auto& layer : vk::enumerateInstanceLayerProperties()) {
  11192. if (layer_name == layer.layerName.data()) {
  11193. for (const auto& ext : vk::enumerateInstanceExtensionProperties(layer_name)) {
  11194. if (strcmp("VK_EXT_validation_features", ext.extensionName.data()) == 0) {
  11195. return true;
  11196. }
  11197. }
  11198. }
  11199. }
  11200. std::cerr << "ggml_vulkan: WARNING: Validation layer or layer extension VK_EXT_validation_features not found." << std::endl;
  11201. #endif
  11202. return false;
  11203. }
  11204. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  11205. #ifdef __APPLE__
  11206. // Check for portability enumeration extension for MoltenVK support
  11207. for (const auto& properties : instance_extensions) {
  11208. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  11209. return true;
  11210. }
  11211. }
  11212. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  11213. #endif
  11214. return false;
  11215. UNUSED(instance_extensions);
  11216. }
  11217. // Extension availability
  11218. static bool ggml_vk_instance_debug_utils_ext_available(
  11219. const std::vector<vk::ExtensionProperties> & instance_extensions) {
  11220. // Check for portability enumeration extension for MoltenVK support
  11221. for (const auto & properties : instance_extensions) {
  11222. if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) {
  11223. return true;
  11224. }
  11225. }
  11226. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl;
  11227. return false;
  11228. UNUSED(instance_extensions);
  11229. }
  11230. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev) {
  11231. VkPhysicalDeviceFeatures2 device_features2;
  11232. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  11233. VkPhysicalDeviceVulkan11Features vk11_features;
  11234. vk11_features.pNext = nullptr;
  11235. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  11236. device_features2.pNext = &vk11_features;
  11237. vkGetPhysicalDeviceFeatures2(vkdev, &device_features2);
  11238. return vk11_features.storageBuffer16BitAccess;
  11239. }
  11240. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) {
  11241. switch (props.vendorID) {
  11242. case VK_VENDOR_ID_INTEL:
  11243. // Only allowing Xe2 GPU at the moment since Xe2 GPU can gain significant performance boost,
  11244. // while some older hardware (ex. Arc A770) has performance regressions
  11245. return arch == vk_device_architecture::INTEL_XE2;
  11246. case VK_VENDOR_ID_AMD:
  11247. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  11248. // Workaround for AMD proprietary driver reporting support on all GPUs
  11249. return arch == vk_device_architecture::AMD_RDNA3;
  11250. }
  11251. return true;
  11252. default:
  11253. return true;
  11254. }
  11255. }
  11256. // checks
  11257. #ifdef GGML_VULKAN_CHECK_RESULTS
  11258. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  11259. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  11260. return;
  11261. }
  11262. for (int j = 0; j < level; j++) {
  11263. std::cerr << " ";
  11264. }
  11265. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  11266. done.push_back(tensor);
  11267. for (int i = 0; i < GGML_MAX_SRC; i++) {
  11268. if (tensor->src[i] != nullptr) {
  11269. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  11270. }
  11271. }
  11272. }
  11273. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  11274. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  11275. return;
  11276. }
  11277. i0 = std::max(i0, 5);
  11278. i1 = std::max(i1, 5);
  11279. i2 = std::max(i2, 0);
  11280. i3 = std::max(i3, 0);
  11281. fprintf(stderr, " ");
  11282. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  11283. fprintf(stderr, "%7d ", idx1);
  11284. }
  11285. fprintf(stderr, "\n");
  11286. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  11287. fprintf(stderr, "%7d: ", idx0);
  11288. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  11289. 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]) {
  11290. float val;
  11291. if (tensor->type == GGML_TYPE_F32) {
  11292. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  11293. } else if (tensor->type == GGML_TYPE_F16) {
  11294. 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]));
  11295. } else if (tensor->type == GGML_TYPE_I32) {
  11296. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  11297. } else {
  11298. GGML_ABORT("fatal error");
  11299. }
  11300. fprintf(stderr, "% 7.2f ", val);
  11301. } else {
  11302. fprintf(stderr, " ");
  11303. }
  11304. }
  11305. fprintf(stderr, "\n");
  11306. }
  11307. }
  11308. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  11309. void * tensor_data = tensor->data;
  11310. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  11311. if (is_gpu) {
  11312. const size_t tensor_size = ggml_nbytes(tensor);
  11313. tensor_data = malloc(tensor_size);
  11314. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  11315. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  11316. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  11317. }
  11318. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  11319. 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;
  11320. if (tensor->src[0] != nullptr) {
  11321. 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;
  11322. }
  11323. if (tensor->src[1] != nullptr) {
  11324. 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;
  11325. }
  11326. std::cerr << std::endl << "Result:" << std::endl;
  11327. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  11328. std::cerr << std::endl;
  11329. std::vector<const ggml_tensor *> done;
  11330. ggml_vk_print_graph_origin(tensor, done);
  11331. if (is_gpu) {
  11332. free(tensor_data);
  11333. }
  11334. }
  11335. void * comp_result;
  11336. size_t comp_size;
  11337. size_t comp_nb[GGML_MAX_DIMS];
  11338. size_t check_counter = 0;
  11339. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  11340. ggml_tensor * tensor = cgraph->nodes[tensor_idx];
  11341. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  11342. return;
  11343. }
  11344. bool fused_rms_norm_mul = false;
  11345. int rms_norm_idx = -1;
  11346. if (ctx->num_additional_fused_ops == 1 &&
  11347. tensor->op == GGML_OP_RMS_NORM &&
  11348. cgraph->nodes[tensor_idx + 1]->op == GGML_OP_MUL) {
  11349. fused_rms_norm_mul = true;
  11350. tensor = cgraph->nodes[tensor_idx + 1];
  11351. }
  11352. check_counter++;
  11353. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  11354. return;
  11355. }
  11356. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  11357. ggml_tensor * src0 = tensor->src[0];
  11358. ggml_tensor * src1 = tensor->src[1];
  11359. struct ggml_init_params iparams = {
  11360. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  11361. /*.mem_buffer =*/ NULL,
  11362. /*.no_alloc =*/ false,
  11363. };
  11364. struct ggml_context * ggml_ctx = ggml_init(iparams);
  11365. std::array<struct ggml_tensor *, 6> src_clone = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  11366. std::array<size_t, 6> src_size = {0, 0, 0, 0, 0, 0};
  11367. std::array<void *, 6> src_buffer = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  11368. const char * srci_name[6] = {"src0", "src1", "src2", "src3", "src4", "src5"};
  11369. struct ggml_tensor * tensor_clone = nullptr;
  11370. for (int i = 0; i < 6; i++) {
  11371. ggml_tensor * srci = tensor->src[i];
  11372. if (fused_rms_norm_mul) {
  11373. rms_norm_idx = tensor->src[0]->op == GGML_OP_RMS_NORM ? 0 : 1;
  11374. ggml_tensor *rms_norm = tensor->src[rms_norm_idx];
  11375. switch (i) {
  11376. case 0: srci = rms_norm->src[0]; break;
  11377. case 1: srci = tensor->src[1 - rms_norm_idx]; break;
  11378. default: continue;
  11379. }
  11380. }
  11381. if (srci == nullptr) {
  11382. continue;
  11383. }
  11384. ggml_tensor * srci_clone = ggml_dup_tensor(ggml_ctx, srci);
  11385. size_t srci_size = ggml_nbytes(srci);
  11386. src_clone[i] = srci_clone;
  11387. src_size[i] = ggml_nbytes(srci);
  11388. src_buffer[i] = malloc(srci_size);
  11389. srci_clone->data = src_buffer[i];
  11390. if (ggml_backend_buffer_is_host(srci->buffer)) {
  11391. memcpy(srci_clone->data, srci->data, srci_size);
  11392. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  11393. } else if (ggml_backend_buffer_is_vk(srci->buffer)) {
  11394. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)srci->buffer->context;
  11395. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  11396. uint64_t offset = vk_tensor_offset(srci) + srci->view_offs;
  11397. if (!ggml_is_contiguous(srci) && ggml_vk_dim01_contiguous(srci)) {
  11398. for (int i3 = 0; i3 < srci->ne[3]; i3++) {
  11399. for (int i2 = 0; i2 < srci->ne[2]; i2++) {
  11400. const int idx = i3*srci->ne[2] + i2;
  11401. 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]);
  11402. }
  11403. }
  11404. srci_clone->nb[0] = srci->nb[0];
  11405. srci_clone->nb[1] = srci->nb[1];
  11406. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  11407. srci_clone->nb[i] = srci_clone->nb[i - 1]*srci_clone->ne[i - 1];
  11408. }
  11409. } else {
  11410. if (offset + srci_size >= buffer_gpu->size) {
  11411. srci_size = buffer_gpu->size - offset;
  11412. }
  11413. ggml_vk_buffer_read(buffer_gpu, offset, srci_clone->data, srci_size);
  11414. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  11415. }
  11416. } else {
  11417. GGML_ABORT("fatal error");
  11418. }
  11419. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  11420. ggml_vk_print_tensor(srci, srci_name[i]);
  11421. }
  11422. }
  11423. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  11424. const float * params = (const float *)tensor->op_params;
  11425. 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]);
  11426. if (src_clone[4]) {
  11427. ggml_flash_attn_ext_add_sinks(tensor_clone, src_clone[4]);
  11428. }
  11429. } else if (tensor->op == GGML_OP_MUL_MAT) {
  11430. tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
  11431. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  11432. tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  11433. } else if (tensor->op == GGML_OP_SUB) {
  11434. tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
  11435. } else if (tensor->op == GGML_OP_MUL) {
  11436. if (fused_rms_norm_mul) {
  11437. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->src[rms_norm_idx]->op_params);
  11438. tensor_clone = ggml_mul(ggml_ctx, tensor_clone, src_clone[1 - rms_norm_idx]);
  11439. } else {
  11440. tensor_clone = ggml_mul(ggml_ctx, src_clone[0], src_clone[1]);
  11441. }
  11442. } else if (tensor->op == GGML_OP_DIV) {
  11443. tensor_clone = ggml_div(ggml_ctx, src_clone[0], src_clone[1]);
  11444. } else if (tensor->op == GGML_OP_CONCAT) {
  11445. tensor_clone = ggml_concat(ggml_ctx, src_clone[0], src_clone[1], *(int *)tensor->op_params);
  11446. } else if (tensor->op == GGML_OP_UPSCALE) {
  11447. 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]);
  11448. } else if (tensor->op == GGML_OP_SCALE) {
  11449. const float * params = (const float *)tensor->op_params;
  11450. tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]);
  11451. } else if (tensor->op == GGML_OP_SQR) {
  11452. tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]);
  11453. } else if (tensor->op == GGML_OP_SQRT) {
  11454. tensor_clone = ggml_sqrt(ggml_ctx, src_clone[0]);
  11455. } else if (tensor->op == GGML_OP_SIN) {
  11456. tensor_clone = ggml_sin(ggml_ctx, src_clone[0]);
  11457. } else if (tensor->op == GGML_OP_COS) {
  11458. tensor_clone = ggml_cos(ggml_ctx, src_clone[0]);
  11459. } else if (tensor->op == GGML_OP_CLAMP) {
  11460. const float * params = (const float *)tensor->op_params;
  11461. tensor_clone = ggml_clamp(ggml_ctx, src_clone[0], params[0], params[1]);
  11462. } else if (tensor->op == GGML_OP_PAD) {
  11463. 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],
  11464. tensor->op_params[4], tensor->op_params[5], tensor->op_params[6], tensor->op_params[7]);
  11465. } else if (tensor->op == GGML_OP_REPEAT) {
  11466. tensor_clone = ggml_repeat(ggml_ctx, src_clone[0], tensor);
  11467. } else if (tensor->op == GGML_OP_REPEAT_BACK) {
  11468. tensor_clone = ggml_repeat_back(ggml_ctx, src_clone[0], tensor);
  11469. } else if (tensor->op == GGML_OP_ADD) {
  11470. tensor_clone = ggml_add(ggml_ctx, src_clone[0], src_clone[1]);
  11471. } else if (tensor->op == GGML_OP_ACC) {
  11472. 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]);
  11473. } else if (tensor->op == GGML_OP_NORM) {
  11474. tensor_clone = ggml_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  11475. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  11476. const float * float_params = (const float *)tensor->op_params;
  11477. tensor_clone = ggml_group_norm(ggml_ctx, src_clone[0], tensor->op_params[0], float_params[1]);
  11478. } else if (tensor->op == GGML_OP_RMS_NORM) {
  11479. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  11480. } else if (tensor->op == GGML_OP_RMS_NORM_BACK) {
  11481. const float eps = ((float *) tensor->op_params)[0];
  11482. tensor_clone = ggml_rms_norm_back(ggml_ctx, src_clone[0], src_clone[1], eps);
  11483. } else if (tensor->op == GGML_OP_SILU_BACK) {
  11484. tensor_clone = ggml_silu_back(ggml_ctx, src_clone[0], src_clone[1]);
  11485. } else if (tensor->op == GGML_OP_L2_NORM) {
  11486. const float eps = ((float *) tensor->op_params)[0];
  11487. tensor_clone = ggml_l2_norm(ggml_ctx, src_clone[0], eps);
  11488. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  11489. if (src1 != nullptr) {
  11490. const float * params = (const float *)tensor->op_params;
  11491. tensor_clone = ggml_soft_max_ext(ggml_ctx, src_clone[0], src_clone[1], params[0], params[1]);
  11492. } else {
  11493. tensor_clone = ggml_soft_max(ggml_ctx, src_clone[0]);
  11494. }
  11495. } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) {
  11496. 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]);
  11497. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  11498. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]);
  11499. } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) {
  11500. const int n_dims = ((int32_t *) tensor->op_params)[1];
  11501. const int mode = ((int32_t *) tensor->op_params)[2];
  11502. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  11503. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  11504. const float freq_base = ((float *) tensor->op_params)[5];
  11505. const float freq_scale = ((float *) tensor->op_params)[6];
  11506. const float ext_factor = ((float *) tensor->op_params)[7];
  11507. const float attn_factor = ((float *) tensor->op_params)[8];
  11508. const float beta_fast = ((float *) tensor->op_params)[9];
  11509. const float beta_slow = ((float *) tensor->op_params)[10];
  11510. if (mode & GGML_ROPE_TYPE_MROPE) {
  11511. int32_t *sections = ((int32_t *) tensor->op_params) + 11;
  11512. if (tensor->op == GGML_OP_ROPE) {
  11513. 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);
  11514. } else {
  11515. 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);
  11516. }
  11517. } else {
  11518. if (tensor->op == GGML_OP_ROPE) {
  11519. 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);
  11520. } else {
  11521. 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);
  11522. }
  11523. }
  11524. } else if (tensor->op == GGML_OP_UNARY) {
  11525. switch (ggml_get_unary_op(tensor)) {
  11526. case GGML_UNARY_OP_EXP:
  11527. tensor_clone = ggml_exp(ggml_ctx, src_clone[0]);
  11528. break;
  11529. case GGML_UNARY_OP_SILU:
  11530. tensor_clone = ggml_silu(ggml_ctx, src_clone[0]);
  11531. break;
  11532. case GGML_UNARY_OP_GELU:
  11533. tensor_clone = ggml_gelu(ggml_ctx, src_clone[0]);
  11534. break;
  11535. case GGML_UNARY_OP_GELU_ERF:
  11536. tensor_clone = ggml_gelu_erf(ggml_ctx, src_clone[0]);
  11537. break;
  11538. case GGML_UNARY_OP_GELU_QUICK:
  11539. tensor_clone = ggml_gelu_quick(ggml_ctx, src_clone[0]);
  11540. break;
  11541. case GGML_UNARY_OP_RELU:
  11542. tensor_clone = ggml_relu(ggml_ctx, src_clone[0]);
  11543. break;
  11544. case GGML_UNARY_OP_TANH:
  11545. tensor_clone = ggml_tanh(ggml_ctx, src_clone[0]);
  11546. break;
  11547. case GGML_UNARY_OP_SIGMOID:
  11548. tensor_clone = ggml_sigmoid(ggml_ctx, src_clone[0]);
  11549. break;
  11550. case GGML_UNARY_OP_HARDSIGMOID:
  11551. tensor_clone = ggml_hardsigmoid(ggml_ctx, src_clone[0]);
  11552. break;
  11553. case GGML_UNARY_OP_HARDSWISH:
  11554. tensor_clone = ggml_hardswish(ggml_ctx, src_clone[0]);
  11555. break;
  11556. default:
  11557. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  11558. GGML_ABORT("fatal error");
  11559. }
  11560. } else if (tensor->op == GGML_OP_GLU) {
  11561. if (src_clone[1] == nullptr) {
  11562. tensor_clone = ggml_glu(ggml_ctx, src_clone[0], (ggml_glu_op) tensor->op_params[0], tensor->op_params[1]);
  11563. } else {
  11564. tensor_clone = ggml_glu_split(ggml_ctx, src_clone[0], src_clone[1], (ggml_glu_op) tensor->op_params[0]);
  11565. }
  11566. ggml_set_op_params_i32(tensor_clone, 2, ggml_get_op_params_i32(tensor, 2));
  11567. ggml_set_op_params_i32(tensor_clone, 3, ggml_get_op_params_i32(tensor, 3));
  11568. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  11569. if (src1 == nullptr) {
  11570. tensor_clone = ggml_dup(ggml_ctx, src_clone[0]);
  11571. tensor_clone->type = tensor->type;
  11572. } else {
  11573. tensor_clone = ggml_cpy(ggml_ctx, src_clone[0], src_clone[1]);
  11574. }
  11575. } else if (tensor->op == GGML_OP_CONT) {
  11576. tensor_clone = ggml_cont_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  11577. } else if (tensor->op == GGML_OP_RESHAPE) {
  11578. tensor_clone = ggml_reshape_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  11579. } else if (tensor->op == GGML_OP_VIEW) {
  11580. 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]);
  11581. } else if (tensor->op == GGML_OP_PERMUTE) {
  11582. int32_t * params = (int32_t *)tensor->op_params;
  11583. tensor_clone = ggml_permute(ggml_ctx, src_clone[0], params[0], params[1], params[2], params[3]);
  11584. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  11585. tensor_clone = ggml_transpose(ggml_ctx, src_clone[0]);
  11586. } else if (tensor->op == GGML_OP_GET_ROWS) {
  11587. tensor_clone = ggml_get_rows(ggml_ctx, src_clone[0], src_clone[1]);
  11588. } else if (tensor->op == GGML_OP_ARGSORT) {
  11589. tensor_clone = ggml_argsort(ggml_ctx, src_clone[0], (ggml_sort_order) *(int *)tensor->op_params);
  11590. } else if (tensor->op == GGML_OP_SUM) {
  11591. tensor_clone = ggml_sum(ggml_ctx, src_clone[0]);
  11592. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  11593. tensor_clone = ggml_sum_rows(ggml_ctx, src_clone[0]);
  11594. } else if (tensor->op == GGML_OP_MEAN) {
  11595. tensor_clone = ggml_mean(ggml_ctx, src_clone[0]);
  11596. } else if (tensor->op == GGML_OP_ARGMAX) {
  11597. tensor_clone = ggml_argmax(ggml_ctx, src_clone[0]);
  11598. } else if (tensor->op == GGML_OP_COUNT_EQUAL) {
  11599. tensor_clone = ggml_count_equal(ggml_ctx, src_clone[0], src_clone[1]);
  11600. } else if (tensor->op == GGML_OP_IM2COL) {
  11601. const int32_t s0 = tensor->op_params[0];
  11602. const int32_t s1 = tensor->op_params[1];
  11603. const int32_t p0 = tensor->op_params[2];
  11604. const int32_t p1 = tensor->op_params[3];
  11605. const int32_t d0 = tensor->op_params[4];
  11606. const int32_t d1 = tensor->op_params[5];
  11607. const bool is_2D = tensor->op_params[6] == 1;
  11608. tensor_clone = ggml_im2col(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  11609. } else if (tensor->op == GGML_OP_IM2COL_3D) {
  11610. const int32_t s0 = tensor->op_params[0];
  11611. const int32_t s1 = tensor->op_params[1];
  11612. const int32_t s2 = tensor->op_params[2];
  11613. const int32_t p0 = tensor->op_params[3];
  11614. const int32_t p1 = tensor->op_params[4];
  11615. const int32_t p2 = tensor->op_params[5];
  11616. const int32_t d0 = tensor->op_params[6];
  11617. const int32_t d1 = tensor->op_params[7];
  11618. const int32_t d2 = tensor->op_params[8];
  11619. const int32_t IC = tensor->op_params[9];
  11620. 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);
  11621. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  11622. const int32_t dim = tensor->op_params[0];
  11623. const int32_t max_period = tensor->op_params[1];
  11624. tensor_clone = ggml_timestep_embedding(ggml_ctx, src_clone[0], dim, max_period);
  11625. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_1D){
  11626. const int32_t s0 = tensor->op_params[0];
  11627. const int32_t p0 = tensor->op_params[1];
  11628. const int32_t d0 = tensor->op_params[2];
  11629. tensor_clone = ggml_conv_transpose_1d(ggml_ctx, src_clone[0], src_clone[1], s0, p0, d0);
  11630. } else if (tensor->op == GGML_OP_POOL_2D) {
  11631. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  11632. const int32_t k0 = tensor->op_params[1];
  11633. const int32_t k1 = tensor->op_params[2];
  11634. const int32_t s0 = tensor->op_params[3];
  11635. const int32_t s1 = tensor->op_params[4];
  11636. const int32_t p0 = tensor->op_params[5];
  11637. const int32_t p1 = tensor->op_params[6];
  11638. tensor_clone = ggml_pool_2d(ggml_ctx, src_clone[0], op, k0, k1, s0, s1, p0, p1);
  11639. } else if (tensor->op == GGML_OP_CONV_2D) {
  11640. const int32_t s0 = tensor->op_params[0];
  11641. const int32_t s1 = tensor->op_params[1];
  11642. const int32_t p0 = tensor->op_params[2];
  11643. const int32_t p1 = tensor->op_params[3];
  11644. const int32_t d0 = tensor->op_params[4];
  11645. const int32_t d1 = tensor->op_params[5];
  11646. tensor_clone = ggml_conv_2d(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  11647. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_2D) {
  11648. const int32_t s = tensor->op_params[0];
  11649. tensor_clone = ggml_conv_transpose_2d_p0(ggml_ctx, src_clone[0], src_clone[1], s);
  11650. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  11651. const float * op_params = (const float *)tensor->op_params;
  11652. tensor_clone = ggml_leaky_relu(ggml_ctx, src_clone[0], op_params[0], false);
  11653. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  11654. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, src_clone[0], src_clone[1],
  11655. src_clone[2], src_clone[3], src_clone[4], src_clone[5]);
  11656. } else if (tensor->op == GGML_OP_RWKV_WKV7) {
  11657. tensor_clone = ggml_rwkv_wkv7(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3],
  11658. src_clone[4], src_clone[5], src_clone[6]);
  11659. } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
  11660. src_clone[0]->flags = src0->flags;
  11661. tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
  11662. src_clone[2], src_clone[3], src_clone[4]);
  11663. } else if (tensor->op == GGML_OP_OPT_STEP_SGD) {
  11664. src_clone[0]->flags = src0->flags;
  11665. tensor_clone = ggml_opt_step_sgd(ggml_ctx, src_clone[0], src_clone[1],
  11666. src_clone[2]);
  11667. } else if (tensor->op == GGML_OP_ADD_ID) {
  11668. tensor_clone = ggml_add_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  11669. }
  11670. else {
  11671. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  11672. GGML_ABORT("fatal error");
  11673. }
  11674. ggml_cgraph * cgraph_cpu = ggml_new_graph(ggml_ctx);
  11675. ggml_build_forward_expand(cgraph_cpu, tensor_clone);
  11676. ggml_graph_compute_with_ctx(ggml_ctx, cgraph_cpu, 8);
  11677. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  11678. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  11679. }
  11680. comp_size = ggml_nbytes(tensor_clone);
  11681. comp_result = malloc(comp_size);
  11682. memcpy(comp_result, tensor_clone->data, comp_size);
  11683. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  11684. for (int i = 0; i < 6; i++) {
  11685. if (src_buffer[i] != nullptr) {
  11686. free(src_buffer[i]);
  11687. }
  11688. }
  11689. ggml_free(ggml_ctx);
  11690. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  11691. }
  11692. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  11693. ggml_tensor * tensor = cgraph->nodes[tensor_idx];
  11694. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  11695. return;
  11696. }
  11697. if (ctx->num_additional_fused_ops == 1 &&
  11698. tensor->op == GGML_OP_RMS_NORM &&
  11699. cgraph->nodes[tensor_idx + 1]->op == GGML_OP_MUL) {
  11700. tensor = cgraph->nodes[tensor_idx + 1];
  11701. }
  11702. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  11703. return;
  11704. }
  11705. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  11706. ggml_tensor * src0 = tensor->src[0];
  11707. ggml_tensor * src1 = tensor->src[1];
  11708. ggml_tensor * src2 = tensor->src[2];
  11709. ggml_tensor * src3 = tensor->src[3];
  11710. void * tensor_data = tensor->data;
  11711. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  11712. size_t tensor_size = ggml_nbytes(tensor);
  11713. tensor_data = malloc(tensor_size);
  11714. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  11715. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  11716. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  11717. if (offset + tensor_size >= buffer_gpu->size) {
  11718. tensor_size = buffer_gpu->size - offset;
  11719. }
  11720. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  11721. }
  11722. float first_error_result = -1.0f;
  11723. float first_error_correct = -1.0f;
  11724. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  11725. double avg_err = 0.0;
  11726. size_t counter = 0;
  11727. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  11728. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  11729. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  11730. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  11731. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  11732. float correct = 0.0f;
  11733. float result = 0.0f;
  11734. if (buffer_size_fit) {
  11735. if (tensor->type == GGML_TYPE_F32) {
  11736. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  11737. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  11738. } else if (tensor->type == GGML_TYPE_F16) {
  11739. 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]));
  11740. 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]));
  11741. } else if (tensor->type == GGML_TYPE_BF16) {
  11742. 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]));
  11743. 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]));
  11744. } else if (tensor->type == GGML_TYPE_I32) {
  11745. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  11746. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  11747. } else if (tensor->type == GGML_TYPE_I64) {
  11748. correct = *(int64_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  11749. result = *(int64_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  11750. } else {
  11751. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  11752. }
  11753. } else {
  11754. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  11755. GGML_ABORT("fatal error");
  11756. }
  11757. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  11758. 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;
  11759. 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;
  11760. if (src0 != nullptr) {
  11761. 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;
  11762. }
  11763. if (src1 != nullptr) {
  11764. 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;
  11765. }
  11766. if (src2 != nullptr) {
  11767. 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;
  11768. }
  11769. if (src3 != nullptr) {
  11770. 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;
  11771. }
  11772. 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;
  11773. std::cerr << std::endl << "Result:" << std::endl;
  11774. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  11775. std::cerr << std::endl << "Correct:" << std::endl;
  11776. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  11777. std::cerr << std::endl;
  11778. std::vector<const ggml_tensor *> done;
  11779. ggml_vk_print_graph_origin(tensor, done);
  11780. GGML_ABORT("fatal error");
  11781. }
  11782. const double denom = std::fabs(correct) > 1.0f ? (std::fabs(correct) > 1e-8 ? std::fabs(correct) : 1e-8) : 1.0f;
  11783. if (first_error[0] == -1 && std::fabs(correct - result) / denom > 0.5) {
  11784. first_error[0] = i0;
  11785. first_error[1] = i1;
  11786. first_error[2] = i2;
  11787. first_error[3] = i3;
  11788. first_error_result = result;
  11789. first_error_correct = correct;
  11790. }
  11791. // Special case, value is infinite, avoid NaN result in avg_err
  11792. // NaN also appears in results, if both are nan error is 0
  11793. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  11794. avg_err += std::fabs(correct - result) / denom;
  11795. }
  11796. counter++;
  11797. }
  11798. }
  11799. }
  11800. }
  11801. avg_err /= counter;
  11802. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  11803. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  11804. 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;
  11805. if (src0 != nullptr) {
  11806. 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;
  11807. }
  11808. if (src1 != nullptr) {
  11809. 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;
  11810. }
  11811. if (src2 != nullptr) {
  11812. 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;
  11813. }
  11814. if (src3 != nullptr) {
  11815. 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;
  11816. }
  11817. 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;
  11818. std::cerr << std::endl << "Result:" << std::endl;
  11819. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  11820. std::cerr << std::endl << "Correct:" << std::endl;
  11821. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  11822. std::cerr << std::endl;
  11823. std::vector<const ggml_tensor *> done;
  11824. ggml_vk_print_graph_origin(tensor, done);
  11825. }
  11826. if (avg_err > 0.5 || std::isnan(avg_err)) {
  11827. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  11828. 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;
  11829. if (src0 != nullptr) {
  11830. 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;
  11831. }
  11832. if (src1 != nullptr) {
  11833. 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;
  11834. }
  11835. if (src2 != nullptr) {
  11836. 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;
  11837. }
  11838. if (src3 != nullptr) {
  11839. 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;
  11840. }
  11841. 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;
  11842. std::cerr << std::endl << "Result:" << std::endl;
  11843. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  11844. std::cerr << std::endl << "Correct:" << std::endl;
  11845. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  11846. std::cerr << std::endl;
  11847. std::vector<const ggml_tensor *> done;
  11848. ggml_vk_print_graph_origin(tensor, done);
  11849. GGML_ABORT("fatal error");
  11850. } else {
  11851. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  11852. }
  11853. free(comp_result);
  11854. comp_result = nullptr;
  11855. comp_size = 0;
  11856. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  11857. free(tensor_data);
  11858. }
  11859. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  11860. }
  11861. #endif
  11862. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)