ggml-vulkan.cpp 603 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217
  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. #include <vulkan/vulkan.hpp>
  8. #include <algorithm>
  9. #include <cmath>
  10. #include <iomanip>
  11. #include <iostream>
  12. #include <tuple>
  13. #include <vector>
  14. #include <sstream>
  15. #include <utility>
  16. #include <memory>
  17. #include <limits>
  18. #include <map>
  19. #include <unordered_map>
  20. #include <memory>
  21. #include <mutex>
  22. #include <future>
  23. #include <thread>
  24. #if defined(_MSC_VER)
  25. # define NOMINMAX 1
  26. # include <windows.h>
  27. # define YIELD() YieldProcessor()
  28. #elif defined(__clang__) || defined(__GNUC__)
  29. # if defined(__x86_64__) ||defined(__i386__)
  30. # include <immintrin.h>
  31. # define YIELD() _mm_pause()
  32. # elif defined(__arm__) || defined(__aarch64__)
  33. # if defined(__clang__)
  34. # include <arm_acle.h>
  35. # define YIELD() __yield()
  36. # else
  37. # define YIELD() asm volatile("yield")
  38. # endif
  39. # endif
  40. #endif
  41. #if !defined(YIELD)
  42. #define YIELD()
  43. #endif
  44. #include "ggml-impl.h"
  45. #include "ggml-backend-impl.h"
  46. #include "ggml-vulkan-shaders.hpp"
  47. // remove this once it's more widely available in the SDK
  48. #if !defined(VK_KHR_shader_bfloat16)
  49. #define VK_KHR_shader_bfloat16 1
  50. #define VK_KHR_SHADER_BFLOAT16_SPEC_VERSION 1
  51. #define VK_KHR_SHADER_BFLOAT16_EXTENSION_NAME "VK_KHR_shader_bfloat16"
  52. #define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR ((VkStructureType)1000141000)
  53. #define VK_COMPONENT_TYPE_BFLOAT16_KHR ((VkComponentTypeKHR)1000141000)
  54. typedef struct VkPhysicalDeviceShaderBfloat16FeaturesKHR {
  55. VkStructureType sType;
  56. void* pNext;
  57. VkBool32 shaderBFloat16Type;
  58. VkBool32 shaderBFloat16DotProduct;
  59. VkBool32 shaderBFloat16CooperativeMatrix;
  60. } VkPhysicalDeviceShaderBfloat16FeaturesKHR;
  61. #endif
  62. #define ROUNDUP_POW2(M, N) (((M) + (N) - 1) & ~((N) - 1))
  63. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  64. static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; }
  65. #define VK_VENDOR_ID_AMD 0x1002
  66. #define VK_VENDOR_ID_APPLE 0x106b
  67. #define VK_VENDOR_ID_INTEL 0x8086
  68. #define VK_VENDOR_ID_NVIDIA 0x10de
  69. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 256
  70. #define GGML_VK_MAX_NODES 8192
  71. #define MAX_VK_BUFFERS 256
  72. #define VK_CHECK(err, msg) \
  73. do { \
  74. vk::Result err_ = (err); \
  75. if (err_ != vk::Result::eSuccess) { \
  76. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  77. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  78. exit(1); \
  79. } \
  80. } while (0)
  81. #ifdef GGML_VULKAN_DEBUG
  82. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  83. #else
  84. #define VK_LOG_DEBUG(msg) ((void) 0)
  85. #endif // GGML_VULKAN_DEBUG
  86. struct ggml_backend_vk_context;
  87. #define MAX_PARAMETER_COUNT 8
  88. // Max number of adds that can be fused without exceeding MAX_PARAMETER_COUNT.
  89. #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 2)
  90. struct vk_pipeline_struct {
  91. std::string name;
  92. vk::ShaderModule shader_module;
  93. vk::PipelineLayout layout;
  94. vk::Pipeline pipeline;
  95. uint32_t push_constant_size;
  96. uint32_t parameter_count;
  97. std::array<uint32_t, 3> wg_denoms;
  98. uint32_t align;
  99. // set to true to request the pipeline is compiled after the dryrun
  100. bool needed {};
  101. // set to true when the shader has been compiled
  102. bool compiled {};
  103. };
  104. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  105. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  106. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  107. struct vk_matmul_pipeline_struct {
  108. vk_pipeline l, m, s;
  109. vk_pipeline a_l, a_m, a_s;
  110. };
  111. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  112. struct vk_matmul_pipeline2 {
  113. vk_matmul_pipeline2() {
  114. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  115. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  116. }
  117. vk_matmul_pipeline f32acc;
  118. vk_matmul_pipeline f16acc;
  119. };
  120. struct vk_device_struct;
  121. typedef std::shared_ptr<vk_device_struct> vk_device;
  122. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  123. struct vk_buffer_struct;
  124. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  125. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  126. struct ggml_backend_vk_buffer_type_context {
  127. std::string name;
  128. vk_device device;
  129. };
  130. struct vk_queue;
  131. // Stores command pool/buffers. There's an instance of this
  132. // for each (context,queue) pair and for each (device,queue) pair.
  133. struct vk_command_pool {
  134. void init(vk_device& device, vk_queue *q_);
  135. void destroy(vk::Device& device);
  136. vk::CommandPool pool;
  137. uint32_t cmd_buffer_idx;
  138. std::vector<vk::CommandBuffer> cmd_buffers;
  139. vk_queue *q;
  140. };
  141. // Prevent simultaneous submissions to the same queue.
  142. // This could be per vk_queue if we stopped having two vk_queue structures
  143. // sharing the same vk::Queue.
  144. static std::mutex queue_mutex;
  145. struct vk_queue {
  146. uint32_t queue_family_index;
  147. vk::Queue queue;
  148. vk_command_pool cmd_pool;
  149. vk::PipelineStageFlags stage_flags;
  150. bool transfer_only;
  151. // copy everything except the cmd_pool
  152. void copyFrom(vk_queue &other) {
  153. queue_family_index = other.queue_family_index;
  154. queue = other.queue;
  155. stage_flags = other.stage_flags;
  156. transfer_only = other.transfer_only;
  157. }
  158. };
  159. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  160. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  161. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  162. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  163. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  164. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  165. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  166. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  167. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  168. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  169. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  170. /* .is_host = */ NULL,
  171. };
  172. #ifdef GGML_VULKAN_MEMORY_DEBUG
  173. class vk_memory_logger;
  174. #endif
  175. class vk_perf_logger;
  176. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  177. static constexpr uint32_t mul_mat_vec_max_cols = 8;
  178. static constexpr uint32_t p021_max_gqa_ratio = 8;
  179. enum vk_device_architecture {
  180. OTHER,
  181. AMD_GCN,
  182. AMD_RDNA1,
  183. AMD_RDNA2,
  184. AMD_RDNA3,
  185. INTEL_XE2,
  186. NVIDIA_PRE_TURING,
  187. };
  188. // HSK x HSV
  189. enum FaHeadSizes {
  190. FA_HEAD_SIZE_64,
  191. FA_HEAD_SIZE_80,
  192. FA_HEAD_SIZE_96,
  193. FA_HEAD_SIZE_112,
  194. FA_HEAD_SIZE_128,
  195. FA_HEAD_SIZE_192,
  196. FA_HEAD_SIZE_192_128,
  197. FA_HEAD_SIZE_256,
  198. FA_HEAD_SIZE_576_512,
  199. FA_HEAD_SIZE_UNSUPPORTED,
  200. FA_HEAD_SIZE_COUNT = FA_HEAD_SIZE_UNSUPPORTED,
  201. };
  202. static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) {
  203. vk::PhysicalDeviceProperties props = device.getProperties();
  204. if (props.vendorID == VK_VENDOR_ID_AMD) {
  205. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  206. bool amd_shader_core_properties = false;
  207. bool integer_dot_product = false;
  208. bool subgroup_size_control = false;
  209. for (const auto& properties : ext_props) {
  210. if (strcmp("VK_AMD_shader_core_properties", properties.extensionName) == 0) {
  211. amd_shader_core_properties = true;
  212. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0) {
  213. integer_dot_product = true;
  214. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  215. subgroup_size_control = true;
  216. }
  217. }
  218. if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) {
  219. return vk_device_architecture::OTHER;
  220. }
  221. vk::PhysicalDeviceProperties2 props2;
  222. vk::PhysicalDeviceShaderCorePropertiesAMD shader_core_props_amd;
  223. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR integer_dot_props;
  224. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  225. props2.pNext = &shader_core_props_amd;
  226. shader_core_props_amd.pNext = &integer_dot_props;
  227. integer_dot_props.pNext = &subgroup_size_control_props;
  228. device.getProperties2(&props2);
  229. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 64) {
  230. return vk_device_architecture::AMD_GCN;
  231. }
  232. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 32) {
  233. // RDNA
  234. if (shader_core_props_amd.wavefrontsPerSimd == 20) {
  235. return vk_device_architecture::AMD_RDNA1;
  236. }
  237. if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
  238. return vk_device_architecture::AMD_RDNA3;
  239. }
  240. return vk_device_architecture::AMD_RDNA2;
  241. }
  242. } else if (props.vendorID == VK_VENDOR_ID_INTEL) {
  243. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  244. bool subgroup_size_control = false;
  245. for (const auto& properties : ext_props) {
  246. if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  247. subgroup_size_control = true;
  248. }
  249. }
  250. if (!subgroup_size_control) {
  251. return vk_device_architecture::OTHER;
  252. }
  253. vk::PhysicalDeviceProperties2 props2;
  254. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  255. props2.pNext = &subgroup_size_control_props;
  256. device.getProperties2(&props2);
  257. if (subgroup_size_control_props.minSubgroupSize == 16) {
  258. // Xe2 architecture uses SIMD16 while previous Xe and Gen architecture uses SIMD8.
  259. // Minimum subgroup size matches the SIMD width so we distinguish architecture by checking this value.
  260. // https://www.intel.com/content/www/us/en/content-details/824434/2024-intel-tech-tour-xe2-and-lunar-lake-s-gpu.html
  261. // https://www.intel.com/content/www/us/en/docs/oneapi/optimization-guide-gpu/2025-0/intel-xe-gpu-architecture.html
  262. return vk_device_architecture::INTEL_XE2;
  263. }
  264. } else if (props.vendorID == VK_VENDOR_ID_NVIDIA) {
  265. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  266. bool cooperative_matrix = false;
  267. // Detect "pre-turing" based on lack of coopmat support.
  268. for (const auto& properties : ext_props) {
  269. if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0) {
  270. cooperative_matrix = true;
  271. break;
  272. }
  273. }
  274. if (!cooperative_matrix) {
  275. return vk_device_architecture::NVIDIA_PRE_TURING;
  276. }
  277. }
  278. return vk_device_architecture::OTHER;
  279. }
  280. enum vk_conv_shapes {
  281. CONV_SHAPE_128x128,
  282. CONV_SHAPE_64x32,
  283. CONV_SHAPE_32x256,
  284. CONV_SHAPE_COUNT,
  285. };
  286. static constexpr uint32_t num_argsort_pipelines = 11;
  287. static constexpr uint32_t max_argsort_cols = 1 << (num_argsort_pipelines-1);
  288. struct vk_device_struct {
  289. std::recursive_mutex mutex;
  290. vk::PhysicalDevice physical_device;
  291. vk::PhysicalDeviceProperties properties;
  292. std::string name;
  293. uint64_t max_memory_allocation_size;
  294. uint64_t suballocation_block_size;
  295. bool fp16;
  296. bool bf16;
  297. bool pipeline_robustness;
  298. vk::Device device;
  299. uint32_t vendor_id;
  300. vk::DriverId driver_id;
  301. vk_device_architecture architecture;
  302. vk_queue compute_queue;
  303. vk_queue transfer_queue;
  304. bool single_queue;
  305. uint32_t subgroup_size;
  306. uint32_t shader_core_count;
  307. bool uma;
  308. bool prefer_host_memory;
  309. bool float_controls_rte_fp16;
  310. bool subgroup_add;
  311. bool subgroup_shuffle;
  312. bool multi_add;
  313. bool integer_dot_product;
  314. bool subgroup_size_control;
  315. uint32_t subgroup_min_size;
  316. uint32_t subgroup_max_size;
  317. bool subgroup_require_full_support;
  318. bool coopmat_support;
  319. bool coopmat_acc_f32_support {};
  320. bool coopmat_acc_f16_support {};
  321. bool coopmat_bf16_support {};
  322. bool coopmat_support_16x16x16_f16acc {};
  323. bool coopmat_support_16x16x16_f32acc {};
  324. bool coopmat1_fa_support {};
  325. uint32_t coopmat_m;
  326. uint32_t coopmat_n;
  327. uint32_t coopmat_k;
  328. bool coopmat_int_support;
  329. uint32_t coopmat_int_m;
  330. uint32_t coopmat_int_n;
  331. uint32_t coopmat_int_k;
  332. bool coopmat2;
  333. size_t idx;
  334. bool mul_mat_l[GGML_TYPE_COUNT];
  335. bool mul_mat_m[GGML_TYPE_COUNT];
  336. bool mul_mat_s[GGML_TYPE_COUNT];
  337. bool mul_mat_id_l[GGML_TYPE_COUNT];
  338. bool mul_mat_id_m[GGML_TYPE_COUNT];
  339. bool mul_mat_id_s[GGML_TYPE_COUNT];
  340. // set to true to indicate that some shaders need to be compiled after the dryrun
  341. bool need_compiles {};
  342. vk::DescriptorSetLayout dsl;
  343. vk_matmul_pipeline pipeline_matmul_f32 {};
  344. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  345. vk_matmul_pipeline pipeline_matmul_bf16 {};
  346. vk_matmul_pipeline2 pipeline_matmul_f16;
  347. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  348. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  349. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  350. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_COUNT];
  351. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  352. vk_matmul_pipeline pipeline_matmul_id_bf16 {};
  353. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  354. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  355. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  356. vk_pipeline pipeline_matmul_split_k_reduce;
  357. vk_pipeline pipeline_quantize_q8_1;
  358. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  359. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  360. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  361. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_COUNT];
  362. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio];
  363. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  364. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  365. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  366. vk_pipeline pipeline_acc_f32;
  367. // [src0 0=fp32,1=fp16][src1 0=fp32,1=fp16][dst 0=fp32,1=fp16]
  368. vk_pipeline pipeline_add[2][2][2];
  369. vk_pipeline pipeline_add_norepeat[2][2][2];
  370. vk_pipeline pipeline_sub[2][2][2];
  371. vk_pipeline pipeline_sub_norepeat[2][2][2];
  372. vk_pipeline pipeline_mul[2][2][2];
  373. vk_pipeline pipeline_mul_norepeat[2][2][2];
  374. vk_pipeline pipeline_div[2][2][2];
  375. vk_pipeline pipeline_div_norepeat[2][2][2];
  376. // indexed by num_additional_fused_ops == num_adds - 1
  377. vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS];
  378. vk_pipeline pipeline_add_id_f32;
  379. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  380. vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32, pipeline_upscale_bilinear_ac_f32;
  381. vk_pipeline pipeline_scale_f32;
  382. vk_pipeline pipeline_sqr_f32;
  383. vk_pipeline pipeline_sin_f32;
  384. vk_pipeline pipeline_cos_f32;
  385. vk_pipeline pipeline_clamp_f32;
  386. vk_pipeline pipeline_pad_f32;
  387. vk_pipeline pipeline_roll_f32;
  388. vk_pipeline pipeline_repeat_f32, pipeline_repeat_back_f32;
  389. vk_pipeline pipeline_cpy_f32_f32, pipeline_cpy_f32_f16, pipeline_cpy_f16_f16, pipeline_cpy_f16_f32, pipeline_cpy_f32_bf16;
  390. 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;
  391. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  392. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  393. vk_pipeline pipeline_set_rows[GGML_TYPE_COUNT];
  394. vk_pipeline pipeline_norm_f32;
  395. vk_pipeline pipeline_group_norm_f32;
  396. vk_pipeline pipeline_rms_norm_f32;
  397. vk_pipeline pipeline_rms_norm_mul_f32;
  398. vk_pipeline pipeline_rms_norm_back_f32;
  399. vk_pipeline pipeline_l2_norm_f32;
  400. // [src/dst 0=fp32,1=fp16]
  401. vk_pipeline pipeline_gelu[2];
  402. vk_pipeline pipeline_gelu_erf[2];
  403. vk_pipeline pipeline_gelu_quick[2];
  404. vk_pipeline pipeline_silu[2];
  405. vk_pipeline pipeline_relu[2];
  406. vk_pipeline pipeline_tanh[2];
  407. vk_pipeline pipeline_sigmoid[2];
  408. vk_pipeline pipeline_geglu[2];
  409. vk_pipeline pipeline_reglu[2];
  410. vk_pipeline pipeline_swiglu[2];
  411. vk_pipeline pipeline_swiglu_oai[2];
  412. vk_pipeline pipeline_geglu_erf[2];
  413. vk_pipeline pipeline_geglu_quick[2];
  414. vk_pipeline pipeline_leaky_relu_f32;
  415. vk_pipeline pipeline_silu_back_f32;
  416. vk_pipeline pipeline_diag_mask_inf_f32;
  417. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  418. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  419. vk_pipeline pipeline_soft_max_back_f32;
  420. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16;
  421. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16;
  422. vk_pipeline pipeline_rope_multi_f32, pipeline_rope_multi_f16;
  423. vk_pipeline pipeline_rope_vision_f32, pipeline_rope_vision_f16;
  424. vk_pipeline pipeline_argsort_f32[num_argsort_pipelines];
  425. vk_pipeline pipeline_sum_rows_f32;
  426. vk_pipeline pipeline_argmax_f32;
  427. vk_pipeline pipeline_count_equal_i32;
  428. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  429. vk_pipeline pipeline_timestep_embedding_f32;
  430. vk_pipeline pipeline_conv_transpose_1d_f32;
  431. vk_pipeline pipeline_pool2d_f32;
  432. vk_pipeline pipeline_rwkv_wkv6_f32;
  433. vk_pipeline pipeline_rwkv_wkv7_f32;
  434. vk_pipeline pipeline_opt_step_adamw_f32;
  435. vk_pipeline pipeline_opt_step_sgd_f32;
  436. vk_pipeline pipeline_conv2d_f32[CONV_SHAPE_COUNT];
  437. vk_pipeline pipeline_conv2d_f16_f32[CONV_SHAPE_COUNT];
  438. vk_pipeline pipeline_conv2d_dw_whcn_f32;
  439. vk_pipeline pipeline_conv2d_dw_cwhn_f32;
  440. // [2][2][2] is for {f16acc,f32acc}x{large,small_rows}x{unaligned, aligned}
  441. vk_pipeline pipeline_flash_attn_f32_f16_cm2[GGML_TYPE_COUNT][FA_HEAD_SIZE_COUNT][2][2][2];
  442. vk_pipeline pipeline_flash_attn_f32_f16_cm1[GGML_TYPE_COUNT][FA_HEAD_SIZE_COUNT][2][2][2];
  443. vk_pipeline pipeline_flash_attn_f32_f16[GGML_TYPE_COUNT][FA_HEAD_SIZE_COUNT][2][2][2];
  444. vk_pipeline pipeline_flash_attn_split_k_reduce;
  445. std::unordered_map<std::string, vk_pipeline_ref> pipelines;
  446. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  447. vk::Fence fence;
  448. vk_buffer sync_staging;
  449. ggml_backend_buffer_type buffer_type;
  450. bool disable_fusion;
  451. bool disable_host_visible_vidmem;
  452. #ifdef GGML_VULKAN_MEMORY_DEBUG
  453. std::unique_ptr<vk_memory_logger> memory_logger;
  454. #endif
  455. // for GGML_VK_PERF_LOGGER
  456. std::unique_ptr<vk_perf_logger> perf_logger;
  457. vk::QueryPool query_pool;
  458. int32_t num_queries;
  459. ~vk_device_struct() {
  460. VK_LOG_DEBUG("destroy device " << name);
  461. device.destroyFence(fence);
  462. ggml_vk_destroy_buffer(sync_staging);
  463. compute_queue.cmd_pool.destroy(device);
  464. transfer_queue.cmd_pool.destroy(device);
  465. for (auto& pipeline : pipelines) {
  466. if (pipeline.second.expired()) {
  467. continue;
  468. }
  469. vk_pipeline pl = pipeline.second.lock();
  470. ggml_vk_destroy_pipeline(device, pl);
  471. }
  472. pipelines.clear();
  473. device.destroyDescriptorSetLayout(dsl);
  474. device.destroy();
  475. }
  476. };
  477. void vk_command_pool::init(vk_device& device, vk_queue *q_) {
  478. cmd_buffer_idx = 0;
  479. q = q_;
  480. vk::CommandPoolCreateInfo command_pool_create_info(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), q->queue_family_index);
  481. pool = device->device.createCommandPool(command_pool_create_info);
  482. }
  483. void vk_command_pool::destroy(vk::Device& device) {
  484. device.destroyCommandPool(pool);
  485. pool = nullptr;
  486. cmd_buffers.clear();
  487. }
  488. struct vk_buffer_struct {
  489. vk::Buffer buffer = VK_NULL_HANDLE;
  490. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  491. vk::MemoryPropertyFlags memory_property_flags;
  492. void * ptr;
  493. size_t size = 0;
  494. vk_device device;
  495. ~vk_buffer_struct() {
  496. if (size == 0) {
  497. return;
  498. }
  499. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  500. device->device.freeMemory(device_memory);
  501. device->device.destroyBuffer(buffer);
  502. }
  503. };
  504. struct vk_subbuffer {
  505. vk_buffer buffer;
  506. uint64_t offset;
  507. uint64_t size;
  508. operator vk::DescriptorBufferInfo() const {
  509. return { buffer->buffer, offset, size };
  510. }
  511. };
  512. struct vk_semaphore {
  513. vk::Semaphore s;
  514. uint64_t value;
  515. };
  516. struct vk_submission {
  517. vk::CommandBuffer buffer;
  518. std::vector<vk_semaphore> wait_semaphores;
  519. std::vector<vk_semaphore> signal_semaphores;
  520. };
  521. typedef std::vector<vk_submission> vk_sequence;
  522. struct vk_mat_mat_push_constants {
  523. uint32_t M; uint32_t N; uint32_t K;
  524. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  525. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  526. uint32_t k_split;
  527. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  528. uint32_t padded_N;
  529. };
  530. struct vk_mat_vec_push_constants {
  531. uint32_t ncols; uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  532. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  533. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  534. };
  535. struct vk_mat_mat_id_push_constants {
  536. uint32_t M; uint32_t N; uint32_t K;
  537. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  538. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  539. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  540. uint32_t padded_N;
  541. };
  542. struct vk_mat_vec_id_push_constants {
  543. uint32_t ncols; uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  544. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  545. uint32_t nei0; uint32_t ne11;
  546. };
  547. struct vk_flash_attn_push_constants {
  548. uint32_t N;
  549. uint32_t KV;
  550. uint32_t ne1;
  551. uint32_t ne2;
  552. uint32_t ne3;
  553. uint32_t neq2;
  554. uint32_t neq3;
  555. uint32_t nek2;
  556. uint32_t nek3;
  557. uint32_t nev2;
  558. uint32_t nev3;
  559. uint32_t nem1;
  560. uint32_t nem2;
  561. uint32_t nem3;
  562. uint32_t nb01;
  563. uint32_t nb02;
  564. uint32_t nb03;
  565. uint32_t nb11;
  566. uint32_t nb12;
  567. uint32_t nb13;
  568. uint32_t nb21;
  569. uint32_t nb22;
  570. uint32_t nb23;
  571. float scale;
  572. float max_bias;
  573. float logit_softcap;
  574. uint32_t mask_n_head_log2;
  575. float m0;
  576. float m1;
  577. uint32_t gqa_ratio;
  578. uint32_t split_kv;
  579. uint32_t k_num;
  580. };
  581. static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128");
  582. struct vk_op_push_constants {
  583. uint32_t KX;
  584. uint32_t KY;
  585. float param1;
  586. float param2;
  587. };
  588. struct vk_op_glu_push_constants {
  589. uint32_t N;
  590. uint32_t ne00;
  591. uint32_t ne20;
  592. uint32_t mode; // 0: default, 1: swapped, 2: split
  593. float alpha; // for swiglu_oai
  594. float limit;
  595. };
  596. struct vk_op_unary_push_constants {
  597. uint32_t ne;
  598. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  599. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  600. uint32_t misalign_offsets;
  601. float param1; float param2;
  602. uint32_t ne0_012mp; uint32_t ne0_012L;
  603. uint32_t ne0_01mp; uint32_t ne0_01L;
  604. uint32_t ne0_0mp; uint32_t ne0_0L;
  605. uint32_t ne1_012mp; uint32_t ne1_012L;
  606. uint32_t ne1_01mp; uint32_t ne1_01L;
  607. uint32_t ne1_0mp; uint32_t ne1_0L;
  608. };
  609. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  610. static vk_op_unary_push_constants vk_op_unary_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst, int64_t ne = 0) {
  611. GGML_ASSERT(ne != 0 || (ggml_nelements(src0) == ggml_nelements(dst)));
  612. ne = ne != 0 ? ne : ggml_nelements(dst);
  613. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  614. vk_op_unary_push_constants p{};
  615. p.ne = (uint32_t)ne;
  616. size_t src0_tsize = ggml_type_size(src0->type);
  617. p.ne00 = (uint32_t)src0->ne[0];
  618. p.ne01 = (uint32_t)src0->ne[1];
  619. p.ne02 = (uint32_t)src0->ne[2];
  620. p.ne03 = (uint32_t)src0->ne[3];
  621. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  622. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  623. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  624. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  625. size_t dst_tsize = ggml_type_size(dst->type);
  626. p.ne10 = (uint32_t)dst->ne[0];
  627. p.ne11 = (uint32_t)dst->ne[1];
  628. p.ne12 = (uint32_t)dst->ne[2];
  629. p.ne13 = (uint32_t)dst->ne[3];
  630. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  631. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  632. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  633. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  634. return p; // fastdiv values and offsets are initialized later in ggml_vk_op
  635. }
  636. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  637. // Precompute mp (m' in the paper) and L such that division
  638. // can be computed using a multiply (high 32b of 64b result)
  639. // and a shift:
  640. //
  641. // n/d = (mulhi(n, mp) + n) >> L;
  642. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  643. {
  644. // compute L = ceil(log2(d));
  645. L = 0;
  646. while (L < 32 && (uint32_t{1} << L) < d) {
  647. L++;
  648. }
  649. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  650. }
  651. template <typename T> void init_pushconst_fastdiv(T &p) {
  652. GGML_UNUSED(p);
  653. static_assert(!std::is_const<T>::value, "unexpected type");
  654. }
  655. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  656. // Compute magic values to divide by these six numbers.
  657. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  658. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  659. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  660. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  661. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  662. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  663. }
  664. struct vk_op_binary_push_constants {
  665. uint32_t ne;
  666. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  667. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  668. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  669. uint32_t misalign_offsets;
  670. float param1; float param2; int32_t param3;
  671. };
  672. struct vk_op_multi_add_push_constants {
  673. // shape for dst
  674. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23;
  675. // strides for srcs+dst
  676. uint32_t nb[8][4];
  677. };
  678. struct vk_op_add_id_push_constants {
  679. uint32_t ne0;
  680. uint32_t ne1;
  681. uint32_t s01;
  682. uint32_t s02;
  683. uint32_t s11;
  684. uint32_t s21;
  685. };
  686. struct vk_op_diag_mask_push_constants {
  687. uint32_t ncols;
  688. uint32_t rows_per_channel;
  689. int32_t n_past;
  690. };
  691. struct vk_op_rope_push_constants {
  692. uint32_t ncols;
  693. uint32_t n_dims;
  694. float freq_scale;
  695. uint32_t p_delta_rows;
  696. float freq_base;
  697. float ext_factor;
  698. float attn_factor;
  699. float corr_dims[2];
  700. float theta_scale;
  701. uint32_t has_ff;
  702. uint32_t ne02;
  703. uint32_t s1;
  704. uint32_t s2;
  705. int32_t sections[4];
  706. uint32_t is_back;
  707. };
  708. struct vk_op_soft_max_push_constants {
  709. uint32_t KX;
  710. uint32_t KY;
  711. uint32_t ne00;
  712. uint32_t ne01;
  713. uint32_t ne02;
  714. uint32_t ne12;
  715. uint32_t ne13;
  716. uint32_t nb11;
  717. uint32_t nb12;
  718. uint32_t nb13;
  719. float scale;
  720. float max_bias;
  721. float m0;
  722. float m1;
  723. uint32_t n_head_log2;
  724. uint32_t nrows_x;
  725. uint32_t has_sinks;
  726. };
  727. struct vk_op_argsort_push_constants {
  728. uint32_t ncols;
  729. int32_t order;
  730. };
  731. struct vk_op_im2col_push_constants {
  732. uint32_t batch_offset; uint32_t offset_delta;
  733. uint32_t IC;
  734. uint32_t IW; uint32_t IH;
  735. uint32_t OW; uint32_t OH;
  736. uint32_t KW; uint32_t KH;
  737. uint32_t pelements;
  738. uint32_t CHW;
  739. int32_t s0; int32_t s1;
  740. int32_t p0; int32_t p1;
  741. int32_t d0; int32_t d1;
  742. };
  743. struct vk_op_timestep_embedding_push_constants {
  744. uint32_t nb1;
  745. uint32_t dim;
  746. uint32_t max_period;
  747. };
  748. struct vk_op_conv_transpose_1d_push_constants {
  749. uint32_t Cout;
  750. uint32_t Cin;
  751. uint32_t K;
  752. uint32_t L;
  753. uint32_t KL;
  754. uint32_t nb01;
  755. uint32_t nb02;
  756. uint32_t nb11;
  757. uint32_t nb1;
  758. int32_t s0;
  759. };
  760. struct vk_op_pool2d_push_constants {
  761. uint32_t IW; uint32_t IH;
  762. uint32_t OW; uint32_t OH;
  763. uint32_t OC;
  764. uint32_t pelements;
  765. uint32_t op;
  766. int32_t k0; int32_t k1;
  767. int32_t s0; int32_t s1;
  768. int32_t p0; int32_t p1;
  769. };
  770. struct vk_op_rwkv_wkv6_push_constants {
  771. uint32_t B;
  772. uint32_t T;
  773. uint32_t C;
  774. uint32_t H;
  775. };
  776. struct vk_op_rwkv_wkv7_push_constants {
  777. uint32_t B;
  778. uint32_t T;
  779. uint32_t C;
  780. uint32_t H;
  781. };
  782. struct vk_op_conv2d_push_constants {
  783. uint32_t Cout;
  784. uint32_t Cin;
  785. uint32_t N;
  786. uint32_t KW;
  787. uint32_t KH;
  788. uint32_t W;
  789. uint32_t H;
  790. uint32_t OW;
  791. uint32_t OH;
  792. uint32_t s0;
  793. uint32_t s1;
  794. uint32_t p0;
  795. uint32_t p1;
  796. uint32_t d0;
  797. uint32_t d1;
  798. uint32_t nb01;
  799. uint32_t nb02;
  800. uint32_t nb03;
  801. uint32_t nb11;
  802. uint32_t nb12;
  803. uint32_t nb13;
  804. uint32_t nb1;
  805. uint32_t nb2;
  806. uint32_t nb3;
  807. // init_fastdiv_values constants for dividing by KW, KW*KH, OW, OW*OH
  808. uint32_t KWmp; uint32_t KWL;
  809. uint32_t KWKHmp; uint32_t KWKHL;
  810. uint32_t OWmp; uint32_t OWL;
  811. uint32_t OWOHmp; uint32_t OWOHL;
  812. };
  813. template <> void init_pushconst_fastdiv(vk_op_conv2d_push_constants &p) {
  814. // Compute magic values to divide by KW, KW*KH, OW, OW*OH
  815. init_fastdiv_values(p.KW, p.KWmp, p.KWL);
  816. init_fastdiv_values(p.KW*p.KH, p.KWKHmp, p.KWKHL);
  817. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  818. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  819. }
  820. struct vk_op_conv2d_dw_push_constants {
  821. uint32_t ne;
  822. uint32_t batches;
  823. uint32_t channels;
  824. uint32_t dst_w;
  825. uint32_t dst_h;
  826. uint32_t src_w;
  827. uint32_t src_h;
  828. uint32_t knl_w;
  829. uint32_t knl_h;
  830. int32_t stride_x;
  831. int32_t stride_y;
  832. int32_t pad_x;
  833. int32_t pad_y;
  834. int32_t dilation_x;
  835. int32_t dilation_y;
  836. };
  837. struct vk_op_upscale_push_constants {
  838. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  839. uint32_t ne00; uint32_t ne01;
  840. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  841. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  842. float sf0; float sf1; float sf2; float sf3;
  843. };
  844. // Allow pre-recording command buffers
  845. struct vk_staging_memcpy {
  846. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  847. void * dst;
  848. const void * src;
  849. size_t n;
  850. };
  851. struct vk_context_struct {
  852. vk_submission * s;
  853. std::vector<vk_sequence> seqs;
  854. int exit_tensor_idx;
  855. std::vector<vk_staging_memcpy> in_memcpys;
  856. std::vector<vk_staging_memcpy> out_memcpys;
  857. vk_command_pool * p {};
  858. };
  859. typedef std::shared_ptr<vk_context_struct> vk_context;
  860. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  861. struct ggml_vk_garbage_collector {
  862. std::vector<vk_semaphore> tl_semaphores;
  863. std::vector<vk_semaphore> semaphores;
  864. std::vector<vk::Event> events;
  865. std::vector<vk_buffer> temp_buffers;
  866. std::vector<vk_context> contexts;
  867. };
  868. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  869. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  870. static std::string format_size(size_t size) {
  871. const size_t kib = 1024;
  872. const size_t mib = kib * 1024;
  873. const size_t gib = mib * 1024;
  874. std::ostringstream oss;
  875. oss << std::fixed << std::setprecision(2);
  876. if (size >= gib) {
  877. oss << static_cast<double>(size) / gib << " GiB";
  878. } else if (size >= mib) {
  879. oss << static_cast<double>(size) / mib << " MiB";
  880. } else if (size >= kib) {
  881. oss << static_cast<double>(size) / kib << " KiB";
  882. } else {
  883. oss << size << " B";
  884. }
  885. return oss.str();
  886. }
  887. static std::mutex log_mutex;
  888. class vk_memory_logger {
  889. public:
  890. vk_memory_logger(): total_device(0), total_host(0) {}
  891. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  892. void log_deallocation(vk_buffer_ref buf_ref);
  893. private:
  894. std::map<vk::Buffer, size_t> allocations; // Track allocations
  895. size_t total_device;
  896. size_t total_host;
  897. };
  898. #else
  899. #define VK_LOG_MEMORY(msg) ((void) 0)
  900. #endif // GGML_VULKAN_MEMORY_DEBUG
  901. class vk_perf_logger {
  902. public:
  903. void print_timings() {
  904. if (timings.empty()) {
  905. return;
  906. }
  907. uint64_t total_all_op_times = 0;
  908. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  909. for (const auto & t : timings) {
  910. uint64_t total_op_times = 0;
  911. for (const auto & time : t.second) {
  912. total_op_times += time;
  913. }
  914. std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0)
  915. << " us";
  916. // If we have as many flops entries as timing entries for the op, then compute and log the flops/S.
  917. auto it = flops.find(t.first);
  918. if (it != flops.end() && (it->second).size() == t.second.size()) {
  919. uint64_t total_op_flops = 0;
  920. for (const auto & elem : it->second) {
  921. total_op_flops += elem;
  922. }
  923. std::cerr << " ("
  924. << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) /
  925. (double(total_op_times) / (1000.0 * 1000.0 * 1000.0))
  926. << " GFLOPS/s)";
  927. }
  928. total_all_op_times += total_op_times;
  929. std::cerr << std::endl;
  930. }
  931. if (timings.size() > 0) {
  932. std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl;
  933. }
  934. timings.clear();
  935. flops.clear();
  936. }
  937. void log_timing(const ggml_tensor * node, uint64_t time) {
  938. if (node->op == GGML_OP_UNARY) {
  939. timings[ggml_unary_op_name(ggml_get_unary_op(node))].push_back(time);
  940. return;
  941. }
  942. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  943. const uint64_t m = node->src[0]->ne[1];
  944. const uint64_t n = node->ne[1];
  945. const uint64_t k = node->src[1]->ne[0];
  946. const uint64_t batch = node->src[1]->ne[2] * node->src[1]->ne[3];
  947. std::string name = ggml_op_name(node->op);
  948. if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) ||
  949. (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) {
  950. name += "_VEC";
  951. }
  952. name += " ";
  953. name += ggml_type_name(node->src[0]->type);
  954. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  955. if (batch > 1) {
  956. name += " batch=" + std::to_string(batch);
  957. }
  958. timings[name].push_back(time);
  959. flops[name].push_back(m * n * (k + (k - 1)) * batch);
  960. return;
  961. }
  962. if (node->op == GGML_OP_CONV_2D) {
  963. std::string name = ggml_op_name(node->op);
  964. ggml_tensor * knl = node->src[0];
  965. uint64_t OW = node->ne[0];
  966. uint64_t OH = node->ne[1];
  967. uint64_t N = node->ne[3];
  968. uint64_t Cout = node->ne[2];
  969. uint64_t KW = knl->ne[0];
  970. uint64_t KH = knl->ne[1];
  971. uint64_t Cin = knl->ne[2];
  972. // KxCRS @ CRSxNPQ = KxNPQ -> M=K, K=CRS, N=NPQ
  973. uint64_t size_M = Cout;
  974. uint64_t size_K = Cin * KW * KH;
  975. uint64_t size_N = N * OW * OH;
  976. uint64_t n_flops = size_M * size_N * (size_K + (size_K - 1));
  977. name += " M=Cout=" + std::to_string(size_M) + ", K=Cin*KW*KH=" + std::to_string(size_K) +
  978. ", N=N*OW*OH=" + std::to_string(size_N);
  979. flops[name].push_back(n_flops);
  980. timings[name].push_back(time);
  981. return;
  982. }
  983. timings[ggml_op_name(node->op)].push_back(time);
  984. }
  985. private:
  986. std::map<std::string, std::vector<uint64_t>> timings;
  987. std::map<std::string, std::vector<uint64_t>> flops;
  988. };
  989. struct ggml_backend_vk_context {
  990. std::string name;
  991. vk_device device;
  992. size_t semaphore_idx, event_idx;
  993. ggml_vk_garbage_collector gc;
  994. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k;
  995. vk_buffer prealloc_x, prealloc_y, prealloc_split_k;
  996. vk::Fence fence, almost_ready_fence;
  997. bool almost_ready_fence_pending {};
  998. vk_buffer buffer_pool[MAX_VK_BUFFERS];
  999. vk_context_ref compute_ctx;
  1000. vk_context_ref transfer_ctx;
  1001. std::vector<vk_context_ref> tensor_ctxs;
  1002. std::vector<vk::DescriptorPool> descriptor_pools;
  1003. std::vector<vk::DescriptorSet> descriptor_sets;
  1004. uint32_t descriptor_set_idx {};
  1005. uint32_t pipeline_descriptor_set_requirements {};
  1006. vk_command_pool compute_cmd_pool;
  1007. vk_command_pool transfer_cmd_pool;
  1008. // number of additional consecutive nodes that are being fused with the
  1009. // node currently being processed
  1010. int num_additional_fused_ops {};
  1011. };
  1012. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  1013. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  1014. if (tensor->view_src) {
  1015. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  1016. }
  1017. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  1018. }
  1019. struct ggml_backend_vk_buffer_context {
  1020. vk_device_ref device;
  1021. vk_buffer dev_buffer;
  1022. std::string name;
  1023. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  1024. device(device),
  1025. dev_buffer(dev_buffer),
  1026. name(name) {
  1027. }
  1028. ~ggml_backend_vk_buffer_context() {
  1029. ggml_vk_destroy_buffer(dev_buffer);
  1030. }
  1031. };
  1032. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1033. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  1034. std::lock_guard<std::mutex> guard(log_mutex);
  1035. vk_buffer buf = buf_ref.lock();
  1036. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1037. const std::string type = device ? "device" : "host";
  1038. allocations[buf->buffer] = size;
  1039. total_device += device ? size : 0;
  1040. total_host += device ? 0 : size;
  1041. 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));
  1042. }
  1043. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  1044. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  1045. return;
  1046. }
  1047. std::lock_guard<std::mutex> guard(log_mutex);
  1048. vk_buffer buf = buf_ref.lock();
  1049. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1050. std::string type = device ? "device" : "host";
  1051. auto it = allocations.find(buf->buffer);
  1052. total_device -= device ? it->second : 0;
  1053. total_host -= device ? 0 : it->second;
  1054. if (it != allocations.end()) {
  1055. 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));
  1056. allocations.erase(it);
  1057. } else {
  1058. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  1059. }
  1060. }
  1061. #endif // GGML_VULKAN_MEMORY_DEBUG
  1062. struct vk_instance_t {
  1063. vk::Instance instance;
  1064. bool debug_utils_support = false; // VK_EXT_debug_utils enabled
  1065. PFN_vkSetDebugUtilsObjectNameEXT pfn_vkSetDebugUtilsObjectNameEXT = {};
  1066. PFN_vkQueueBeginDebugUtilsLabelEXT pfn_vkQueueBeginDebugUtilsLabelEXT = {};
  1067. PFN_vkQueueEndDebugUtilsLabelEXT pfn_vkQueueEndDebugUtilsLabelEXT = {};
  1068. PFN_vkCmdBeginDebugUtilsLabelEXT pfn_vkCmdBeginDebugUtilsLabelEXT = {};
  1069. PFN_vkCmdEndDebugUtilsLabelEXT pfn_vkCmdEndDebugUtilsLabelEXT = {};
  1070. PFN_vkCmdInsertDebugUtilsLabelEXT pfn_vkCmdInsertDebugUtilsLabelEXT = {};
  1071. std::vector<size_t> device_indices;
  1072. vk_device devices[GGML_VK_MAX_DEVICES];
  1073. };
  1074. static bool vk_instance_initialized = false;
  1075. static vk_instance_t vk_instance;
  1076. static bool vk_perf_logger_enabled = false;
  1077. #ifdef GGML_VULKAN_CHECK_RESULTS
  1078. static size_t vk_skip_checks;
  1079. static size_t vk_output_tensor;
  1080. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  1081. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1082. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1083. #endif
  1084. 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);
  1085. static void ggml_backend_vk_free(ggml_backend_t backend);
  1086. // Wait for ctx->fence to be signaled.
  1087. static void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) {
  1088. // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep
  1089. // during this wait.
  1090. if (ctx->almost_ready_fence_pending) {
  1091. VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence");
  1092. ctx->device->device.resetFences({ ctx->almost_ready_fence });
  1093. ctx->almost_ready_fence_pending = false;
  1094. }
  1095. // Spin (w/pause) waiting for the graph to finish executing.
  1096. vk::Result result;
  1097. while ((result = ctx->device->device.getFenceStatus(ctx->fence)) != vk::Result::eSuccess) {
  1098. if (result != vk::Result::eNotReady) {
  1099. fprintf(stderr, "ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__);
  1100. exit(1);
  1101. }
  1102. for (uint32_t i = 0; i < 100; ++i) {
  1103. YIELD();
  1104. YIELD();
  1105. YIELD();
  1106. YIELD();
  1107. YIELD();
  1108. YIELD();
  1109. YIELD();
  1110. YIELD();
  1111. YIELD();
  1112. YIELD();
  1113. }
  1114. }
  1115. ctx->device->device.resetFences({ ctx->fence });
  1116. }
  1117. // variables to track number of compiles in progress
  1118. static uint32_t compile_count = 0;
  1119. static std::mutex compile_count_mutex;
  1120. static std::condition_variable compile_count_cond;
  1121. 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,
  1122. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  1123. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  1124. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  1125. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  1126. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  1127. GGML_ASSERT(parameter_count > 0);
  1128. GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT);
  1129. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  1130. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  1131. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  1132. vk::PushConstantRange pcr(
  1133. vk::ShaderStageFlagBits::eCompute,
  1134. 0,
  1135. pipeline->push_constant_size
  1136. );
  1137. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr);
  1138. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  1139. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  1140. for (size_t i = 0; i < specialization_constants.size(); i++) {
  1141. specialization_entries[i].constantID = i;
  1142. specialization_entries[i].offset = i * sizeof(uint32_t);
  1143. specialization_entries[i].size = sizeof(uint32_t);
  1144. }
  1145. vk::SpecializationInfo specialization_info(
  1146. specialization_entries.size(),
  1147. specialization_entries.data(),
  1148. specialization_constants.size() * sizeof(uint32_t),
  1149. specialization_constants.data()
  1150. );
  1151. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  1152. if (device->subgroup_require_full_support && require_full_subgroups) {
  1153. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  1154. }
  1155. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  1156. pipeline_shader_stage_create_flags,
  1157. vk::ShaderStageFlagBits::eCompute,
  1158. pipeline->shader_module,
  1159. entrypoint.c_str(),
  1160. &specialization_info);
  1161. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  1162. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  1163. if (device->subgroup_size_control && required_subgroup_size > 0) {
  1164. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  1165. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  1166. }
  1167. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  1168. vk::PipelineCreateFlags{},
  1169. pipeline_shader_create_info,
  1170. pipeline->layout);
  1171. vk::PipelineRobustnessCreateInfoEXT rci;
  1172. if (device->pipeline_robustness && disable_robustness) {
  1173. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1174. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1175. compute_pipeline_create_info.setPNext(&rci);
  1176. }
  1177. try {
  1178. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  1179. } catch (const vk::SystemError& e) {
  1180. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  1181. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1182. throw e;
  1183. }
  1184. pipeline->compiled = true;
  1185. if (vk_instance.debug_utils_support) {
  1186. vk::DebugUtilsObjectNameInfoEXT duoni;
  1187. duoni.objectType = vk::ObjectType::ePipeline;
  1188. duoni.pObjectName = pipeline->name.c_str();
  1189. duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast<VkPipeline>(pipeline->pipeline));
  1190. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast<VkDebugUtilsObjectNameInfoEXT &>(duoni));
  1191. }
  1192. {
  1193. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1194. device->pipelines.insert({ pipeline->name, pipeline });
  1195. }
  1196. {
  1197. std::lock_guard<std::mutex> guard(compile_count_mutex);
  1198. assert(compile_count > 0);
  1199. compile_count--;
  1200. }
  1201. compile_count_cond.notify_all();
  1202. }
  1203. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  1204. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  1205. device.destroyPipelineLayout(pipeline->layout);
  1206. device.destroyShaderModule(pipeline->shader_module);
  1207. device.destroyPipeline(pipeline->pipeline);
  1208. }
  1209. static void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) {
  1210. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  1211. ctx->pipeline_descriptor_set_requirements += n;
  1212. if (!pipeline->compiled) {
  1213. pipeline->needed = true;
  1214. ctx->device->need_compiles = true;
  1215. }
  1216. }
  1217. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
  1218. if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) {
  1219. // Enough descriptors are available
  1220. return;
  1221. }
  1222. vk_device& device = ctx->device;
  1223. uint32_t to_alloc = ctx->pipeline_descriptor_set_requirements - ctx->descriptor_sets.size();
  1224. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1225. uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1226. while (to_alloc > 0) {
  1227. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  1228. to_alloc -= alloc_count;
  1229. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1230. if (pool_idx >= ctx->descriptor_pools.size()) {
  1231. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  1232. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  1233. ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  1234. }
  1235. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  1236. for (uint32_t i = 0; i < alloc_count; i++) {
  1237. layouts[i] = device->dsl;
  1238. }
  1239. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
  1240. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  1241. ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
  1242. pool_idx++;
  1243. }
  1244. }
  1245. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) {
  1246. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  1247. if (p.cmd_buffers.size() > p.cmd_buffer_idx) {
  1248. // Reuse command buffer
  1249. return p.cmd_buffers[p.cmd_buffer_idx++];
  1250. }
  1251. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  1252. p.pool,
  1253. vk::CommandBufferLevel::ePrimary,
  1254. 1);
  1255. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  1256. auto buf = cmd_buffers.front();
  1257. p.cmd_buffers.push_back(buf);
  1258. p.cmd_buffer_idx++;
  1259. return buf;
  1260. }
  1261. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  1262. if (ctx->seqs.empty()) {
  1263. if (fence) {
  1264. std::lock_guard<std::mutex> guard(queue_mutex);
  1265. ctx->p->q->queue.submit({}, fence);
  1266. }
  1267. return;
  1268. }
  1269. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  1270. std::vector<std::vector<uint64_t>> tl_wait_vals;
  1271. std::vector<std::vector<uint64_t>> tl_signal_vals;
  1272. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  1273. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  1274. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  1275. std::vector<vk::SubmitInfo> submit_infos;
  1276. int idx = -1;
  1277. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  1278. size_t reserve = 0;
  1279. for (const auto& sequence : ctx->seqs) {
  1280. reserve += sequence.size();
  1281. }
  1282. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  1283. tl_wait_semaphores.reserve(reserve);
  1284. tl_wait_vals.reserve(reserve);
  1285. tl_signal_semaphores.reserve(reserve);
  1286. tl_signal_vals.reserve(reserve);
  1287. tl_submit_infos.reserve(reserve);
  1288. submit_infos.reserve(reserve);
  1289. stage_flags.reserve(reserve);
  1290. for (const auto& sequence : ctx->seqs) {
  1291. for (const auto& submission : sequence) {
  1292. stage_flags.push_back({});
  1293. idx++;
  1294. tl_wait_vals.push_back({});
  1295. tl_wait_semaphores.push_back({});
  1296. tl_signal_vals.push_back({});
  1297. tl_signal_semaphores.push_back({});
  1298. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  1299. stage_flags[idx].push_back(ctx->p->q->stage_flags);
  1300. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  1301. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  1302. }
  1303. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  1304. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  1305. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  1306. }
  1307. tl_submit_infos.push_back({
  1308. (uint32_t) submission.wait_semaphores.size(),
  1309. tl_wait_vals[idx].data(),
  1310. (uint32_t) submission.signal_semaphores.size(),
  1311. tl_signal_vals[idx].data(),
  1312. });
  1313. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  1314. tl_submit_infos[idx].pNext = nullptr;
  1315. vk::SubmitInfo si{
  1316. (uint32_t) submission.wait_semaphores.size(),
  1317. tl_wait_semaphores[idx].data(),
  1318. stage_flags[idx].data(),
  1319. 1,
  1320. &submission.buffer,
  1321. (uint32_t) submission.signal_semaphores.size(),
  1322. tl_signal_semaphores[idx].data(),
  1323. };
  1324. si.setPNext(&tl_submit_infos[idx]);
  1325. submit_infos.push_back(si);
  1326. }
  1327. }
  1328. std::lock_guard<std::mutex> guard(queue_mutex);
  1329. ctx->p->q->queue.submit(submit_infos, fence);
  1330. ctx->seqs.clear();
  1331. }
  1332. 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) {
  1333. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  1334. const uint32_t qfsize = queue_family_props.size();
  1335. // Try with avoid preferences first
  1336. for (uint32_t i = 0; i < qfsize; i++) {
  1337. 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)) {
  1338. return i;
  1339. }
  1340. }
  1341. // Fall back to only required
  1342. for (size_t i = 0; i < qfsize; i++) {
  1343. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  1344. return i;
  1345. }
  1346. }
  1347. // Fall back to reusing compute queue
  1348. for (size_t i = 0; i < qfsize; i++) {
  1349. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  1350. return i;
  1351. }
  1352. }
  1353. // Fall back to ignoring min_num_queries
  1354. for (size_t i = 0; i < qfsize; i++) {
  1355. if (queue_family_props[i].queueFlags & required) {
  1356. return i;
  1357. }
  1358. }
  1359. // 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.
  1360. // 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.
  1361. if (compute_index >= 0) {
  1362. return compute_index;
  1363. }
  1364. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  1365. for(auto &q_family : queue_family_props) {
  1366. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  1367. }
  1368. abort();
  1369. }
  1370. 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) {
  1371. VK_LOG_DEBUG("ggml_vk_create_queue()");
  1372. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1373. q.queue_family_index = queue_family_index;
  1374. q.transfer_only = transfer_only;
  1375. q.cmd_pool.init(device, &q);
  1376. q.queue = device->device.getQueue(queue_family_index, queue_index);
  1377. q.stage_flags = stage_flags;
  1378. }
  1379. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) {
  1380. vk_context result = std::make_shared<vk_context_struct>();
  1381. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  1382. ctx->gc.contexts.emplace_back(result);
  1383. result->p = &p;
  1384. return result;
  1385. }
  1386. static vk_context ggml_vk_create_temporary_context(vk_command_pool& p) {
  1387. vk_context result = std::make_shared<vk_context_struct>();
  1388. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  1389. result->p = &p;
  1390. return result;
  1391. }
  1392. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  1393. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1394. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  1395. vk::SemaphoreCreateInfo ci{};
  1396. ci.setPNext(&tci);
  1397. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1398. ctx->gc.semaphores.push_back({ semaphore, 0 });
  1399. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  1400. }
  1401. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  1402. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1403. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  1404. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  1405. vk::SemaphoreCreateInfo ci{};
  1406. ci.setPNext(&tci);
  1407. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1408. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  1409. }
  1410. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  1411. }
  1412. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  1413. if (ctx->event_idx >= ctx->gc.events.size()) {
  1414. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  1415. }
  1416. return ctx->gc.events[ctx->event_idx++];
  1417. }
  1418. static void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) {
  1419. VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()");
  1420. // Requires command buffers to be done
  1421. device->device.resetCommandPool(p.pool);
  1422. p.cmd_buffer_idx = 0;
  1423. }
  1424. static void ggml_vk_queue_command_pools_cleanup(vk_device& device) {
  1425. VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()");
  1426. // Arbitrary frequency to cleanup/reuse command buffers
  1427. static constexpr uint32_t cleanup_frequency = 10;
  1428. if (device->compute_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1429. ggml_vk_command_pool_cleanup(device, device->compute_queue.cmd_pool);
  1430. }
  1431. if (device->transfer_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1432. ggml_vk_command_pool_cleanup(device, device->transfer_queue.cmd_pool);
  1433. }
  1434. }
  1435. static uint32_t find_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  1436. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  1437. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  1438. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  1439. (flags & memory_type.propertyFlags) == flags &&
  1440. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  1441. return static_cast<int32_t>(i);
  1442. }
  1443. }
  1444. return UINT32_MAX;
  1445. }
  1446. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, vk::MemoryPropertyFlags req_flags, vk::MemoryPropertyFlags fallback_flags = vk::MemoryPropertyFlags(0)) {
  1447. VK_LOG_DEBUG("ggml_vk_create_buffer(" << device->name << ", " << size << ", " << to_string(req_flags) << ", " << to_string(fallback_flags) << ")");
  1448. if (size > device->max_memory_allocation_size) {
  1449. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device memory allocation limit");
  1450. }
  1451. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  1452. if (size == 0) {
  1453. buf->size = 0;
  1454. return buf;
  1455. }
  1456. vk::BufferCreateInfo buffer_create_info{
  1457. vk::BufferCreateFlags(),
  1458. size,
  1459. vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst,
  1460. vk::SharingMode::eExclusive,
  1461. 0,
  1462. nullptr,
  1463. };
  1464. buf->buffer = device->device.createBuffer(buffer_create_info);
  1465. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  1466. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  1467. uint32_t memory_type_index = UINT32_MAX;
  1468. memory_type_index = find_properties(&mem_props, &mem_req, req_flags);
  1469. buf->memory_property_flags = req_flags;
  1470. if (memory_type_index == UINT32_MAX && fallback_flags) {
  1471. memory_type_index = find_properties(&mem_props, &mem_req, fallback_flags);
  1472. buf->memory_property_flags = fallback_flags;
  1473. }
  1474. if (memory_type_index == UINT32_MAX) {
  1475. device->device.destroyBuffer(buf->buffer);
  1476. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  1477. }
  1478. try {
  1479. buf->device_memory = device->device.allocateMemory({ mem_req.size, memory_type_index });
  1480. } catch (const vk::SystemError& e) {
  1481. if (buf->memory_property_flags != fallback_flags) {
  1482. // Try again with fallback flags
  1483. memory_type_index = find_properties(&mem_props, &mem_req, fallback_flags);
  1484. buf->memory_property_flags = fallback_flags;
  1485. try {
  1486. buf->device_memory = device->device.allocateMemory({ mem_req.size, memory_type_index });
  1487. }
  1488. catch (const vk::SystemError& e) {
  1489. device->device.destroyBuffer(buf->buffer);
  1490. throw e;
  1491. }
  1492. } else {
  1493. // Out of Host/Device memory, clean up buffer
  1494. device->device.destroyBuffer(buf->buffer);
  1495. throw e;
  1496. }
  1497. }
  1498. buf->ptr = nullptr;
  1499. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1500. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  1501. }
  1502. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  1503. buf->device = device;
  1504. buf->size = size;
  1505. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1506. device->memory_logger->log_allocation(buf, size);
  1507. #endif
  1508. return buf;
  1509. }
  1510. 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)) {
  1511. try {
  1512. return ggml_vk_create_buffer(device, size, req_flags, fallback_flags);
  1513. } catch (const vk::SystemError& e) {
  1514. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  1515. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1516. throw e;
  1517. }
  1518. }
  1519. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  1520. vk_buffer buf;
  1521. try {
  1522. if (device->prefer_host_memory) {
  1523. buf = ggml_vk_create_buffer(device, size, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, vk::MemoryPropertyFlagBits::eDeviceLocal);
  1524. } else if (device->uma) {
  1525. // Fall back to host memory type
  1526. buf = ggml_vk_create_buffer(device, size, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  1527. } else if (device->disable_host_visible_vidmem) {
  1528. buf = ggml_vk_create_buffer(device, size, vk::MemoryPropertyFlagBits::eDeviceLocal, vk::MemoryPropertyFlagBits::eDeviceLocal);
  1529. } else {
  1530. // use rebar if available, otherwise fallback to device only visible memory
  1531. buf = ggml_vk_create_buffer(device, size, vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, vk::MemoryPropertyFlagBits::eDeviceLocal);
  1532. }
  1533. } catch (const vk::SystemError& e) {
  1534. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  1535. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1536. throw e;
  1537. }
  1538. return buf;
  1539. }
  1540. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  1541. if (buf == nullptr) {
  1542. return;
  1543. }
  1544. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1545. if (buf->device != nullptr) {
  1546. buf->device->memory_logger->log_deallocation(buf);
  1547. }
  1548. #endif
  1549. buf.reset();
  1550. }
  1551. static vk_subbuffer ggml_vk_subbuffer(vk_buffer& buf) {
  1552. return { buf, 0, VK_WHOLE_SIZE };
  1553. }
  1554. static void ggml_vk_sync_buffers(vk_context& ctx) {
  1555. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  1556. const bool transfer_queue = ctx->p->q->transfer_only;
  1557. ctx->s->buffer.pipelineBarrier(
  1558. ctx->p->q->stage_flags,
  1559. ctx->p->q->stage_flags,
  1560. {},
  1561. { {
  1562. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  1563. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  1564. } },
  1565. {},
  1566. {}
  1567. );
  1568. }
  1569. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  1570. VK_LOG_DEBUG("ggml_vk_wait_events()");
  1571. if (events.empty()) {
  1572. return;
  1573. }
  1574. ctx->s->buffer.waitEvents(
  1575. events,
  1576. ctx->p->q->stage_flags,
  1577. ctx->p->q->stage_flags,
  1578. {},
  1579. {},
  1580. {}
  1581. );
  1582. }
  1583. enum FaCodePath {
  1584. FA_SCALAR,
  1585. FA_COOPMAT1,
  1586. FA_COOPMAT2,
  1587. };
  1588. static FaHeadSizes fa_get_head_sizes(uint32_t hsk, uint32_t hsv) {
  1589. if (hsk != 192 && hsk != 576 && hsk != hsv) {
  1590. return FA_HEAD_SIZE_UNSUPPORTED;
  1591. }
  1592. switch (hsk) {
  1593. case 64: return FA_HEAD_SIZE_64;
  1594. case 80: return FA_HEAD_SIZE_80;
  1595. case 96: return FA_HEAD_SIZE_96;
  1596. case 112: return FA_HEAD_SIZE_112;
  1597. case 128: return FA_HEAD_SIZE_128;
  1598. case 192:
  1599. if (hsv == 192) {
  1600. return FA_HEAD_SIZE_192;
  1601. } else if (hsv == 128) {
  1602. return FA_HEAD_SIZE_192_128;
  1603. } else {
  1604. return FA_HEAD_SIZE_UNSUPPORTED;
  1605. }
  1606. case 256: return FA_HEAD_SIZE_256;
  1607. case 576:
  1608. if (hsv == 512) {
  1609. return FA_HEAD_SIZE_576_512;
  1610. } else {
  1611. return FA_HEAD_SIZE_UNSUPPORTED;
  1612. }
  1613. default: return FA_HEAD_SIZE_UNSUPPORTED;
  1614. }
  1615. }
  1616. // number of rows/cols for flash attention shader
  1617. static constexpr uint32_t flash_attention_num_small_rows = 32;
  1618. static constexpr uint32_t scalar_flash_attention_num_small_rows = 1;
  1619. static uint32_t get_fa_scalar_num_large_rows(uint32_t hsv) {
  1620. if (hsv >= 512) {
  1621. return 2;
  1622. } else {
  1623. return 8;
  1624. }
  1625. }
  1626. // The FA coopmat1 shader assumes 16x16x16 matrix multiply support.
  1627. // 128 threads split into four subgroups, each subgroup does 1/4
  1628. // of the Bc dimension.
  1629. static constexpr uint32_t coopmat1_flash_attention_num_large_rows = 16;
  1630. static constexpr uint32_t scalar_flash_attention_Bc = 64;
  1631. static constexpr uint32_t scalar_flash_attention_workgroup_size = 128;
  1632. static uint32_t get_fa_num_small_rows(FaCodePath path) {
  1633. if (path == FA_COOPMAT2) {
  1634. return flash_attention_num_small_rows;
  1635. } else {
  1636. return scalar_flash_attention_num_small_rows;
  1637. }
  1638. }
  1639. 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) {
  1640. GGML_UNUSED(clamp);
  1641. GGML_UNUSED(hsv);
  1642. if (path == FA_SCALAR) {
  1643. if (small_rows) {
  1644. return {scalar_flash_attention_num_small_rows, 64};
  1645. } else {
  1646. return {get_fa_scalar_num_large_rows(hsv), 32};
  1647. }
  1648. }
  1649. if (path == FA_COOPMAT1) {
  1650. if (small_rows) {
  1651. return {scalar_flash_attention_num_small_rows, scalar_flash_attention_Bc};
  1652. } else {
  1653. return {coopmat1_flash_attention_num_large_rows, scalar_flash_attention_Bc};
  1654. }
  1655. }
  1656. // small rows, large cols
  1657. if (small_rows) {
  1658. return {get_fa_num_small_rows(FA_COOPMAT2), 32};
  1659. }
  1660. // small cols to reduce register count
  1661. if (ggml_is_quantized(type) || hsk >= 256) {
  1662. if (hsk >= 512) {
  1663. return {32, 32};
  1664. } else {
  1665. return {64, 32};
  1666. }
  1667. }
  1668. return {64, 64};
  1669. }
  1670. 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) {
  1671. uint32_t lut_size = 0;
  1672. switch (src0_type) {
  1673. case GGML_TYPE_IQ1_S:
  1674. case GGML_TYPE_IQ1_M:
  1675. lut_size = 2*2048;
  1676. break;
  1677. case GGML_TYPE_IQ2_XXS:
  1678. lut_size = 8*256;
  1679. break;
  1680. case GGML_TYPE_IQ2_XS:
  1681. lut_size = 8*512;
  1682. break;
  1683. case GGML_TYPE_IQ2_S:
  1684. lut_size = 8*1024;
  1685. break;
  1686. case GGML_TYPE_IQ3_XXS:
  1687. lut_size = 4*256;
  1688. break;
  1689. case GGML_TYPE_IQ3_S:
  1690. lut_size = 4*512;
  1691. break;
  1692. case GGML_TYPE_IQ4_NL:
  1693. case GGML_TYPE_IQ4_XS:
  1694. case GGML_TYPE_MXFP4:
  1695. lut_size = 4*16;
  1696. break;
  1697. default:
  1698. break;
  1699. }
  1700. // Needs to be kept up to date on shader changes
  1701. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  1702. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  1703. const uint32_t warps = warptile[0] / warptile[10];
  1704. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  1705. const uint32_t mmid_row_ids = mul_mat_id ? (4096 * sizeof(uint32_t) + 4/*_ne1*/) : 0;
  1706. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  1707. const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size;
  1708. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  1709. VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), "
  1710. "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported);
  1711. return supported;
  1712. }
  1713. struct GpuPipelineConfig {
  1714. // GPU architecture identifier.
  1715. // Example: vk_device_architecture::AMD_GCN
  1716. vk_device_architecture arch;
  1717. // Mapping of pipeline names to their specific subgroup sizes.
  1718. // Example: {"soft_max_f32", 64}
  1719. std::unordered_map<std::string, uint32_t> pipelines;
  1720. // Default subgroup size for this GPU.
  1721. // Defaults to 0 if not explicitly provided.
  1722. uint32_t default_subgroup_size = 0;
  1723. };
  1724. // Pipeline configuration for RDNA1 GPUs.
  1725. static const std::unordered_map<std::string, uint32_t> rdna1_pipelines = {
  1726. {"soft_max", 64}, {"im2col", 64},
  1727. {"argmax", 64}, {"mul_mat_vec", 64},
  1728. {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32}
  1729. };
  1730. // Pipeline configuration for RDNA2 GPUs.
  1731. static const std::unordered_map<std::string, uint32_t> rdna2_pipelines = {
  1732. {"soft_max", 64}, {"im2col", 64},
  1733. };
  1734. static constexpr uint32_t RDNA_DEFAULT_SUBGROUP_SIZE = 32;
  1735. // Define configurations for different GPUs.
  1736. static std::vector<GpuPipelineConfig> gpu_pipeline_configs = {
  1737. {
  1738. vk_device_architecture::AMD_RDNA1,
  1739. {
  1740. rdna1_pipelines,
  1741. },
  1742. RDNA_DEFAULT_SUBGROUP_SIZE
  1743. },
  1744. {
  1745. vk_device_architecture::AMD_RDNA2,
  1746. {
  1747. rdna2_pipelines,
  1748. },
  1749. RDNA_DEFAULT_SUBGROUP_SIZE
  1750. },
  1751. };
  1752. static uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) {
  1753. for (const auto &config : gpu_pipeline_configs) {
  1754. if (config.arch == arch) {
  1755. auto pipIt = config.pipelines.find(pipeline_name);
  1756. if (pipIt != config.pipelines.end()) {
  1757. return pipIt->second;
  1758. }
  1759. std::vector<std::pair<std::string, uint32_t>> sorted_pipelines(config.pipelines.begin(), config.pipelines.end());
  1760. std::sort(sorted_pipelines.begin(), sorted_pipelines.end(),
  1761. [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
  1762. for (const auto &entry : sorted_pipelines) {
  1763. if (pipeline_name.find(entry.first) != std::string::npos) {
  1764. return entry.second;
  1765. }
  1766. }
  1767. return config.default_subgroup_size;
  1768. }
  1769. }
  1770. return 0; // If no matching configuration is found
  1771. }
  1772. static void ggml_vk_load_shaders(vk_device& device) {
  1773. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  1774. // some shaders have a minimum subgroup size
  1775. const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u);
  1776. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  1777. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  1778. // mulmat
  1779. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  1780. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  1781. l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int,
  1782. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  1783. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid;
  1784. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  1785. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  1786. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  1787. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  1788. uint32_t l_align, m_align, s_align;
  1789. if (device->coopmat2) {
  1790. // spec constants and tile sizes for non-quant matmul/matmul_id
  1791. l_warptile = { 256, 128, 256, 64, 1 };
  1792. m_warptile = { 256, 128, 128, 64, 0 };
  1793. s_warptile = { 128, 64, 64, 64, 0 };
  1794. l_wg_denoms = {128, 256, 1 };
  1795. m_wg_denoms = {128, 128, 1 };
  1796. s_wg_denoms = { 64, 64, 1 };
  1797. // spec constants and tile sizes for quant matmul (non-Qi_K)
  1798. l_warptile_mmq = { 256, 128, 256, 64, 1 };
  1799. m_warptile_mmq = { 256, 128, 128, 64, 1 };
  1800. s_warptile_mmq = { 256, 32, 64, 128, 0 };
  1801. l_mmq_wg_denoms = { 128, 256, 1 };
  1802. m_mmq_wg_denoms = { 128, 128, 1 };
  1803. s_mmq_wg_denoms = { 32, 64, 1 };
  1804. // spec constants and tile sizes for quant matmul (Qi_K)
  1805. l_warptile_mmq_k = { 256, 128, 256, 64, 1 };
  1806. m_warptile_mmq_k = { 256, 128, 128, 64, 1 };
  1807. s_warptile_mmq_k = { 256, 32, 64, 128, 0 };
  1808. l_mmq_wg_denoms_k = { 128, 256, 1 };
  1809. m_mmq_wg_denoms_k = { 128, 128, 1 };
  1810. s_mmq_wg_denoms_k = { 32, 64, 1 };
  1811. // spec constants and tile sizes for quant matmul_id
  1812. l_warptile_mmqid = { 256, 128, 128, 16, 0 };
  1813. m_warptile_mmqid = { 256, 128, 64, 16, 0 };
  1814. s_warptile_mmqid = { 256, 128, 64, 16, 0 };
  1815. l_mmqid_wg_denoms = { 128, 128, 1 };
  1816. m_mmqid_wg_denoms = { 128, 64, 1 };
  1817. s_mmqid_wg_denoms = { 128, 64, 1 };
  1818. l_align = 128;
  1819. m_align = 64;
  1820. s_align = 32;
  1821. } else {
  1822. // Matrix cores require different warp group sizes
  1823. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  1824. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  1825. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  1826. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  1827. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  1828. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  1829. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  1830. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  1831. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  1832. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  1833. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  1834. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  1835. l_warptile_mmq = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  1836. m_warptile_mmq = { 128, 64, 64, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  1837. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  1838. l_warptile_mmq_int = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  1839. m_warptile_mmq_int = { 128, 64, 64, 32, subgroup_size_8, 32, 2, 2, 2, 1, subgroup_size_8 };
  1840. s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, subgroup_size_8 };
  1841. // chip specific tuning
  1842. if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) {
  1843. m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  1844. }
  1845. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  1846. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  1847. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  1848. l_align = 128;
  1849. m_align = 64;
  1850. s_align = 32;
  1851. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  1852. ggml_type t = (ggml_type)i;
  1853. // Disable medium and large matrix multiplication if not enough shared memory is available
  1854. // Check mmq warptiles as the largest configuration
  1855. // Throw an error if not enough for any matrix multiplication is available
  1856. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) {
  1857. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  1858. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  1859. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) {
  1860. device->mul_mat_m[i] = false;
  1861. device->mul_mat_l[i] = false;
  1862. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) {
  1863. device->mul_mat_l[i] = false;
  1864. }
  1865. // Disable mul_mat_id if not enough shared memory is available
  1866. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, true, t)) {
  1867. device->mul_mat_id_s[i] = false;
  1868. device->mul_mat_id_m[i] = false;
  1869. device->mul_mat_id_l[i] = false;
  1870. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, true, t)) {
  1871. device->mul_mat_id_m[i] = false;
  1872. device->mul_mat_id_l[i] = false;
  1873. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, true, t)) {
  1874. device->mul_mat_id_l[i] = false;
  1875. }
  1876. }
  1877. }
  1878. if (!device->pipeline_matmul_f32) {
  1879. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  1880. }
  1881. if (!device->pipeline_matmul_f32_f16) {
  1882. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  1883. }
  1884. if (!device->pipeline_matmul_id_f32) {
  1885. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  1886. }
  1887. if (!device->pipeline_matmul_bf16) {
  1888. device->pipeline_matmul_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  1889. }
  1890. if (!device->pipeline_matmul_id_bf16) {
  1891. device->pipeline_matmul_id_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  1892. }
  1893. std::vector<std::future<void>> compiles;
  1894. auto const &ggml_vk_create_pipeline = [&](vk_device& device, vk_pipeline& pipeline, const std::string &name, size_t spv_size, const void* spv_data, const std::string &entrypoint,
  1895. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  1896. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  1897. if (!require_full_subgroups && required_subgroup_size == 0) {
  1898. required_subgroup_size = get_subgroup_size(name, device->architecture);
  1899. }
  1900. if (!pipeline) {
  1901. pipeline = std::make_shared<vk_pipeline_struct>();
  1902. pipeline->name = name;
  1903. pipeline->parameter_count = parameter_count;
  1904. pipeline->push_constant_size = push_constant_size;
  1905. pipeline->wg_denoms = wg_denoms;
  1906. pipeline->align = align;
  1907. }
  1908. if (!pipeline->needed || pipeline->compiled) {
  1909. return;
  1910. }
  1911. {
  1912. // wait until fewer than N compiles are in progress
  1913. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  1914. std::unique_lock<std::mutex> guard(compile_count_mutex);
  1915. while (compile_count >= N) {
  1916. compile_count_cond.wait(guard);
  1917. }
  1918. compile_count++;
  1919. }
  1920. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  1921. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  1922. };
  1923. 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> {
  1924. return {fa_rows_cols(path, hsk, hsv, clamp, type, small_rows)[0], 1, 1};
  1925. };
  1926. 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> {
  1927. // For large number of rows, 128 invocations seems to work best.
  1928. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  1929. // can't use 256 for D==80.
  1930. // For scalar, use 128 (arbitrary)
  1931. // The same D_split value is used for both HSK and HSV, so just base it on the union of the LSBs.
  1932. const uint32_t D = (hsk|hsv);
  1933. uint32_t wg_size = (path == FA_SCALAR || path == FA_COOPMAT1)
  1934. ? scalar_flash_attention_workgroup_size
  1935. : ((small_rows && (D % 32) == 0) ? 256 : 128);
  1936. auto rows_cols = fa_rows_cols(path, hsk, hsv, clamp, type, small_rows);
  1937. // D_split can't be larger than a subgroup because we use subgroupShuffle to reduce it.
  1938. // D_split can't be larger than the LSB of D divided by 4 due to vectorization in the shader.
  1939. const uint32_t D_lsb = D ^ (D & (D-1));
  1940. uint32_t D_split = std::min(std::min(device->subgroup_size, 8u), D_lsb / 4);
  1941. // mask dim1 is padded to 64, we rely on this to avoid clamping mask loads
  1942. GGML_ASSERT((GGML_KQ_MASK_PAD % rows_cols[0]) == 0);
  1943. return {wg_size, rows_cols[0], rows_cols[1], hsk, hsv, clamp, D_split};
  1944. };
  1945. #define CREATE_FA2(TYPE, NAMELC, FAPATH, SUFFIX, HSK, HSV, HEAD_SIZES) \
  1946. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16 ## SUFFIX[TYPE][FA_HEAD_SIZE_##HEAD_SIZES][0][0][0], "flash_attn_f32_f16_" #HEAD_SIZES "_f16acc" #NAMELC #SUFFIX, 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,false), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,false), 1, true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  1947. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16 ## SUFFIX[TYPE][FA_HEAD_SIZE_##HEAD_SIZES][0][0][1], "flash_attn_f32_f16_" #HEAD_SIZES "_aligned_f16acc" #NAMELC #SUFFIX, 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,false), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,false), fa_rows_cols(FAPATH,HSK,HSV,0,TYPE,false)[1], true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  1948. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16 ## SUFFIX[TYPE][FA_HEAD_SIZE_##HEAD_SIZES][1][0][0], "flash_attn_f32_f16_" #HEAD_SIZES "_f32acc" #NAMELC #SUFFIX, 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,false), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,false), 1, true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  1949. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16 ## SUFFIX[TYPE][FA_HEAD_SIZE_##HEAD_SIZES][1][0][1], "flash_attn_f32_f16_" #HEAD_SIZES "_aligned_f32acc" #NAMELC #SUFFIX, 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,false), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,false), fa_rows_cols(FAPATH,HSK,HSV,0,TYPE,false)[1], true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  1950. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16 ## SUFFIX[TYPE][FA_HEAD_SIZE_##HEAD_SIZES][0][1][0], "flash_attn_f32_f16_" #HEAD_SIZES "_f16acc_smallrows" #NAMELC #SUFFIX, 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,true), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,true), 1, true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  1951. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16 ## SUFFIX[TYPE][FA_HEAD_SIZE_##HEAD_SIZES][0][1][1], "flash_attn_f32_f16_" #HEAD_SIZES "_aligned_f16acc_smallrows" #NAMELC #SUFFIX, 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,true), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,true), fa_rows_cols(FAPATH,HSK,HSV,0,TYPE,true)[1], true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  1952. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16 ## SUFFIX[TYPE][FA_HEAD_SIZE_##HEAD_SIZES][1][1][0], "flash_attn_f32_f16_" #HEAD_SIZES "_f32acc_smallrows" #NAMELC #SUFFIX, 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,true), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,true), 1, true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  1953. ggml_vk_create_pipeline(device, device->pipeline_flash_attn_f32_f16 ## SUFFIX[TYPE][FA_HEAD_SIZE_##HEAD_SIZES][1][1][1], "flash_attn_f32_f16_" #HEAD_SIZES "_aligned_f32acc_smallrows" #NAMELC #SUFFIX, 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,true), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,true), fa_rows_cols(FAPATH,HSK,HSV,0,TYPE,true)[1], true, FAPATH==FA_COOPMAT1, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  1954. #define CREATE_FA(TYPE, NAMELC, FAPATH, SUFFIX) \
  1955. CREATE_FA2(TYPE, NAMELC, FAPATH, SUFFIX, 64, 64, 64) \
  1956. CREATE_FA2(TYPE, NAMELC, FAPATH, SUFFIX, 80, 80, 80) \
  1957. CREATE_FA2(TYPE, NAMELC, FAPATH, SUFFIX, 96, 96, 96) \
  1958. CREATE_FA2(TYPE, NAMELC, FAPATH, SUFFIX, 112, 112, 112) \
  1959. CREATE_FA2(TYPE, NAMELC, FAPATH, SUFFIX, 128, 128, 128) \
  1960. CREATE_FA2(TYPE, NAMELC, FAPATH, SUFFIX, 192, 192, 192) \
  1961. CREATE_FA2(TYPE, NAMELC, FAPATH, SUFFIX, 192, 128, 192_128) \
  1962. CREATE_FA2(TYPE, NAMELC, FAPATH, SUFFIX, 256, 256, 256) \
  1963. CREATE_FA2(TYPE, NAMELC, FAPATH, SUFFIX, 576, 512, 576_512)
  1964. CREATE_FA(GGML_TYPE_F16, f16, FA_SCALAR, )
  1965. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_SCALAR, )
  1966. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_SCALAR, )
  1967. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  1968. if (device->coopmat1_fa_support) {
  1969. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT1, _cm1)
  1970. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT1, _cm1)
  1971. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT1, _cm1)
  1972. }
  1973. #endif
  1974. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  1975. if (device->coopmat2) {
  1976. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT2, _cm2)
  1977. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT2, _cm2)
  1978. CREATE_FA(GGML_TYPE_Q4_1, q4_1, FA_COOPMAT2, _cm2)
  1979. CREATE_FA(GGML_TYPE_Q5_0, q5_0, FA_COOPMAT2, _cm2)
  1980. CREATE_FA(GGML_TYPE_Q5_1, q5_1, FA_COOPMAT2, _cm2)
  1981. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT2, _cm2)
  1982. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl, FA_COOPMAT2, _cm2)
  1983. }
  1984. #endif
  1985. #undef CREATE_FA2
  1986. #undef CREATE_FA
  1987. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  1988. if (device->coopmat2) {
  1989. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  1990. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1991. 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); \
  1992. 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); \
  1993. 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); \
  1994. 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); \
  1995. 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); \
  1996. 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); \
  1997. // Create 2 variants, {f16,f32} accumulator
  1998. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  1999. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2000. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2001. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2002. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2003. if (device->coopmat_bf16_support) {
  2004. CREATE_MM(pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2005. }
  2006. #endif
  2007. 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)
  2008. 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)
  2009. 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)
  2010. 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)
  2011. 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)
  2012. 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)
  2013. 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)
  2014. 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)
  2015. 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)
  2016. 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)
  2017. 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)
  2018. 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)
  2019. 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)
  2020. 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)
  2021. 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)
  2022. 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)
  2023. 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)
  2024. 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)
  2025. 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)
  2026. 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)
  2027. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2028. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2029. if (device->coopmat_bf16_support) {
  2030. CREATE_MM(pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2031. }
  2032. #endif
  2033. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_q4_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2034. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_q4_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2035. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_q5_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2036. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_q5_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2037. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_q8_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2038. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_q2_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2039. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_q3_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2040. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_q4_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2041. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_q5_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2042. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_q6_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2043. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_iq1_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2044. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_iq1_m_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2045. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_iq2_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2046. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_iq2_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2047. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_iq2_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2048. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_iq3_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2049. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_iq3_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2050. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_iq4_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2051. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_iq4_nl_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2052. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_mxfp4_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2053. #undef CREATE_MM
  2054. #undef CREATE_MM2
  2055. } else
  2056. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2057. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2058. if (device->coopmat_support) {
  2059. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2060. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2061. if (device->mul_mat ## ID ## _l[TYPE]) \
  2062. 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); \
  2063. if (device->mul_mat ## ID ## _m[TYPE]) \
  2064. 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); \
  2065. if (device->mul_mat ## ID ## _s[TYPE]) \
  2066. 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); \
  2067. if (device->mul_mat ## ID ## _l[TYPE]) \
  2068. 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); \
  2069. if (device->mul_mat ## ID ## _m[TYPE]) \
  2070. 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); \
  2071. if (device->mul_mat ## ID ## _s[TYPE]) \
  2072. 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); \
  2073. // Create 2 variants, {f16,f32} accumulator
  2074. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2075. if (device->coopmat_acc_f16_support) { \
  2076. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2077. } \
  2078. if (device->coopmat_acc_f32_support) { \
  2079. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2080. } \
  2081. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2082. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2083. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2084. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2085. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2086. if (device->coopmat_bf16_support) {
  2087. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, )
  2088. }
  2089. #endif
  2090. if (device->coopmat_acc_f16_support) {
  2091. 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, );
  2092. 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, );
  2093. 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, );
  2094. 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, );
  2095. 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, );
  2096. 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, );
  2097. 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, );
  2098. 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, );
  2099. 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, );
  2100. 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, );
  2101. 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, );
  2102. 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, );
  2103. 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, );
  2104. 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, );
  2105. 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, );
  2106. 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, );
  2107. 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, );
  2108. 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, );
  2109. 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, );
  2110. 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, );
  2111. } else {
  2112. 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, );
  2113. 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, );
  2114. 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, );
  2115. 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, );
  2116. 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, );
  2117. 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, );
  2118. 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, );
  2119. 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, );
  2120. 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, );
  2121. 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, );
  2122. 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, );
  2123. 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, );
  2124. 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, );
  2125. 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, );
  2126. 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, );
  2127. 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, );
  2128. 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, );
  2129. 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, );
  2130. 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, );
  2131. 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, );
  2132. }
  2133. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2134. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2135. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2136. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2137. if (device->coopmat_bf16_support) {
  2138. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2139. }
  2140. #endif
  2141. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2142. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2143. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2144. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2145. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2146. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2147. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2148. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2149. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2150. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2151. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2152. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2153. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2154. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2155. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2156. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2157. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2158. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2159. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2160. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2161. #undef CREATE_MM2
  2162. #undef CREATE_MM
  2163. } else
  2164. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2165. if (device->fp16) {
  2166. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2167. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2168. if (device->mul_mat ## ID ## _l[TYPE]) \
  2169. 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); \
  2170. if (device->mul_mat ## ID ## _m[TYPE]) \
  2171. 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); \
  2172. if (device->mul_mat ## ID ## _s[TYPE]) \
  2173. 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); \
  2174. if (device->mul_mat ## ID ## _l[TYPE]) \
  2175. 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); \
  2176. if (device->mul_mat ## ID ## _m[TYPE]) \
  2177. 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); \
  2178. if (device->mul_mat ## ID ## _s[TYPE]) \
  2179. 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); \
  2180. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2181. if (device->mul_mat ## ID ## _l[TYPE]) { \
  2182. 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); \
  2183. 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); \
  2184. } \
  2185. if (device->mul_mat ## ID ## _m[TYPE]) { \
  2186. 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); \
  2187. 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); \
  2188. } \
  2189. if (device->mul_mat ## ID ## _s[TYPE]) { \
  2190. 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); \
  2191. 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); \
  2192. } \
  2193. // Create 2 variants, {f16,f32} accumulator
  2194. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2195. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2196. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2197. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2198. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2199. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2200. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2201. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2202. 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, );
  2203. 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, );
  2204. 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, );
  2205. 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, );
  2206. 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, );
  2207. 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, );
  2208. 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, );
  2209. 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, );
  2210. 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, );
  2211. 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, );
  2212. 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, );
  2213. 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, );
  2214. 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, );
  2215. 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, );
  2216. 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, );
  2217. 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, );
  2218. 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, );
  2219. 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, );
  2220. 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, );
  2221. 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, );
  2222. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2223. if (device->integer_dot_product) {
  2224. 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, );
  2225. 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, );
  2226. 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, );
  2227. 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, );
  2228. 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, );
  2229. }
  2230. #endif
  2231. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2232. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2233. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2234. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id);
  2235. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2236. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2237. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2238. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2239. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2240. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2241. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2242. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2243. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2244. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2245. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2246. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2247. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2248. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2249. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2250. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2251. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2252. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2253. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2254. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2255. #undef CREATE_MM2
  2256. #undef CREATE_MMQ
  2257. #undef CREATE_MM
  2258. } else {
  2259. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2260. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2261. if (device->mul_mat ## ID ## _l[TYPE]) \
  2262. 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); \
  2263. if (device->mul_mat ## ID ## _m[TYPE]) \
  2264. 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); \
  2265. if (device->mul_mat ## ID ## _s[TYPE]) \
  2266. 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); \
  2267. if (device->mul_mat ## ID ## _l[TYPE]) \
  2268. 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); \
  2269. if (device->mul_mat ## ID ## _m[TYPE]) \
  2270. 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); \
  2271. if (device->mul_mat ## ID ## _s[TYPE]) \
  2272. 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); \
  2273. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2274. if (device->mul_mat ## ID ## _l[TYPE]) \
  2275. 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); \
  2276. if (device->mul_mat ## ID ## _m[TYPE]) \
  2277. 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); \
  2278. if (device->mul_mat ## ID ## _s[TYPE]) \
  2279. 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); \
  2280. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2281. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2282. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2283. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2284. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2285. 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, );
  2286. 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, );
  2287. 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, );
  2288. 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, );
  2289. 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, );
  2290. 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, );
  2291. 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, );
  2292. 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, );
  2293. 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, );
  2294. 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, );
  2295. 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, );
  2296. 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, );
  2297. 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, );
  2298. 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, );
  2299. 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, );
  2300. 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, );
  2301. 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, );
  2302. 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, );
  2303. 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, );
  2304. 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, );
  2305. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2306. if (device->integer_dot_product) {
  2307. 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, );
  2308. 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, );
  2309. 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, );
  2310. 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, );
  2311. 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, );
  2312. }
  2313. #endif
  2314. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2315. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2316. 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);
  2317. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id);
  2318. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2319. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2320. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2321. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2322. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2323. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2324. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2325. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2326. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2327. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2328. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2329. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2330. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2331. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2332. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2333. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2334. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2335. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2336. 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_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2337. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_mxfp4_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2338. }
  2339. // reusing CREATE_MM from the fp32 path
  2340. if ((device->coopmat2 || device->coopmat_support)
  2341. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2342. && !device->coopmat_bf16_support
  2343. #endif
  2344. ) {
  2345. // use scalar tile sizes
  2346. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2347. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, 4, 2, 1, subgroup_size_8 };
  2348. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, 2, 2, 1, subgroup_size_8 };
  2349. l_wg_denoms = {128, 128, 1 };
  2350. m_wg_denoms = { 64, 64, 1 };
  2351. s_wg_denoms = { 32, 32, 1 };
  2352. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2353. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id);
  2354. }
  2355. #undef CREATE_MM
  2356. // mul mat vec
  2357. // the number of rows computed per shader depends on GPU model and quant
  2358. uint32_t rm_stdq = 1;
  2359. uint32_t rm_kq = 2;
  2360. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  2361. if (device->architecture == AMD_GCN) {
  2362. rm_stdq = 2;
  2363. rm_kq = 4;
  2364. }
  2365. } else if (device->vendor_id == VK_VENDOR_ID_INTEL)
  2366. rm_stdq = 2;
  2367. uint32_t rm_iq = 2 * rm_kq;
  2368. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  2369. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f32_f32_"+std::to_string(i+1), mul_mat_vec_f32_f32_f32_len, mul_mat_vec_f32_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2, i+1}, 1);
  2370. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f32_f32_"+std::to_string(i+1), mul_mat_vec_f16_f32_f32_len, mul_mat_vec_f16_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2, i+1}, 1);
  2371. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f32_f32_"+std::to_string(i+1), mul_mat_vec_bf16_f32_f32_len, mul_mat_vec_bf16_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2, i+1}, 1);
  2372. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f32_f32_"+std::to_string(i+1), mul_mat_vec_q4_0_f32_f32_len, mul_mat_vec_q4_0_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  2373. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f32_f32_"+std::to_string(i+1), mul_mat_vec_q4_1_f32_f32_len, mul_mat_vec_q4_1_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  2374. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f32_f32_"+std::to_string(i+1), mul_mat_vec_q5_0_f32_f32_len, mul_mat_vec_q5_0_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  2375. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f32_f32_"+std::to_string(i+1), mul_mat_vec_q5_1_f32_f32_len, mul_mat_vec_q5_1_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  2376. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f32_f32_"+std::to_string(i+1), mul_mat_vec_q8_0_f32_f32_len, mul_mat_vec_q8_0_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {device->subgroup_size, 1*rm_stdq, i+1}, 1, true);
  2377. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f32_f32_"+std::to_string(i+1), mul_mat_vec_q2_k_f32_f32_len, mul_mat_vec_q2_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  2378. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f32_f32_"+std::to_string(i+1), mul_mat_vec_q3_k_f32_f32_len, mul_mat_vec_q3_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  2379. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f32_f32_"+std::to_string(i+1), mul_mat_vec_q4_k_f32_f32_len, mul_mat_vec_q4_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  2380. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f32_f32_"+std::to_string(i+1), mul_mat_vec_q5_k_f32_f32_len, mul_mat_vec_q5_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  2381. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f32_f32_"+std::to_string(i+1), mul_mat_vec_q6_k_f32_f32_len, mul_mat_vec_q6_k_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  2382. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f32_f32_"+std::to_string(i+1), mul_mat_vec_iq1_s_f32_f32_len, mul_mat_vec_iq1_s_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2383. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f32_f32_"+std::to_string(i+1), mul_mat_vec_iq1_m_f32_f32_len, mul_mat_vec_iq1_m_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2384. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f32_f32_"+std::to_string(i+1), mul_mat_vec_iq2_xxs_f32_f32_len, mul_mat_vec_iq2_xxs_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2385. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f32_f32_"+std::to_string(i+1), mul_mat_vec_iq2_xs_f32_f32_len, mul_mat_vec_iq2_xs_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2386. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f32_f32_"+std::to_string(i+1), mul_mat_vec_iq2_s_f32_f32_len, mul_mat_vec_iq2_s_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2387. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f32_f32_"+std::to_string(i+1), mul_mat_vec_iq3_xxs_f32_f32_len, mul_mat_vec_iq3_xxs_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2388. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f32_f32_"+std::to_string(i+1), mul_mat_vec_iq3_s_f32_f32_len, mul_mat_vec_iq3_s_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2389. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f32_f32_"+std::to_string(i+1), mul_mat_vec_iq4_xs_f32_f32_len, mul_mat_vec_iq4_xs_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2390. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f32_f32_"+std::to_string(i+1), mul_mat_vec_iq4_nl_f32_f32_len, mul_mat_vec_iq4_nl_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2391. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f32_f32_"+std::to_string(i+1), mul_mat_vec_mxfp4_f32_f32_len, mul_mat_vec_mxfp4_f32_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2392. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f16_f32_"+std::to_string(i+1), mul_mat_vec_f32_f16_f32_len, mul_mat_vec_f32_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2, i+1}, 1);
  2393. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f16_f32_"+std::to_string(i+1), mul_mat_vec_f16_f16_f32_len, mul_mat_vec_f16_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2, i+1}, 1);
  2394. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f16_f32_"+std::to_string(i+1), mul_mat_vec_bf16_f16_f32_len, mul_mat_vec_bf16_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {device->subgroup_size, 2, i+1}, 1);
  2395. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f16_f32_"+std::to_string(i+1), mul_mat_vec_q4_0_f16_f32_len, mul_mat_vec_q4_0_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  2396. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f16_f32_"+std::to_string(i+1), mul_mat_vec_q4_1_f16_f32_len, mul_mat_vec_q4_1_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  2397. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f16_f32_"+std::to_string(i+1), mul_mat_vec_q5_0_f16_f32_len, mul_mat_vec_q5_0_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  2398. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f16_f32_"+std::to_string(i+1), mul_mat_vec_q5_1_f16_f32_len, mul_mat_vec_q5_1_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq, i+1}, 1, true);
  2399. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f16_f32_"+std::to_string(i+1), mul_mat_vec_q8_0_f16_f32_len, mul_mat_vec_q8_0_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {device->subgroup_size, 1*rm_stdq, i+1}, 1, true);
  2400. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f16_f32_"+std::to_string(i+1), mul_mat_vec_q2_k_f16_f32_len, mul_mat_vec_q2_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  2401. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f16_f32_"+std::to_string(i+1), mul_mat_vec_q3_k_f16_f32_len, mul_mat_vec_q3_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  2402. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f16_f32_"+std::to_string(i+1), mul_mat_vec_q4_k_f16_f32_len, mul_mat_vec_q4_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  2403. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f16_f32_"+std::to_string(i+1), mul_mat_vec_q5_k_f16_f32_len, mul_mat_vec_q5_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  2404. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f16_f32_"+std::to_string(i+1), mul_mat_vec_q6_k_f16_f32_len, mul_mat_vec_q6_k_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq, i+1}, 1, true);
  2405. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f16_f32_"+std::to_string(i+1), mul_mat_vec_iq1_s_f16_f32_len, mul_mat_vec_iq1_s_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2406. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f16_f32_"+std::to_string(i+1), mul_mat_vec_iq1_m_f16_f32_len, mul_mat_vec_iq1_m_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2407. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f16_f32_"+std::to_string(i+1), mul_mat_vec_iq2_xxs_f16_f32_len, mul_mat_vec_iq2_xxs_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2408. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f16_f32_"+std::to_string(i+1), mul_mat_vec_iq2_xs_f16_f32_len, mul_mat_vec_iq2_xs_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2409. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f16_f32_"+std::to_string(i+1), mul_mat_vec_iq2_s_f16_f32_len, mul_mat_vec_iq2_s_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2410. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f16_f32_"+std::to_string(i+1), mul_mat_vec_iq3_xxs_f16_f32_len, mul_mat_vec_iq3_xxs_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2411. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f16_f32_"+std::to_string(i+1), mul_mat_vec_iq3_s_f16_f32_len, mul_mat_vec_iq3_s_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2412. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f16_f32_"+std::to_string(i+1), mul_mat_vec_iq4_xs_f16_f32_len, mul_mat_vec_iq4_xs_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2413. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f16_f32_"+std::to_string(i+1), mul_mat_vec_iq4_nl_f16_f32_len, mul_mat_vec_iq4_nl_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2414. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f16_f32_"+std::to_string(i+1), mul_mat_vec_mxfp4_f16_f32_len, mul_mat_vec_mxfp4_f16_f32_data, "main", 3, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq, i+1}, 1, true);
  2415. }
  2416. 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);
  2417. 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);
  2418. 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);
  2419. 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);
  2420. 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);
  2421. 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);
  2422. 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);
  2423. 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);
  2424. 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);
  2425. 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);
  2426. 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);
  2427. 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);
  2428. 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);
  2429. 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);
  2430. 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);
  2431. 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);
  2432. 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);
  2433. 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);
  2434. 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);
  2435. 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);
  2436. 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);
  2437. 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);
  2438. 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);
  2439. // dequant shaders
  2440. 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);
  2441. 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);
  2442. 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);
  2443. 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);
  2444. 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);
  2445. 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);
  2446. 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);
  2447. 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);
  2448. 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);
  2449. 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);
  2450. 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);
  2451. 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);
  2452. 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);
  2453. 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);
  2454. 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);
  2455. 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);
  2456. 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);
  2457. 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);
  2458. 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);
  2459. 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);
  2460. 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);
  2461. // get_rows
  2462. 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);
  2463. 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);
  2464. 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);
  2465. 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);
  2466. 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);
  2467. 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);
  2468. 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);
  2469. 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);
  2470. 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);
  2471. 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);
  2472. 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);
  2473. 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);
  2474. 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);
  2475. 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);
  2476. 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);
  2477. 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);
  2478. 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);
  2479. 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);
  2480. 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);
  2481. 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);
  2482. 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);
  2483. 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);
  2484. 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);
  2485. 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);
  2486. 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);
  2487. 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);
  2488. 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);
  2489. 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);
  2490. 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);
  2491. 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);
  2492. 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);
  2493. 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);
  2494. 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);
  2495. 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);
  2496. 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);
  2497. 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);
  2498. 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);
  2499. 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);
  2500. 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);
  2501. for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) {
  2502. if (device->subgroup_add && device->subgroup_require_full_support) {
  2503. ggml_vk_create_pipeline(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);
  2504. } else {
  2505. ggml_vk_create_pipeline(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);
  2506. }
  2507. }
  2508. 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);
  2509. 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);
  2510. 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);
  2511. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_f32, "rms_norm_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0}, 1);
  2512. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_f32, "rms_norm_mul_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1}, 1);
  2513. 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);
  2514. 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);
  2515. 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);
  2516. 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);
  2517. 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);
  2518. 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);
  2519. 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);
  2520. 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);
  2521. 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);
  2522. 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);
  2523. 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);
  2524. 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);
  2525. if (device->float_controls_rte_fp16) {
  2526. 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);
  2527. 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);
  2528. 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);
  2529. 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);
  2530. 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);
  2531. 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);
  2532. } else {
  2533. 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);
  2534. 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);
  2535. 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);
  2536. 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);
  2537. 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);
  2538. 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);
  2539. }
  2540. if (device->float_controls_rte_fp16) {
  2541. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_F32], "set_rows_f32", set_rows_f32_rte_len, set_rows_f32_rte_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2542. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_F16], "set_rows_f16", set_rows_f16_rte_len, set_rows_f16_rte_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2543. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_BF16], "set_rows_bf16", set_rows_bf16_rte_len, set_rows_bf16_rte_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2544. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_Q4_0], "set_rows_q4_0", set_rows_q4_0_rte_len, set_rows_q4_0_rte_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2545. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_Q4_1], "set_rows_q4_1", set_rows_q4_1_rte_len, set_rows_q4_1_rte_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2546. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_Q5_0], "set_rows_q5_0", set_rows_q5_0_rte_len, set_rows_q5_0_rte_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2547. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_Q5_1], "set_rows_q5_1", set_rows_q5_1_rte_len, set_rows_q5_1_rte_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2548. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_Q8_0], "set_rows_q8_0", set_rows_q8_0_rte_len, set_rows_q8_0_rte_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2549. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_IQ4_NL], "set_rows_iq4_nl", set_rows_iq4_nl_rte_len, set_rows_iq4_nl_rte_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2550. } else {
  2551. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_F32], "set_rows_f32", set_rows_f32_len, set_rows_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2552. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_F16], "set_rows_f16", set_rows_f16_len, set_rows_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2553. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_BF16], "set_rows_bf16", set_rows_bf16_len, set_rows_bf16_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2554. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_Q4_0], "set_rows_q4_0", set_rows_q4_0_len, set_rows_q4_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2555. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_Q4_1], "set_rows_q4_1", set_rows_q4_1_len, set_rows_q4_1_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2556. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_Q5_0], "set_rows_q5_0", set_rows_q5_0_len, set_rows_q5_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2557. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_Q5_1], "set_rows_q5_1", set_rows_q5_1_len, set_rows_q5_1_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2558. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_Q8_0], "set_rows_q8_0", set_rows_q8_0_len, set_rows_q8_0_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2559. ggml_vk_create_pipeline(device, device->pipeline_set_rows[GGML_TYPE_IQ4_NL], "set_rows_iq4_nl", set_rows_iq4_nl_len, set_rows_iq4_nl_data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  2560. }
  2561. 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);
  2562. 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);
  2563. 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);
  2564. 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);
  2565. 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);
  2566. 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);
  2567. auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) {
  2568. std::string s;
  2569. s += std::string(src0_f16 ? "_f16" : "_f32");
  2570. s += std::string(src1_f16 ? "_f16" : "_f32");
  2571. s += std::string(dst_f16 ? "_f16" : "_f32");
  2572. return s;
  2573. };
  2574. bool rte = device->float_controls_rte_fp16;
  2575. #define CREATE_BINARY(name, namemod, spec) \
  2576. for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \
  2577. ggml_vk_create_pipeline(device, device->pipeline_ ## name ## namemod[s0][s1][d], \
  2578. #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d][rte], name ## _data[s0][s1][d][rte], \
  2579. "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1);
  2580. CREATE_BINARY(add, , {0})
  2581. CREATE_BINARY(add, _norepeat, {1})
  2582. CREATE_BINARY(sub, , {0})
  2583. CREATE_BINARY(sub, _norepeat, {1})
  2584. CREATE_BINARY(mul, , {0})
  2585. CREATE_BINARY(mul, _norepeat, {1})
  2586. CREATE_BINARY(div, , {0})
  2587. CREATE_BINARY(div, _norepeat, {1})
  2588. #undef CREATE_BINARY
  2589. if (device->multi_add) {
  2590. for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) {
  2591. ggml_vk_create_pipeline(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);
  2592. }
  2593. }
  2594. 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);
  2595. 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);
  2596. 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);
  2597. 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);
  2598. 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);
  2599. 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);
  2600. 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);
  2601. 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);
  2602. 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);
  2603. 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);
  2604. 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);
  2605. 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);
  2606. 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);
  2607. ggml_vk_create_pipeline(device, device->pipeline_pad_f32, "pad_f32", pad_f32_len, pad_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  2608. 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);
  2609. 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);
  2610. 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);
  2611. #define CREATE_UNARY(name) \
  2612. 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); \
  2613. 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);
  2614. CREATE_UNARY(gelu)
  2615. CREATE_UNARY(gelu_erf)
  2616. CREATE_UNARY(gelu_quick)
  2617. CREATE_UNARY(silu)
  2618. CREATE_UNARY(relu)
  2619. CREATE_UNARY(tanh)
  2620. CREATE_UNARY(sigmoid)
  2621. #undef CREATE_UNARY
  2622. #define CREATE_GLU(name) \
  2623. if (device->float_controls_rte_fp16) { \
  2624. 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); \
  2625. 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); \
  2626. } else { \
  2627. 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); \
  2628. 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); \
  2629. }
  2630. CREATE_GLU(geglu)
  2631. CREATE_GLU(reglu)
  2632. CREATE_GLU(swiglu)
  2633. CREATE_GLU(swiglu_oai)
  2634. CREATE_GLU(geglu_erf)
  2635. CREATE_GLU(geglu_quick)
  2636. #undef CREATE_GLU
  2637. 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);
  2638. 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);
  2639. 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);
  2640. 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);
  2641. 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);
  2642. 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);
  2643. 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);
  2644. 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);
  2645. 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);
  2646. 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);
  2647. 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);
  2648. 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);
  2649. if (device->float_controls_rte_fp16) {
  2650. 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);
  2651. 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);
  2652. 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);
  2653. 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);
  2654. } else {
  2655. 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);
  2656. 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);
  2657. 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);
  2658. 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);
  2659. }
  2660. for (uint32_t i = 0; i < num_argsort_pipelines; ++i) {
  2661. ggml_vk_create_pipeline(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);
  2662. }
  2663. 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);
  2664. ggml_vk_create_pipeline(device, device->pipeline_sum_rows_f32, "sum_rows_f32", sum_rows_f32_len, sum_rows_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  2665. 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);
  2666. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32, "im2col_f32", im2col_f32_len, im2col_f32_data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true);
  2667. if (device->float_controls_rte_fp16) {
  2668. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16_rte_len, im2col_f32_f16_rte_data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true);
  2669. } else {
  2670. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16_len, im2col_f32_f16_data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true);
  2671. }
  2672. 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);
  2673. 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);
  2674. 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);
  2675. 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);
  2676. 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);
  2677. 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);
  2678. 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);
  2679. // conv2d
  2680. for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) {
  2681. uint32_t conv2d_WG_SIZE = 256;
  2682. uint32_t conv2d_BS_K = 128;
  2683. uint32_t conv2d_BS_CRS = 16;
  2684. uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices.
  2685. uint32_t conv2d_BS_NPQ = 128;
  2686. uint32_t conv2d_TS_K = 8;
  2687. uint32_t conv2d_SHMEM_PAD = 4;
  2688. bool conv2d_UNROLL = true;
  2689. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2690. if (device->coopmat2) {
  2691. conv2d_SHMEM_PAD = 8; // 8 float16_t
  2692. }
  2693. #endif
  2694. if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  2695. conv2d_SHMEM_PAD = 0;
  2696. conv2d_UNROLL = false;
  2697. } else if (device->vendor_id == VK_VENDOR_ID_AMD) {
  2698. conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4;
  2699. }
  2700. switch (s) {
  2701. default:
  2702. case CONV_SHAPE_128x128:
  2703. conv2d_BS_K = 128;
  2704. conv2d_BS_NPQ = 128;
  2705. conv2d_BS_CRS = 16;
  2706. if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != vk_device_architecture::AMD_GCN) {
  2707. conv2d_UNROLL = false;
  2708. }
  2709. break;
  2710. case CONV_SHAPE_64x32:
  2711. conv2d_BS_K = 64;
  2712. conv2d_BS_NPQ = 32;
  2713. conv2d_BS_CRS = 32;
  2714. conv2d_TS_K = 4;
  2715. break;
  2716. case CONV_SHAPE_32x256:
  2717. conv2d_BS_K = 32;
  2718. conv2d_BS_NPQ = 256;
  2719. conv2d_BS_CRS = 16;
  2720. break;
  2721. }
  2722. // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math.
  2723. bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA ||
  2724. device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  2725. bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD ||
  2726. device->architecture == vk_device_architecture::AMD_GCN;
  2727. if (device->subgroup_shuffle &&
  2728. device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316.
  2729. allow_collectives_nv &&
  2730. allow_collectives_amd) {
  2731. use_collectives = 1;
  2732. conv2d_BS_CRS = std::min(
  2733. device->subgroup_size,
  2734. conv2d_BS_CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used.
  2735. }
  2736. uint32_t conv2d_shmem_req =
  2737. (conv2d_BS_K * (conv2d_BS_CRS + conv2d_SHMEM_PAD) + conv2d_BS_CRS * (conv2d_BS_NPQ + conv2d_SHMEM_PAD)) * sizeof(float);
  2738. if (device->properties.limits.maxComputeSharedMemorySize < conv2d_shmem_req) {
  2739. conv2d_BS_CRS = 8;
  2740. if (use_collectives) {
  2741. conv2d_BS_CRS = std::min(device->subgroup_size, conv2d_BS_CRS);
  2742. }
  2743. }
  2744. std::array<uint32_t, 3> wg_denoms = { conv2d_BS_K, conv2d_BS_NPQ, 1 };
  2745. 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 };
  2746. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2747. if (device->coopmat2) {
  2748. ggml_vk_create_pipeline(
  2749. device, device->pipeline_conv2d_f32[s], "conv2d_f32", conv2d_f32_cm2_len, conv2d_f32_cm2_data, "main", 3,
  2750. sizeof(vk_op_conv2d_push_constants), wg_denoms, spec_constants, 1, true, use_collectives);
  2751. ggml_vk_create_pipeline(
  2752. device, device->pipeline_conv2d_f16_f32[s], "conv2d_f16_f32", conv2d_f16_f32_cm2_len, conv2d_f16_f32_cm2_data, "main", 3,
  2753. sizeof(vk_op_conv2d_push_constants), wg_denoms, spec_constants, 1, true, use_collectives);
  2754. } else
  2755. #endif
  2756. if (conv2d_UNROLL) {
  2757. ggml_vk_create_pipeline(
  2758. device, device->pipeline_conv2d_f32[s], "conv2d_f32", conv2d_f32_unroll_len, conv2d_f32_unroll_data, "main", 3,
  2759. sizeof(vk_op_conv2d_push_constants), wg_denoms, spec_constants, 1, true, use_collectives);
  2760. ggml_vk_create_pipeline(
  2761. device, device->pipeline_conv2d_f16_f32[s], "conv2d_f16_f32", conv2d_f16_f32_unroll_len, conv2d_f16_f32_unroll_data, "main", 3,
  2762. sizeof(vk_op_conv2d_push_constants), wg_denoms, spec_constants, 1, true, use_collectives);
  2763. } else {
  2764. ggml_vk_create_pipeline(
  2765. device, device->pipeline_conv2d_f32[s], "conv2d_f32", conv2d_f32_len, conv2d_f32_data, "main", 3,
  2766. sizeof(vk_op_conv2d_push_constants), wg_denoms, spec_constants, 1, true, use_collectives);
  2767. ggml_vk_create_pipeline(
  2768. device, device->pipeline_conv2d_f16_f32[s], "conv2d_f16_f32", conv2d_f16_f32_len, conv2d_f16_f32_data, "main", 3,
  2769. sizeof(vk_op_conv2d_push_constants), wg_denoms, spec_constants, 1, true, use_collectives);
  2770. }
  2771. }
  2772. 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);
  2773. 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);
  2774. for (auto &c : compiles) {
  2775. c.wait();
  2776. }
  2777. device->need_compiles = false;
  2778. }
  2779. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch);
  2780. static vk_device ggml_vk_get_device(size_t idx) {
  2781. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  2782. if (vk_instance.devices[idx] == nullptr) {
  2783. VK_LOG_DEBUG("Initializing new vk_device");
  2784. vk_device device = std::make_shared<vk_device_struct>();
  2785. vk_instance.devices[idx] = device;
  2786. #ifdef GGML_VULKAN_MEMORY_DEBUG
  2787. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  2788. #endif
  2789. if (vk_perf_logger_enabled) {
  2790. device->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  2791. }
  2792. size_t dev_num = vk_instance.device_indices[idx];
  2793. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  2794. if (dev_num >= physical_devices.size()) {
  2795. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  2796. throw std::runtime_error("Device not found");
  2797. }
  2798. device->physical_device = physical_devices[dev_num];
  2799. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  2800. device->architecture = get_device_architecture(device->physical_device);
  2801. const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY");
  2802. device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr;
  2803. const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM");
  2804. device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr;
  2805. bool fp16_storage = false;
  2806. bool fp16_compute = false;
  2807. bool maintenance4_support = false;
  2808. bool sm_builtins = false;
  2809. bool amd_shader_core_properties2 = false;
  2810. bool pipeline_robustness = false;
  2811. bool coopmat2_support = false;
  2812. device->coopmat_support = false;
  2813. device->integer_dot_product = false;
  2814. bool bfloat16_support = false;
  2815. for (const auto& properties : ext_props) {
  2816. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  2817. maintenance4_support = true;
  2818. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  2819. fp16_storage = true;
  2820. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  2821. fp16_compute = true;
  2822. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  2823. sm_builtins = true;
  2824. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  2825. amd_shader_core_properties2 = true;
  2826. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  2827. pipeline_robustness = true;
  2828. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  2829. device->subgroup_size_control = true;
  2830. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2831. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  2832. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  2833. device->coopmat_support = true;
  2834. device->coopmat_m = 0;
  2835. device->coopmat_n = 0;
  2836. device->coopmat_k = 0;
  2837. #endif
  2838. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2839. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  2840. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  2841. coopmat2_support = true;
  2842. #endif
  2843. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2844. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  2845. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  2846. device->integer_dot_product = true;
  2847. #endif
  2848. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2849. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  2850. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  2851. bfloat16_support = true;
  2852. #endif
  2853. }
  2854. }
  2855. vk::PhysicalDeviceProperties2 props2;
  2856. vk::PhysicalDeviceMaintenance3Properties props3;
  2857. vk::PhysicalDeviceMaintenance4Properties props4;
  2858. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  2859. vk::PhysicalDeviceDriverProperties driver_props;
  2860. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  2861. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  2862. vk::PhysicalDeviceVulkan11Properties vk11_props;
  2863. vk::PhysicalDeviceVulkan12Properties vk12_props;
  2864. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  2865. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  2866. props2.pNext = &props3;
  2867. props3.pNext = &subgroup_props;
  2868. subgroup_props.pNext = &driver_props;
  2869. driver_props.pNext = &vk11_props;
  2870. vk11_props.pNext = &vk12_props;
  2871. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  2872. if (maintenance4_support) {
  2873. last_struct->pNext = (VkBaseOutStructure *)&props4;
  2874. last_struct = (VkBaseOutStructure *)&props4;
  2875. }
  2876. if (sm_builtins) {
  2877. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  2878. last_struct = (VkBaseOutStructure *)&sm_props;
  2879. }
  2880. if (amd_shader_core_properties2) {
  2881. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  2882. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  2883. }
  2884. if (device->subgroup_size_control) {
  2885. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  2886. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  2887. }
  2888. #if defined(VK_NV_cooperative_matrix2)
  2889. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  2890. if (coopmat2_support) {
  2891. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  2892. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  2893. }
  2894. #endif
  2895. if (device->integer_dot_product) {
  2896. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  2897. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  2898. }
  2899. device->physical_device.getProperties2(&props2);
  2900. device->properties = props2.properties;
  2901. device->vendor_id = device->properties.vendorID;
  2902. device->driver_id = driver_props.driverID;
  2903. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  2904. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  2905. device->max_memory_allocation_size = std::stoul(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  2906. } else if (maintenance4_support) {
  2907. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  2908. } else {
  2909. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  2910. }
  2911. const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE");
  2912. if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) {
  2913. device->suballocation_block_size = std::stoul(GGML_VK_SUBALLOCATION_BLOCK_SIZE);
  2914. } else {
  2915. // Limit batching of allocations to 1GB by default to avoid fragmentation issues
  2916. device->suballocation_block_size = 1024*1024*1024;
  2917. }
  2918. device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size);
  2919. device->subgroup_size = subgroup_props.subgroupSize;
  2920. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  2921. if (sm_builtins) {
  2922. device->shader_core_count = sm_props.shaderSMCount;
  2923. } else if (amd_shader_core_properties2) {
  2924. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  2925. } else {
  2926. device->shader_core_count = 0;
  2927. }
  2928. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  2929. device->subgroup_add = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  2930. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic);
  2931. device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  2932. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle);
  2933. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  2934. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  2935. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) {
  2936. device->coopmat_support = false;
  2937. }
  2938. device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated;
  2939. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  2940. // Try to find a non-graphics compute queue and transfer-focused queues
  2941. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  2942. 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);
  2943. const float priorities[] = { 1.0f, 1.0f };
  2944. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  2945. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  2946. if (compute_queue_family_index != transfer_queue_family_index) {
  2947. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  2948. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  2949. } else if(!device->single_queue) {
  2950. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  2951. } else {
  2952. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  2953. }
  2954. vk::DeviceCreateInfo device_create_info;
  2955. std::vector<const char *> device_extensions;
  2956. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  2957. VkPhysicalDeviceFeatures2 device_features2;
  2958. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  2959. device_features2.pNext = nullptr;
  2960. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  2961. VkPhysicalDeviceVulkan11Features vk11_features;
  2962. vk11_features.pNext = nullptr;
  2963. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  2964. device_features2.pNext = &vk11_features;
  2965. VkPhysicalDeviceVulkan12Features vk12_features;
  2966. vk12_features.pNext = nullptr;
  2967. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  2968. vk11_features.pNext = &vk12_features;
  2969. last_struct = (VkBaseOutStructure *)&vk12_features;
  2970. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  2971. pl_robustness_features.pNext = nullptr;
  2972. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  2973. pl_robustness_features.pipelineRobustness = VK_FALSE;
  2974. if (pipeline_robustness) {
  2975. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  2976. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  2977. device_extensions.push_back("VK_EXT_pipeline_robustness");
  2978. }
  2979. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  2980. subgroup_size_control_features.pNext = nullptr;
  2981. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  2982. subgroup_size_control_features.computeFullSubgroups = false;
  2983. subgroup_size_control_features.subgroupSizeControl = false;
  2984. if (device->subgroup_size_control) {
  2985. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  2986. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  2987. }
  2988. #if defined(VK_KHR_cooperative_matrix)
  2989. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  2990. coopmat_features.pNext = nullptr;
  2991. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  2992. coopmat_features.cooperativeMatrix = VK_FALSE;
  2993. if (device->coopmat_support) {
  2994. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  2995. last_struct = (VkBaseOutStructure *)&coopmat_features;
  2996. }
  2997. #endif
  2998. #if defined(VK_NV_cooperative_matrix2)
  2999. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  3000. coopmat2_features.pNext = nullptr;
  3001. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  3002. if (coopmat2_support) {
  3003. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  3004. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  3005. device_extensions.push_back("VK_NV_cooperative_matrix2");
  3006. }
  3007. #endif
  3008. #if defined(VK_KHR_shader_bfloat16)
  3009. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  3010. bfloat16_features.pNext = nullptr;
  3011. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  3012. if (bfloat16_support) {
  3013. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  3014. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  3015. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3016. }
  3017. #endif
  3018. VkPhysicalDeviceMaintenance4Features maint4_features {};
  3019. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  3020. if (maintenance4_support) {
  3021. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  3022. last_struct = (VkBaseOutStructure *)&maint4_features;
  3023. device_extensions.push_back("VK_KHR_maintenance4");
  3024. }
  3025. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  3026. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  3027. if (device->integer_dot_product) {
  3028. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3029. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3030. device_extensions.push_back("VK_KHR_shader_integer_dot_product");
  3031. }
  3032. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  3033. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  3034. #if defined(VK_KHR_shader_bfloat16)
  3035. device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  3036. #else
  3037. device->bf16 = false;
  3038. #endif
  3039. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  3040. device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 &&
  3041. device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) &&
  3042. vk12_features.runtimeDescriptorArray &&
  3043. device->vendor_id != VK_VENDOR_ID_INTEL &&
  3044. getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr;
  3045. if (device->subgroup_size_control) {
  3046. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  3047. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  3048. device_extensions.push_back("VK_EXT_subgroup_size_control");
  3049. }
  3050. device->subgroup_size_control = device->subgroup_size_control &&
  3051. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  3052. subgroup_size_control_features.subgroupSizeControl;
  3053. if (device->subgroup_size_control) {
  3054. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  3055. }
  3056. #if defined(VK_KHR_cooperative_matrix)
  3057. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  3058. // coopmat1 fa shader currently assumes 32 invocations per subgroup
  3059. device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support &&
  3060. device->subgroup_size_control && device->subgroup_min_size <= 32 &&
  3061. device->subgroup_max_size >= 32;
  3062. #endif
  3063. if (coopmat2_support) {
  3064. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3065. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  3066. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  3067. coopmat2_features.cooperativeMatrixReductions &&
  3068. coopmat2_features.cooperativeMatrixConversions &&
  3069. coopmat2_features.cooperativeMatrixPerElementOperations &&
  3070. coopmat2_features.cooperativeMatrixTensorAddressing &&
  3071. coopmat2_features.cooperativeMatrixBlockLoads &&
  3072. vk12_features.bufferDeviceAddress) {
  3073. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  3074. uint32_t count = 0;
  3075. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  3076. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  3077. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  3078. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  3079. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  3080. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  3081. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  3082. flexible_dimensions.resize(count, empty_prop);
  3083. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  3084. bool found_fp16_128 = false,
  3085. found_fp16_256 = false,
  3086. found_fp32_128 = false,
  3087. found_fp32_256 = false;
  3088. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  3089. // with 32x16x16 and 256 with 32x32x16.
  3090. for (auto &prop : flexible_dimensions) {
  3091. if (prop.saturatingAccumulation == VK_FALSE &&
  3092. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  3093. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3094. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3095. if (prop.workgroupInvocations == 128 &&
  3096. prop.MGranularity <= 32 &&
  3097. prop.NGranularity <= 16 &&
  3098. prop.KGranularity <= 16) {
  3099. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3100. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3101. found_fp16_128 = true;
  3102. }
  3103. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3104. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3105. found_fp32_128 = true;
  3106. }
  3107. }
  3108. if (prop.workgroupInvocations == 256 &&
  3109. prop.MGranularity <= 32 &&
  3110. prop.NGranularity <= 32 &&
  3111. prop.KGranularity <= 16) {
  3112. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3113. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3114. found_fp16_256 = true;
  3115. }
  3116. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3117. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3118. found_fp32_256 = true;
  3119. }
  3120. }
  3121. }
  3122. }
  3123. if (found_fp16_128 && found_fp16_256 &&
  3124. found_fp32_128 && found_fp32_256 &&
  3125. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  3126. device->coopmat2 = true;
  3127. }
  3128. }
  3129. #endif
  3130. }
  3131. if (!vk11_features.storageBuffer16BitAccess) {
  3132. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  3133. throw std::runtime_error("Unsupported device");
  3134. }
  3135. device_extensions.push_back("VK_KHR_16bit_storage");
  3136. #ifdef GGML_VULKAN_VALIDATE
  3137. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  3138. #endif
  3139. if (device->fp16) {
  3140. device_extensions.push_back("VK_KHR_shader_float16_int8");
  3141. }
  3142. #if defined(VK_KHR_cooperative_matrix)
  3143. if (device->coopmat_support) {
  3144. // Query supported shapes
  3145. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  3146. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  3147. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  3148. uint32_t cm_props_num;
  3149. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  3150. cm_props.resize(cm_props_num);
  3151. for (auto& prop : cm_props) {
  3152. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  3153. }
  3154. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  3155. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  3156. for (auto& prop : cm_props) {
  3157. 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));
  3158. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  3159. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  3160. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3161. ) {
  3162. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  3163. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  3164. // coopmat sizes not set yet
  3165. if (device->coopmat_m == 0) {
  3166. device->coopmat_acc_f32_support = true;
  3167. device->coopmat_m = prop.MSize;
  3168. device->coopmat_n = prop.NSize;
  3169. device->coopmat_k = prop.KSize;
  3170. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3171. // Only enable if shape is identical
  3172. device->coopmat_acc_f32_support = true;
  3173. }
  3174. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3175. device->coopmat_support_16x16x16_f32acc = true;
  3176. }
  3177. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  3178. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  3179. // coopmat sizes not set yet
  3180. if (device->coopmat_m == 0) {
  3181. device->coopmat_acc_f16_support = true;
  3182. device->coopmat_m = prop.MSize;
  3183. device->coopmat_n = prop.NSize;
  3184. device->coopmat_k = prop.KSize;
  3185. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3186. // Only enable if shape is identical
  3187. device->coopmat_acc_f16_support = true;
  3188. }
  3189. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3190. device->coopmat_support_16x16x16_f16acc = true;
  3191. }
  3192. }
  3193. } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 &&
  3194. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 &&
  3195. (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 &&
  3196. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 &&
  3197. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup &&
  3198. device->coopmat_int_m == 0
  3199. ) {
  3200. device->coopmat_int_support = true;
  3201. device->coopmat_int_m = prop.MSize;
  3202. device->coopmat_int_n = prop.NSize;
  3203. device->coopmat_int_k = prop.KSize;
  3204. }
  3205. #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3206. if (prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3207. prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  3208. prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3209. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3210. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3211. ) {
  3212. // coopmat sizes not set yet
  3213. if (device->coopmat_m == 0) {
  3214. device->coopmat_bf16_support = true;
  3215. device->coopmat_m = prop.MSize;
  3216. device->coopmat_n = prop.NSize;
  3217. device->coopmat_k = prop.KSize;
  3218. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3219. // Only enable if shape is identical
  3220. device->coopmat_bf16_support = true;
  3221. }
  3222. }
  3223. #endif
  3224. }
  3225. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  3226. // No suitable matmul mode found
  3227. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  3228. device->coopmat_support = false;
  3229. }
  3230. if (getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3231. device->coopmat_bf16_support = false;
  3232. }
  3233. }
  3234. if (device->coopmat_support) {
  3235. device_extensions.push_back("VK_KHR_cooperative_matrix");
  3236. }
  3237. #if defined(VK_KHR_shader_bfloat16)
  3238. if (device->coopmat_bf16_support) {
  3239. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3240. }
  3241. #endif
  3242. #endif
  3243. device->name = GGML_VK_NAME + std::to_string(idx);
  3244. device_create_info = {
  3245. vk::DeviceCreateFlags(),
  3246. device_queue_create_infos,
  3247. {},
  3248. device_extensions
  3249. };
  3250. device_create_info.setPNext(&device_features2);
  3251. device->device = device->physical_device.createDevice(device_create_info);
  3252. // Queues
  3253. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  3254. // Shaders
  3255. // Disable matmul tile sizes early if performance low or not supported
  3256. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  3257. switch (device->vendor_id) {
  3258. #ifndef GGML_VULKAN_RUN_TESTS
  3259. case VK_VENDOR_ID_AMD:
  3260. case VK_VENDOR_ID_INTEL:
  3261. device->mul_mat_l[i] = false;
  3262. device->mul_mat_m[i] = true;
  3263. device->mul_mat_s[i] = true;
  3264. device->mul_mat_id_l[i] = false;
  3265. device->mul_mat_id_m[i] = true;
  3266. device->mul_mat_id_s[i] = true;
  3267. break;
  3268. case VK_VENDOR_ID_APPLE:
  3269. device->mul_mat_l[i] = false;
  3270. device->mul_mat_m[i] = true;
  3271. device->mul_mat_s[i] = false;
  3272. device->mul_mat_id_l[i] = false;
  3273. device->mul_mat_id_m[i] = true;
  3274. device->mul_mat_id_s[i] = false;
  3275. break;
  3276. #endif
  3277. default:
  3278. device->mul_mat_l[i] = true;
  3279. device->mul_mat_m[i] = true;
  3280. device->mul_mat_s[i] = true;
  3281. device->mul_mat_id_l[i] = true;
  3282. device->mul_mat_id_m[i] = true;
  3283. device->mul_mat_id_s[i] = true;
  3284. break;
  3285. }
  3286. }
  3287. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  3288. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  3289. for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
  3290. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  3291. dsl_binding_flags.push_back({});
  3292. }
  3293. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  3294. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  3295. {},
  3296. dsl_binding);
  3297. descriptor_set_layout_create_info.setPNext(&dslbfci);
  3298. device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  3299. ggml_vk_load_shaders(device);
  3300. if (!device->single_queue) {
  3301. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  3302. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  3303. } else {
  3304. // TODO: Use pointer or reference to avoid copy
  3305. device->transfer_queue.copyFrom(device->compute_queue);
  3306. device->transfer_queue.cmd_pool.init(device, &device->transfer_queue);
  3307. }
  3308. device->buffer_type = {
  3309. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  3310. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  3311. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  3312. };
  3313. device->fence = device->device.createFence({});
  3314. device->idx = idx;
  3315. device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr;
  3316. return device;
  3317. }
  3318. return vk_instance.devices[idx];
  3319. }
  3320. static void ggml_vk_print_gpu_info(size_t idx) {
  3321. GGML_ASSERT(idx < vk_instance.device_indices.size());
  3322. size_t dev_num = vk_instance.device_indices[idx];
  3323. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  3324. GGML_ASSERT(vk_instance_initialized);
  3325. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  3326. if (dev_num >= devices.size()) {
  3327. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3328. throw std::runtime_error("Device not found");
  3329. }
  3330. vk::PhysicalDevice physical_device = devices[dev_num];
  3331. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  3332. bool fp16_storage = false;
  3333. bool fp16_compute = false;
  3334. bool coopmat_support = false;
  3335. bool coopmat2_support = false;
  3336. bool integer_dot_product = false;
  3337. bool bfloat16_support = false;
  3338. for (auto properties : ext_props) {
  3339. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3340. fp16_storage = true;
  3341. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3342. fp16_compute = true;
  3343. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3344. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3345. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3346. coopmat_support = true;
  3347. #endif
  3348. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3349. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3350. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3351. coopmat2_support = true;
  3352. #endif
  3353. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3354. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3355. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3356. integer_dot_product = true;
  3357. #endif
  3358. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3359. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3360. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3361. bfloat16_support = true;
  3362. #endif
  3363. }
  3364. }
  3365. const vk_device_architecture device_architecture = get_device_architecture(physical_device);
  3366. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  3367. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  3368. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  3369. vk::PhysicalDeviceProperties2 props2;
  3370. vk::PhysicalDeviceMaintenance3Properties props3;
  3371. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3372. vk::PhysicalDeviceDriverProperties driver_props;
  3373. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3374. props2.pNext = &props3;
  3375. props3.pNext = &subgroup_props;
  3376. subgroup_props.pNext = &driver_props;
  3377. // Pointer to the last chain element
  3378. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  3379. if (integer_dot_product) {
  3380. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3381. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3382. }
  3383. physical_device.getProperties2(&props2);
  3384. VkPhysicalDeviceFeatures2 device_features2;
  3385. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  3386. device_features2.pNext = nullptr;
  3387. VkPhysicalDeviceVulkan11Features vk11_features;
  3388. vk11_features.pNext = nullptr;
  3389. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  3390. device_features2.pNext = &vk11_features;
  3391. VkPhysicalDeviceVulkan12Features vk12_features;
  3392. vk12_features.pNext = nullptr;
  3393. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  3394. vk11_features.pNext = &vk12_features;
  3395. // Pointer to the last chain element
  3396. last_struct = (VkBaseOutStructure *)&vk12_features;
  3397. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3398. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  3399. coopmat_features.pNext = nullptr;
  3400. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  3401. coopmat_features.cooperativeMatrix = VK_FALSE;
  3402. if (coopmat_support) {
  3403. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  3404. last_struct = (VkBaseOutStructure *)&coopmat_features;
  3405. }
  3406. #endif
  3407. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  3408. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  3409. if (integer_dot_product) {
  3410. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3411. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3412. }
  3413. #if defined(VK_KHR_shader_bfloat16)
  3414. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  3415. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  3416. if (bfloat16_support) {
  3417. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  3418. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  3419. }
  3420. #endif
  3421. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  3422. fp16 = fp16 && vk12_features.shaderFloat16;
  3423. #if defined(VK_KHR_shader_bfloat16)
  3424. bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  3425. #else
  3426. bool bf16 = false;
  3427. #endif
  3428. uint32_t default_subgroup_size = get_subgroup_size("", device_architecture);
  3429. const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize;
  3430. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3431. integer_dot_product = integer_dot_product
  3432. && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated
  3433. && shader_integer_dot_product_features.shaderIntegerDotProduct;
  3434. coopmat_support = coopmat_support
  3435. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3436. && coopmat_features.cooperativeMatrix
  3437. #endif
  3438. && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture);
  3439. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  3440. std::string device_name = props2.properties.deviceName.data();
  3441. 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",
  3442. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, bf16, subgroup_size,
  3443. props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str());
  3444. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  3445. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  3446. }
  3447. }
  3448. static bool ggml_vk_instance_validation_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  3449. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  3450. static bool ggml_vk_instance_debug_utils_ext_available(const std::vector<vk::ExtensionProperties> & instance_extensions);
  3451. static void ggml_vk_instance_init() {
  3452. if (vk_instance_initialized) {
  3453. return;
  3454. }
  3455. VK_LOG_DEBUG("ggml_vk_instance_init()");
  3456. uint32_t api_version = vk::enumerateInstanceVersion();
  3457. if (api_version < VK_API_VERSION_1_2) {
  3458. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  3459. GGML_ABORT("fatal error");
  3460. }
  3461. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  3462. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  3463. const bool validation_ext = ggml_vk_instance_validation_ext_available(instance_extensions);
  3464. #ifdef __APPLE__
  3465. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  3466. #endif
  3467. const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr;
  3468. std::vector<const char*> layers;
  3469. if (validation_ext) {
  3470. layers.push_back("VK_LAYER_KHRONOS_validation");
  3471. }
  3472. std::vector<const char*> extensions;
  3473. if (validation_ext) {
  3474. extensions.push_back("VK_EXT_validation_features");
  3475. }
  3476. #ifdef __APPLE__
  3477. if (portability_enumeration_ext) {
  3478. extensions.push_back("VK_KHR_portability_enumeration");
  3479. }
  3480. #endif
  3481. if (debug_utils_ext) {
  3482. extensions.push_back("VK_EXT_debug_utils");
  3483. }
  3484. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions);
  3485. #ifdef __APPLE__
  3486. if (portability_enumeration_ext) {
  3487. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  3488. }
  3489. #endif
  3490. std::vector<vk::ValidationFeatureEnableEXT> features_enable;
  3491. vk::ValidationFeaturesEXT validation_features;
  3492. if (validation_ext) {
  3493. features_enable = { vk::ValidationFeatureEnableEXT::eBestPractices };
  3494. validation_features = {
  3495. features_enable,
  3496. {},
  3497. };
  3498. validation_features.setPNext(nullptr);
  3499. instance_create_info.setPNext(&validation_features);
  3500. GGML_LOG_DEBUG("ggml_vulkan: Validation layers enabled\n");
  3501. }
  3502. vk_instance.instance = vk::createInstance(instance_create_info);
  3503. vk_instance_initialized = true;
  3504. if (debug_utils_ext) {
  3505. vk_instance.debug_utils_support = true;
  3506. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT");
  3507. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT");
  3508. vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT");
  3509. vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT");
  3510. vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT");
  3511. vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT");
  3512. }
  3513. vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr;
  3514. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  3515. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  3516. if (devices_env != nullptr) {
  3517. size_t num_available_devices = vk_instance.instance.enumeratePhysicalDevices().size();
  3518. std::string devices(devices_env);
  3519. std::replace(devices.begin(), devices.end(), ',', ' ');
  3520. std::stringstream ss(devices);
  3521. size_t tmp;
  3522. while (ss >> tmp) {
  3523. if(tmp >= num_available_devices) {
  3524. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  3525. throw std::runtime_error("Invalid Vulkan device index");
  3526. }
  3527. vk_instance.device_indices.push_back(tmp);
  3528. }
  3529. } else {
  3530. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  3531. // If no vulkan devices are found, return early
  3532. if (devices.empty()) {
  3533. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  3534. return;
  3535. }
  3536. // Default to using all dedicated GPUs
  3537. for (size_t i = 0; i < devices.size(); i++) {
  3538. vk::PhysicalDeviceProperties2 new_props;
  3539. vk::PhysicalDeviceDriverProperties new_driver;
  3540. vk::PhysicalDeviceIDProperties new_id;
  3541. new_props.pNext = &new_driver;
  3542. new_driver.pNext = &new_id;
  3543. devices[i].getProperties2(&new_props);
  3544. if (new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) {
  3545. // Check if there are two physical devices corresponding to the same GPU
  3546. auto old_device = std::find_if(
  3547. vk_instance.device_indices.begin(),
  3548. vk_instance.device_indices.end(),
  3549. [&devices, &new_id](const size_t k){
  3550. vk::PhysicalDeviceProperties2 old_props;
  3551. vk::PhysicalDeviceIDProperties old_id;
  3552. old_props.pNext = &old_id;
  3553. devices[k].getProperties2(&old_props);
  3554. return std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  3555. }
  3556. );
  3557. if (old_device == vk_instance.device_indices.end()) {
  3558. vk_instance.device_indices.push_back(i);
  3559. } else {
  3560. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  3561. // This can cause error when splitting layers aross the devices, need to keep only 1
  3562. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  3563. vk::PhysicalDeviceProperties2 old_props;
  3564. vk::PhysicalDeviceDriverProperties old_driver;
  3565. old_props.pNext = &old_driver;
  3566. devices[*old_device].getProperties2(&old_props);
  3567. std::map<vk::DriverId, int> driver_priorities {};
  3568. int old_priority = std::numeric_limits<int>::max();
  3569. int new_priority = std::numeric_limits<int>::max();
  3570. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  3571. // Smaller number -> higher priority
  3572. switch (old_props.properties.vendorID) {
  3573. case VK_VENDOR_ID_AMD:
  3574. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  3575. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  3576. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  3577. break;
  3578. case VK_VENDOR_ID_INTEL:
  3579. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  3580. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  3581. break;
  3582. case VK_VENDOR_ID_NVIDIA:
  3583. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  3584. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  3585. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  3586. #endif
  3587. break;
  3588. }
  3589. if (driver_priorities.count(old_driver.driverID)) {
  3590. old_priority = driver_priorities[old_driver.driverID];
  3591. }
  3592. if (driver_priorities.count(new_driver.driverID)) {
  3593. new_priority = driver_priorities[new_driver.driverID];
  3594. }
  3595. if (new_priority < old_priority) {
  3596. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  3597. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  3598. vk_instance.device_indices.push_back(i);
  3599. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  3600. }
  3601. else {
  3602. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  3603. }
  3604. }
  3605. }
  3606. }
  3607. // If no dedicated GPUs found, fall back to the first non-CPU device.
  3608. // If only CPU devices are available, return without devices.
  3609. if (vk_instance.device_indices.empty()) {
  3610. for (size_t i = 0; i < devices.size(); i++) {
  3611. if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) {
  3612. vk_instance.device_indices.push_back(i);
  3613. break;
  3614. }
  3615. }
  3616. }
  3617. if (vk_instance.device_indices.empty()) {
  3618. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  3619. return;
  3620. }
  3621. }
  3622. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  3623. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  3624. ggml_vk_print_gpu_info(i);
  3625. }
  3626. }
  3627. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  3628. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  3629. ggml_vk_instance_init();
  3630. GGML_ASSERT(idx < vk_instance.device_indices.size());
  3631. ctx->name = GGML_VK_NAME + std::to_string(idx);
  3632. ctx->device = ggml_vk_get_device(idx);
  3633. ctx->semaphore_idx = 0;
  3634. ctx->event_idx = 0;
  3635. ctx->prealloc_size_x = 0;
  3636. ctx->prealloc_size_y = 0;
  3637. ctx->prealloc_size_split_k = 0;
  3638. ctx->fence = ctx->device->device.createFence({});
  3639. ctx->almost_ready_fence = ctx->device->device.createFence({});
  3640. ctx->compute_cmd_pool.init(ctx->device, &ctx->device->compute_queue);
  3641. ctx->transfer_cmd_pool.init(ctx->device, &ctx->device->transfer_queue);
  3642. #ifdef GGML_VULKAN_CHECK_RESULTS
  3643. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  3644. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  3645. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  3646. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  3647. #endif
  3648. }
  3649. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  3650. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  3651. switch (type) {
  3652. case GGML_TYPE_F32:
  3653. case GGML_TYPE_Q4_0:
  3654. case GGML_TYPE_Q4_1:
  3655. case GGML_TYPE_Q5_0:
  3656. case GGML_TYPE_Q5_1:
  3657. case GGML_TYPE_Q8_0:
  3658. case GGML_TYPE_Q2_K:
  3659. case GGML_TYPE_Q3_K:
  3660. case GGML_TYPE_Q4_K:
  3661. case GGML_TYPE_Q5_K:
  3662. case GGML_TYPE_Q6_K:
  3663. case GGML_TYPE_IQ1_S:
  3664. case GGML_TYPE_IQ1_M:
  3665. case GGML_TYPE_IQ2_XXS:
  3666. case GGML_TYPE_IQ2_XS:
  3667. case GGML_TYPE_IQ2_S:
  3668. case GGML_TYPE_IQ3_XXS:
  3669. case GGML_TYPE_IQ3_S:
  3670. case GGML_TYPE_IQ4_XS:
  3671. case GGML_TYPE_IQ4_NL:
  3672. case GGML_TYPE_MXFP4:
  3673. break;
  3674. default:
  3675. return nullptr;
  3676. }
  3677. return ctx->device->pipeline_dequant[type];
  3678. }
  3679. 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) {
  3680. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ", " << prec << ")");
  3681. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  3682. return ctx->device->pipeline_matmul_f32;
  3683. }
  3684. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  3685. return ctx->device->pipeline_matmul_f32_f16;
  3686. }
  3687. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  3688. return ctx->device->pipeline_matmul_bf16;
  3689. }
  3690. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  3691. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  3692. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  3693. }
  3694. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  3695. return ctx->device->pipeline_matmul_f16.f16acc;
  3696. }
  3697. } else {
  3698. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  3699. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  3700. }
  3701. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  3702. return ctx->device->pipeline_matmul_f16.f32acc;
  3703. }
  3704. }
  3705. // MMQ
  3706. if (src1_type == GGML_TYPE_Q8_1) {
  3707. 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;
  3708. if (pipelines->s == nullptr && pipelines->m == nullptr && pipelines->l == nullptr) {
  3709. return nullptr;
  3710. }
  3711. return pipelines;
  3712. }
  3713. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  3714. return nullptr;
  3715. }
  3716. switch (src0_type) {
  3717. case GGML_TYPE_Q4_0:
  3718. case GGML_TYPE_Q4_1:
  3719. case GGML_TYPE_Q5_0:
  3720. case GGML_TYPE_Q5_1:
  3721. case GGML_TYPE_Q8_0:
  3722. case GGML_TYPE_Q2_K:
  3723. case GGML_TYPE_Q3_K:
  3724. case GGML_TYPE_Q4_K:
  3725. case GGML_TYPE_Q5_K:
  3726. case GGML_TYPE_Q6_K:
  3727. case GGML_TYPE_IQ1_S:
  3728. case GGML_TYPE_IQ1_M:
  3729. case GGML_TYPE_IQ2_XXS:
  3730. case GGML_TYPE_IQ2_XS:
  3731. case GGML_TYPE_IQ2_S:
  3732. case GGML_TYPE_IQ3_XXS:
  3733. case GGML_TYPE_IQ3_S:
  3734. case GGML_TYPE_IQ4_XS:
  3735. case GGML_TYPE_IQ4_NL:
  3736. case GGML_TYPE_MXFP4:
  3737. break;
  3738. default:
  3739. return nullptr;
  3740. }
  3741. if (ctx->device->coopmat2) {
  3742. assert(src1_type == GGML_TYPE_F16);
  3743. 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;
  3744. }
  3745. if (ctx->device->coopmat_support) {
  3746. 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;
  3747. }
  3748. 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;
  3749. }
  3750. 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) {
  3751. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  3752. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16);
  3753. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  3754. switch (a_type) {
  3755. case GGML_TYPE_F32:
  3756. case GGML_TYPE_F16:
  3757. case GGML_TYPE_BF16:
  3758. case GGML_TYPE_Q4_0:
  3759. case GGML_TYPE_Q4_1:
  3760. case GGML_TYPE_Q5_0:
  3761. case GGML_TYPE_Q5_1:
  3762. case GGML_TYPE_Q8_0:
  3763. case GGML_TYPE_Q2_K:
  3764. case GGML_TYPE_Q3_K:
  3765. case GGML_TYPE_Q4_K:
  3766. case GGML_TYPE_Q5_K:
  3767. case GGML_TYPE_Q6_K:
  3768. case GGML_TYPE_IQ1_S:
  3769. case GGML_TYPE_IQ1_M:
  3770. case GGML_TYPE_IQ2_XXS:
  3771. case GGML_TYPE_IQ2_XS:
  3772. case GGML_TYPE_IQ2_S:
  3773. case GGML_TYPE_IQ3_XXS:
  3774. case GGML_TYPE_IQ3_S:
  3775. case GGML_TYPE_IQ4_XS:
  3776. case GGML_TYPE_IQ4_NL:
  3777. case GGML_TYPE_MXFP4:
  3778. break;
  3779. default:
  3780. return nullptr;
  3781. }
  3782. return b_type == GGML_TYPE_F32 ? ctx->device->pipeline_dequant_mul_mat_vec_f32_f32[a_type][num_cols-1] : ctx->device->pipeline_dequant_mul_mat_vec_f16_f32[a_type][num_cols-1];
  3783. }
  3784. 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) {
  3785. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  3786. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  3787. return ctx->device->pipeline_matmul_id_f32;
  3788. }
  3789. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  3790. return ctx->device->pipeline_matmul_id_bf16;
  3791. }
  3792. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  3793. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  3794. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  3795. }
  3796. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  3797. return ctx->device->pipeline_matmul_id_f16.f16acc;
  3798. }
  3799. } else {
  3800. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  3801. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  3802. }
  3803. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  3804. return ctx->device->pipeline_matmul_id_f16.f32acc;
  3805. }
  3806. }
  3807. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  3808. switch (src0_type) {
  3809. case GGML_TYPE_Q4_0:
  3810. case GGML_TYPE_Q4_1:
  3811. case GGML_TYPE_Q5_0:
  3812. case GGML_TYPE_Q5_1:
  3813. case GGML_TYPE_Q8_0:
  3814. case GGML_TYPE_Q2_K:
  3815. case GGML_TYPE_Q3_K:
  3816. case GGML_TYPE_Q4_K:
  3817. case GGML_TYPE_Q5_K:
  3818. case GGML_TYPE_Q6_K:
  3819. case GGML_TYPE_IQ1_S:
  3820. case GGML_TYPE_IQ1_M:
  3821. case GGML_TYPE_IQ2_XXS:
  3822. case GGML_TYPE_IQ2_XS:
  3823. case GGML_TYPE_IQ2_S:
  3824. case GGML_TYPE_IQ3_XXS:
  3825. case GGML_TYPE_IQ3_S:
  3826. case GGML_TYPE_IQ4_XS:
  3827. case GGML_TYPE_IQ4_NL:
  3828. case GGML_TYPE_MXFP4:
  3829. break;
  3830. default:
  3831. return nullptr;
  3832. }
  3833. // XXX TODO 'prec' is not actually allowed in mul_mat_id.
  3834. bool prefer_fp16acc = ctx->device->fp16 /*&& prec == GGML_PREC_DEFAULT*/;
  3835. bool support_fp16acc = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f16acc != nullptr;
  3836. bool support_fp32acc = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f32acc != nullptr;
  3837. if (support_fp16acc && (prefer_fp16acc || !support_fp32acc)) {
  3838. return ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f16acc;
  3839. } else {
  3840. GGML_ASSERT(support_fp32acc);
  3841. return ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type].f32acc;
  3842. }
  3843. }
  3844. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type) {
  3845. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  3846. GGML_ASSERT(b_type == GGML_TYPE_F32);
  3847. switch (a_type) {
  3848. case GGML_TYPE_F32:
  3849. case GGML_TYPE_F16:
  3850. case GGML_TYPE_BF16:
  3851. case GGML_TYPE_Q4_0:
  3852. case GGML_TYPE_Q4_1:
  3853. case GGML_TYPE_Q5_0:
  3854. case GGML_TYPE_Q5_1:
  3855. case GGML_TYPE_Q8_0:
  3856. case GGML_TYPE_Q2_K:
  3857. case GGML_TYPE_Q3_K:
  3858. case GGML_TYPE_Q4_K:
  3859. case GGML_TYPE_Q5_K:
  3860. case GGML_TYPE_Q6_K:
  3861. case GGML_TYPE_IQ1_S:
  3862. case GGML_TYPE_IQ1_M:
  3863. case GGML_TYPE_IQ2_XXS:
  3864. case GGML_TYPE_IQ2_XS:
  3865. case GGML_TYPE_IQ2_S:
  3866. case GGML_TYPE_IQ3_XXS:
  3867. case GGML_TYPE_IQ3_S:
  3868. case GGML_TYPE_IQ4_XS:
  3869. case GGML_TYPE_IQ4_NL:
  3870. case GGML_TYPE_MXFP4:
  3871. break;
  3872. default:
  3873. return nullptr;
  3874. }
  3875. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[a_type];
  3876. }
  3877. static vk_buffer ggml_vk_pool_malloc(ggml_backend_vk_context * ctx, size_t size) {
  3878. VK_LOG_DEBUG("ggml_vk_pool_malloc(" << size << ")");
  3879. VK_LOG_MEMORY("ggml_vk_pool_malloc");
  3880. int best_i = -1;
  3881. size_t best_size = std::numeric_limits<size_t>::max(); //smallest unused buffer that fits our needs
  3882. int worst_i = -1;
  3883. size_t worst_size = 0; //largest unused buffer seen so far
  3884. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  3885. vk_buffer &b = ctx->buffer_pool[i];
  3886. if (b != nullptr && b->size >= size && b->size < best_size) {
  3887. best_i = i;
  3888. best_size = b->size;
  3889. }
  3890. if (b != nullptr && b->size > worst_size) {
  3891. worst_i = i;
  3892. worst_size = b->size;
  3893. }
  3894. }
  3895. if(best_i != -1) {
  3896. //found the smallest buffer that fits our needs
  3897. vk_buffer b = ctx->buffer_pool[best_i];
  3898. ctx->buffer_pool[best_i].reset();
  3899. return b;
  3900. }
  3901. if(worst_i != -1) {
  3902. //no buffer that fits our needs, resize largest one to save memory
  3903. vk_buffer& b = ctx->buffer_pool[worst_i];
  3904. ggml_vk_destroy_buffer(b);
  3905. }
  3906. return ggml_vk_create_buffer_device(ctx->device, size);
  3907. }
  3908. static void ggml_vk_pool_free(ggml_backend_vk_context * ctx, vk_buffer& buffer) {
  3909. VK_LOG_DEBUG("ggml_vk_pool_free(" << buffer->size << ")");
  3910. for (int i = 0; i < MAX_VK_BUFFERS; ++i) {
  3911. vk_buffer& b = ctx->buffer_pool[i];
  3912. if (b == nullptr) {
  3913. b = buffer;
  3914. return;
  3915. }
  3916. }
  3917. std::cerr << "ggml_vulkan: WARNING: vk buffer pool full, increase MAX_VK_BUFFERS" << std::endl;
  3918. ggml_vk_destroy_buffer(buffer);
  3919. }
  3920. // Returns an available temporary buffer that may only be used temporarily, it will be reused
  3921. static vk_buffer ggml_vk_create_buffer_temp(ggml_backend_vk_context * ctx, size_t size) {
  3922. // Try to find existing temp buffer with enough capacity
  3923. for (auto& buffer : ctx->gc.temp_buffers) {
  3924. if (buffer->size >= size) {
  3925. return buffer;
  3926. }
  3927. }
  3928. VK_LOG_MEMORY("ggml_vk_create_buffer_temp(" << size << ")");
  3929. // Otherwise create new buffer
  3930. vk_buffer buf = ggml_vk_pool_malloc(ctx, size);
  3931. ctx->gc.temp_buffers.push_back(buf);
  3932. return buf;
  3933. }
  3934. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  3935. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  3936. vk_buffer buf = ggml_vk_create_buffer(device, size,
  3937. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  3938. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  3939. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  3940. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  3941. size/1024.0/1024.0);
  3942. device->device.freeMemory(buf->device_memory);
  3943. device->device.destroyBuffer(buf->buffer);
  3944. return nullptr;
  3945. }
  3946. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  3947. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  3948. return buf->ptr;
  3949. }
  3950. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  3951. if (ptr == nullptr) {
  3952. return;
  3953. }
  3954. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  3955. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  3956. vk_buffer buf;
  3957. size_t index;
  3958. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  3959. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  3960. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  3961. if (ptr >= addr && ptr < endr) {
  3962. buf = std::get<2>(device->pinned_memory[i]);
  3963. index = i;
  3964. break;
  3965. }
  3966. }
  3967. if (buf == nullptr) {
  3968. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  3969. return;
  3970. }
  3971. ggml_vk_destroy_buffer(buf);
  3972. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  3973. }
  3974. static void ggml_vk_host_get(vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  3975. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  3976. buf = nullptr;
  3977. buf_offset = 0;
  3978. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  3979. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  3980. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  3981. if (ptr >= addr && ptr < endr) {
  3982. buf = std::get<2>(device->pinned_memory[i]);
  3983. buf_offset = ((const uint8_t *)ptr) - addr;
  3984. break;
  3985. }
  3986. }
  3987. }
  3988. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) {
  3989. vk_submission s;
  3990. s.buffer = ggml_vk_create_cmd_buffer(device, p);
  3991. if (one_time) {
  3992. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  3993. } else {
  3994. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  3995. }
  3996. return s;
  3997. }
  3998. template <typename T> size_t push_constant_size(const T &t) {
  3999. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4000. GGML_UNUSED(t);
  4001. return sizeof(T);
  4002. }
  4003. template <typename T> size_t push_constant_size(const std::vector<T> &t) {
  4004. GGML_UNUSED(t);
  4005. return sizeof(T) * t.size();
  4006. }
  4007. template <typename T, uint32_t N> size_t push_constant_size(const std::array<T, N> &t) {
  4008. GGML_UNUSED(t);
  4009. return sizeof(T) * N;
  4010. }
  4011. template <typename T> const T *push_constant_data(const T &t) {
  4012. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4013. return &t;
  4014. }
  4015. template <typename T> const T *push_constant_data(const std::vector<T> &t) {
  4016. return t.data();
  4017. }
  4018. template <typename T, uint32_t N> const T *push_constant_data(const std::array<T, N> &t) {
  4019. return t.data();
  4020. }
  4021. template <typename T>
  4022. 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) {
  4023. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  4024. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  4025. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  4026. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  4027. for (auto& buffer : descriptor_buffer_infos) {
  4028. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  4029. }
  4030. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  4031. GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size());
  4032. GGML_ASSERT(descriptor_buffer_infos.size() <= MAX_PARAMETER_COUNT);
  4033. GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size());
  4034. vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[ctx->descriptor_set_idx++];
  4035. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  4036. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  4037. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size(push_constants), push_constant_data(push_constants));
  4038. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  4039. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  4040. pipeline->layout,
  4041. 0,
  4042. { descriptor_set },
  4043. {});
  4044. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  4045. }
  4046. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  4047. s.buffer.end();
  4048. s.wait_semaphores = std::move(wait_semaphores);
  4049. s.signal_semaphores = std::move(signal_semaphores);
  4050. }
  4051. static void ggml_vk_ctx_end(vk_context& ctx) {
  4052. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  4053. if (ctx->s == nullptr) {
  4054. return;
  4055. }
  4056. ctx->s->buffer.end();
  4057. ctx->s = nullptr;
  4058. }
  4059. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  4060. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  4061. if (subctx->s != nullptr) {
  4062. ggml_vk_ctx_end(subctx);
  4063. }
  4064. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) });
  4065. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  4066. }
  4067. static size_t ggml_vk_align_size(size_t width, size_t align) {
  4068. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  4069. return CEIL_DIV(width, align) * align;
  4070. }
  4071. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  4072. if (memcpys == nullptr) {
  4073. memcpy(dst, src, size);
  4074. } else {
  4075. memcpys->emplace_back(dst, src, size);
  4076. }
  4077. }
  4078. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  4079. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  4080. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  4081. ggml_vk_destroy_buffer(device->sync_staging);
  4082. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  4083. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4084. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  4085. }
  4086. }
  4087. 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) {
  4088. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  4089. GGML_ASSERT(!ggml_is_contiguous(tensor));
  4090. // Buffer is already mapped
  4091. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4092. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4093. GGML_ABORT("fatal error");
  4094. }
  4095. // Check if src is pinned memory
  4096. vk_buffer buf = nullptr;
  4097. size_t buf_offset = 0;
  4098. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  4099. const uint64_t ne0 = tensor->ne[0];
  4100. const uint64_t ne1 = tensor->ne[1];
  4101. const uint64_t ne2 = tensor->ne[2];
  4102. const uint64_t ne3 = tensor->ne[3];
  4103. const uint64_t nb0 = tensor->nb[0];
  4104. const uint64_t nb1 = tensor->nb[1];
  4105. const uint64_t nb2 = tensor->nb[2];
  4106. const uint64_t nb3 = tensor->nb[3];
  4107. const ggml_type type = tensor->type;
  4108. const uint64_t ts = ggml_type_size(type);
  4109. const uint64_t bs = ggml_blck_size(type);
  4110. const uint64_t dstnb0 = ts;
  4111. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  4112. const uint64_t dstnb2 = dstnb1*ne1;
  4113. const uint64_t dstnb3 = dstnb2*ne2;
  4114. const uint64_t ne = ggml_nelements(tensor);
  4115. if (buf != nullptr) {
  4116. // Memory is pinned, use as staging buffer
  4117. std::vector<vk::BufferCopy> slices;
  4118. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4119. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4120. // Find longest contiguous slice
  4121. if (ne1*nb1 == dstnb2) {
  4122. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  4123. } else {
  4124. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4125. if (ne0*nb0/bs == dstnb1) {
  4126. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  4127. } else {
  4128. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4129. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4130. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4131. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  4132. }
  4133. }
  4134. }
  4135. }
  4136. }
  4137. }
  4138. ggml_vk_sync_buffers(subctx);
  4139. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  4140. return;
  4141. }
  4142. if (!sync_staging) {
  4143. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  4144. }
  4145. // Staging buffer required
  4146. vk_buffer& staging = ctx->device->sync_staging;
  4147. const uint64_t copy_size = ts*ne/bs;
  4148. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  4149. VkBufferCopy buf_copy{ 0, offset, copy_size };
  4150. ggml_vk_sync_buffers(subctx);
  4151. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  4152. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4153. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4154. // Find longest contiguous slice
  4155. if (ne1*nb1 == dstnb2) {
  4156. 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);
  4157. } else {
  4158. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4159. if (ne0*nb0/bs == dstnb1) {
  4160. 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);
  4161. } else {
  4162. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4163. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4164. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4165. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  4166. }
  4167. }
  4168. }
  4169. }
  4170. }
  4171. }
  4172. }
  4173. 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) {
  4174. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  4175. // Buffer is already mapped
  4176. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4177. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4178. GGML_ABORT("fatal error");
  4179. }
  4180. // Check if src is pinned memory
  4181. vk_buffer buf = nullptr;
  4182. size_t buf_offset = 0;
  4183. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  4184. if (buf != nullptr) {
  4185. // Memory is pinned, use as staging buffer
  4186. std::vector<vk::BufferCopy> slices(1);
  4187. if (width == spitch) {
  4188. // Only do single write if stride is equal
  4189. slices[0].srcOffset = buf_offset;
  4190. slices[0].dstOffset = offset;
  4191. slices[0].size = width * height;
  4192. } else {
  4193. slices.resize(height);
  4194. for (size_t i = 0; i < height; i++) {
  4195. slices[i].srcOffset = buf_offset + i * spitch;
  4196. slices[i].dstOffset = offset + i * width;
  4197. slices[i].size = width;
  4198. }
  4199. }
  4200. ggml_vk_sync_buffers(subctx);
  4201. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  4202. return;
  4203. }
  4204. VK_LOG_DEBUG("STAGING");
  4205. if (!sync_staging) {
  4206. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  4207. }
  4208. // Staging buffer required
  4209. const size_t copy_size = width*height;
  4210. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  4211. vk_buffer& staging_buffer = dst->device->sync_staging;
  4212. VkBufferCopy buf_copy = {
  4213. 0,
  4214. offset,
  4215. copy_size};
  4216. ggml_vk_sync_buffers(subctx);
  4217. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  4218. if (width == spitch) {
  4219. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  4220. } else {
  4221. for (size_t i = 0; i < height; i++) {
  4222. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  4223. }
  4224. }
  4225. }
  4226. 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) {
  4227. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  4228. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  4229. }
  4230. 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) {
  4231. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  4232. // Buffer is already mapped
  4233. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4234. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  4235. for (size_t i = 0; i < height; i++) {
  4236. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  4237. }
  4238. } else {
  4239. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  4240. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  4241. ggml_vk_ctx_begin(dst->device, subctx);
  4242. ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  4243. ggml_vk_ctx_end(subctx);
  4244. for (auto& cpy : subctx->in_memcpys) {
  4245. memcpy(cpy.dst, cpy.src, cpy.n);
  4246. }
  4247. ggml_vk_submit(subctx, dst->device->fence);
  4248. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  4249. dst->device->device.resetFences({ dst->device->fence });
  4250. ggml_vk_queue_command_pools_cleanup(dst->device);
  4251. }
  4252. }
  4253. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  4254. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  4255. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  4256. }
  4257. 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) {
  4258. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  4259. GGML_ASSERT(width > 0);
  4260. GGML_ASSERT(height > 0);
  4261. GGML_ASSERT(src != nullptr);
  4262. // TODO: staging_offset is not used
  4263. // Check if dst is pinned memory
  4264. vk_buffer buf = nullptr;
  4265. size_t buf_offset = 0;
  4266. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  4267. std::vector<vk::BufferCopy> slices(1);
  4268. if (width == spitch && width == dpitch) {
  4269. // Only do single write if stride is equal
  4270. slices[0].srcOffset = offset;
  4271. slices[0].dstOffset = buf_offset;
  4272. slices[0].size = width * height;
  4273. } else {
  4274. slices.resize(height);
  4275. for (size_t i = 0; i < height; i++) {
  4276. slices[i].srcOffset = offset + i * spitch;
  4277. slices[i].dstOffset = buf_offset + i * dpitch;
  4278. slices[i].size = width;
  4279. }
  4280. }
  4281. if (buf != nullptr) {
  4282. // Memory is pinned, use as staging buffer
  4283. ggml_vk_sync_buffers(subctx);
  4284. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  4285. return;
  4286. }
  4287. VK_LOG_DEBUG("STAGING");
  4288. if (!sync_staging) {
  4289. GGML_ABORT("Asynchronous read from non-pinned memory not supported");
  4290. }
  4291. // Fall back to staging buffer
  4292. const size_t copy_size = dpitch * height;
  4293. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  4294. vk_buffer& staging_buffer = src->device->sync_staging;
  4295. ggml_vk_sync_buffers(subctx);
  4296. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  4297. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  4298. }
  4299. 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) {
  4300. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  4301. }
  4302. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  4303. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  4304. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  4305. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  4306. // the HW device to host copy path.
  4307. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  4308. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  4309. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  4310. } else {
  4311. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  4312. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  4313. ggml_vk_ctx_begin(src->device, subctx);
  4314. ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  4315. ggml_vk_ctx_end(subctx);
  4316. ggml_vk_submit(subctx, src->device->fence);
  4317. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  4318. src->device->device.resetFences({ src->device->fence });
  4319. ggml_vk_queue_command_pools_cleanup(src->device);
  4320. for (auto& cpy : subctx->out_memcpys) {
  4321. memcpy(cpy.dst, cpy.src, cpy.n);
  4322. }
  4323. }
  4324. }
  4325. 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) {
  4326. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  4327. // Make sure both buffers are on same device
  4328. GGML_ASSERT(src->device == dst->device);
  4329. VkBufferCopy bc{ src_offset, dst_offset, size };
  4330. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  4331. }
  4332. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  4333. if (src->device == dst->device) {
  4334. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  4335. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  4336. // Copy within the device
  4337. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  4338. ggml_vk_ctx_begin(src->device, subctx);
  4339. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  4340. ggml_vk_ctx_end(subctx);
  4341. ggml_vk_submit(subctx, src->device->fence);
  4342. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  4343. src->device->device.resetFences({ src->device->fence });
  4344. ggml_vk_queue_command_pools_cleanup(src->device);
  4345. } else {
  4346. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  4347. // Copy device to device
  4348. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  4349. ggml_vk_ensure_sync_staging_buffer(dst->device, size);
  4350. // Copy to src staging buffer
  4351. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  4352. // memcpy to dst staging buffer
  4353. memcpy(dst->device->sync_staging->ptr, src->device->sync_staging->ptr, size);
  4354. // Copy to dst buffer
  4355. ggml_vk_buffer_copy(dst, dst_offset, dst->device->sync_staging, 0, size);
  4356. }
  4357. }
  4358. static void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  4359. VK_LOG_DEBUG("ggml_vk_buffer_memset_async(" << offset << ", " << c << ", " << size << ")");
  4360. ctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  4361. }
  4362. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  4363. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  4364. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  4365. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  4366. ggml_vk_ctx_begin(dst->device, subctx);
  4367. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  4368. ggml_vk_ctx_end(subctx);
  4369. ggml_vk_submit(subctx, dst->device->fence);
  4370. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  4371. dst->device->device.resetFences({ dst->device->fence });
  4372. ggml_vk_queue_command_pools_cleanup(dst->device);
  4373. }
  4374. static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, uint32_t m, uint32_t n, uint32_t k, const vk_pipeline& pipeline) {
  4375. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ")");
  4376. uint32_t split_k = 1;
  4377. if (ctx->device->shader_core_count != 0 && m >= pipeline->wg_denoms[0] && n >= pipeline->wg_denoms[1]) {
  4378. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  4379. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  4380. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  4381. if (k >= 2048) {
  4382. if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) {
  4383. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  4384. } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) {
  4385. split_k = 3;
  4386. }
  4387. // Cap the split at 8x. Unless k is huge this is a lot of overhead.
  4388. split_k = std::min(split_k, 8u);
  4389. // ggml_vk_matmul will align the splits to be a multiple of 256.
  4390. // If this rounded up size would cause the last split to be empty,
  4391. // then reduce the split count.
  4392. while (true) {
  4393. if (split_k == 1) {
  4394. break;
  4395. }
  4396. uint32_t k_split = CEIL_DIV(k, split_k);
  4397. k_split = ROUNDUP_POW2(k_split, 256);
  4398. if (k_split * (split_k - 1) < k) {
  4399. break;
  4400. }
  4401. split_k--;
  4402. }
  4403. }
  4404. }
  4405. return split_k;
  4406. }
  4407. 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) {
  4408. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  4409. if (ctx->device->coopmat2) {
  4410. const uint32_t shader_core_count = ctx->device->shader_core_count;
  4411. const uint32_t tiles_l = CEIL_DIV(m, mmp->a_l->wg_denoms[0]) * CEIL_DIV(n, mmp->a_l->wg_denoms[1]);
  4412. const uint32_t tiles_m = CEIL_DIV(m, mmp->a_m->wg_denoms[0]) * CEIL_DIV(n, mmp->a_m->wg_denoms[1]);
  4413. // Use large shader when the N dimension is greater than the medium shader's tile size
  4414. uint32_t crossover_large = mmp->m->wg_denoms[1];
  4415. // Prefer large over medium if either:
  4416. // - medium or large tiles would overfill the GPU
  4417. // - large tiles with a split_k==3 fits in the GPU and medium tiles with split_k==2 does not
  4418. // (medium with split_k==2 is probably better if it fits - more workgroups running and less split_k overhead)
  4419. bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count ||
  4420. // split_k==3 with large tiles likely better than medium tiles with no split_k.
  4421. (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2);
  4422. 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])) {
  4423. return aligned ? mmp->a_l : mmp->l;
  4424. }
  4425. // Use medium shader when the N dimension is greater than the small shader's tile size
  4426. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  4427. if ((ctx->device->mul_mat_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_s[src0_type]) {
  4428. return aligned ? mmp->a_m : mmp->m;
  4429. }
  4430. return aligned ? mmp->a_s : mmp->s;
  4431. }
  4432. 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])) {
  4433. return aligned ? mmp->a_s : mmp->s;
  4434. }
  4435. if ((ctx->device->mul_mat_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l[src0_type]) {
  4436. return aligned ? mmp->a_m : mmp->m;
  4437. }
  4438. return aligned ? mmp->a_l : mmp->l;
  4439. GGML_UNUSED(src1_type);
  4440. }
  4441. 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) {
  4442. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  4443. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, src0_type, src1_type)->align;
  4444. }
  4445. static void ggml_vk_matmul(
  4446. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  4447. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  4448. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  4449. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  4450. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3,
  4451. uint32_t padded_n) {
  4452. 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 << ")");
  4453. ggml_vk_sync_buffers(subctx);
  4454. if (split_k == 1) {
  4455. 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 };
  4456. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc, { m, n, batch });
  4457. return;
  4458. }
  4459. GGML_ASSERT(batch_stride_d == m * n);
  4460. // Round the split size up to a multiple of 256 (k-quant alignment)
  4461. uint32_t k_split = CEIL_DIV(k, split_k);
  4462. k_split = ROUNDUP_POW2(k_split, 256);
  4463. 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 };
  4464. // Make sure enough workgroups get assigned for split k to work
  4465. 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 });
  4466. ggml_vk_sync_buffers(subctx);
  4467. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  4468. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 });
  4469. }
  4470. 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) {
  4471. VK_LOG_DEBUG("ggml_vk_guess_matmul_id_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ")");
  4472. if (ctx->device->coopmat2) {
  4473. // Use large shader when the N dimension is greater than the medium shader's tile size
  4474. uint32_t crossover_large = mmp->m->wg_denoms[1];
  4475. 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])) {
  4476. return aligned ? mmp->a_l : mmp->l;
  4477. }
  4478. // Use medium shader when the N dimension is greater than the small shader's tile size
  4479. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  4480. if ((ctx->device->mul_mat_id_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_id_s[src0_type]) {
  4481. return aligned ? mmp->a_m : mmp->m;
  4482. }
  4483. return aligned ? mmp->a_s : mmp->s;
  4484. }
  4485. 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])) {
  4486. return aligned ? mmp->a_s : mmp->s;
  4487. }
  4488. if ((ctx->device->mul_mat_id_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l[src0_type]) {
  4489. return aligned ? mmp->a_m : mmp->m;
  4490. }
  4491. return aligned ? mmp->a_l : mmp->l;
  4492. }
  4493. 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) {
  4494. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ")");
  4495. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true, src0_type)->align;
  4496. }
  4497. static void ggml_vk_matmul_id(
  4498. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  4499. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  4500. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  4501. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  4502. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11,
  4503. uint32_t padded_n) {
  4504. 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 << "), " <<
  4505. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  4506. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  4507. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  4508. ggml_vk_sync_buffers(subctx);
  4509. 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,
  4510. nei0, nei1, nbi1, ne11, padded_n };
  4511. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, pc, { m, nei1, n_as });
  4512. }
  4513. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  4514. return
  4515. tensor->nb[0] == ggml_type_size(tensor->type) &&
  4516. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  4517. (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]);
  4518. }
  4519. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  4520. // Choose "contiguous copy" shader if src/dst are contiguous
  4521. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  4522. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  4523. if (contig) {
  4524. return ctx->device->pipeline_contig_cpy_f32_f32;
  4525. } else {
  4526. return ctx->device->pipeline_cpy_f32_f32;
  4527. }
  4528. }
  4529. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  4530. if (contig) {
  4531. return ctx->device->pipeline_contig_cpy_f32_f16;
  4532. } else {
  4533. return ctx->device->pipeline_cpy_f32_f16;
  4534. }
  4535. }
  4536. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  4537. if (contig) {
  4538. return ctx->device->pipeline_contig_cpy_f16_f16;
  4539. } else {
  4540. return ctx->device->pipeline_cpy_f16_f16;
  4541. }
  4542. }
  4543. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) {
  4544. if (contig) {
  4545. return ctx->device->pipeline_contig_cpy_f16_f32;
  4546. } else {
  4547. return ctx->device->pipeline_cpy_f16_f32;
  4548. }
  4549. }
  4550. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) {
  4551. if (contig) {
  4552. return ctx->device->pipeline_contig_cpy_f32_bf16;
  4553. } else {
  4554. return ctx->device->pipeline_cpy_f32_bf16;
  4555. }
  4556. }
  4557. if (src->type == GGML_TYPE_F32) {
  4558. switch (to) {
  4559. case GGML_TYPE_Q4_0:
  4560. case GGML_TYPE_Q4_1:
  4561. case GGML_TYPE_Q5_0:
  4562. case GGML_TYPE_Q5_1:
  4563. case GGML_TYPE_Q8_0:
  4564. case GGML_TYPE_IQ4_NL:
  4565. return ctx->device->pipeline_cpy_f32_quant[to];
  4566. default:
  4567. break;
  4568. }
  4569. }
  4570. if (to == GGML_TYPE_F32) {
  4571. switch (src->type) {
  4572. case GGML_TYPE_Q4_0:
  4573. case GGML_TYPE_Q4_1:
  4574. case GGML_TYPE_Q5_0:
  4575. case GGML_TYPE_Q5_1:
  4576. case GGML_TYPE_Q8_0:
  4577. case GGML_TYPE_IQ4_NL:
  4578. return ctx->device->pipeline_cpy_quant_f32[src->type];
  4579. default:
  4580. break;
  4581. }
  4582. }
  4583. if (src->type == to) {
  4584. // Copy two or four bytes at a time, depending on block size.
  4585. // For quantized types, we scale by block size/type size. But
  4586. // this path is also used for bf16->bf16 for example, where the
  4587. // type size must be exactly 2 or 4.
  4588. GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4);
  4589. if ((ggml_type_size(src->type) % 4) == 0) {
  4590. if (contig) {
  4591. return ctx->device->pipeline_contig_cpy_f32_f32;
  4592. } else {
  4593. return ctx->device->pipeline_cpy_f32_f32;
  4594. }
  4595. } else {
  4596. if (contig) {
  4597. return ctx->device->pipeline_contig_cpy_f16_f16;
  4598. } else {
  4599. return ctx->device->pipeline_cpy_f16_f16;
  4600. }
  4601. }
  4602. }
  4603. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  4604. GGML_ABORT("fatal error");
  4605. }
  4606. 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) {
  4607. 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] << "), ";
  4608. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  4609. const int tensor_type_size = ggml_type_size(tensor->type);
  4610. const uint32_t ne = ggml_nelements(tensor);
  4611. std::array<uint32_t, 3> elements;
  4612. if (ne > 262144) {
  4613. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  4614. } else if (ne > 512) {
  4615. elements = { 512, CEIL_DIV(ne, 512), 1 };
  4616. } else {
  4617. elements = { ne, 1, 1 };
  4618. }
  4619. vk_op_unary_push_constants pc = {
  4620. (uint32_t)ne,
  4621. (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,
  4622. (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]),
  4623. 0,
  4624. 0.0f, 0.0f,
  4625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  4626. };
  4627. init_pushconst_fastdiv(pc);
  4628. ggml_vk_sync_buffers(subctx);
  4629. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements);
  4630. }
  4631. static vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type) {
  4632. switch(type) {
  4633. case GGML_TYPE_Q8_1:
  4634. return ctx->device->pipeline_quantize_q8_1;
  4635. default:
  4636. std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl;
  4637. GGML_ABORT("fatal error");
  4638. }
  4639. }
  4640. static void ggml_vk_quantize_q8_1(ggml_backend_vk_context * ctx, vk_context& subctx, vk_subbuffer&& in, vk_subbuffer&& out, uint32_t ne) {
  4641. VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")");
  4642. vk_pipeline pipeline = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  4643. ggml_vk_sync_buffers(subctx);
  4644. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, std::array<uint32_t, 1>{ne}, { ne, 1, 1 });
  4645. }
  4646. static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  4647. 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];
  4648. 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];
  4649. 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];
  4650. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  4651. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  4652. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  4653. const uint64_t ne00 = src0->ne[0];
  4654. const uint64_t ne01 = src0->ne[1];
  4655. const uint64_t ne02 = src0->ne[2];
  4656. const uint64_t ne03 = src0->ne[3];
  4657. const uint64_t ne10 = src1->ne[0];
  4658. const uint64_t ne11 = src1->ne[1];
  4659. const uint64_t ne12 = src1->ne[2];
  4660. const uint64_t ne13 = src1->ne[3];
  4661. const uint64_t ne20 = dst->ne[0];
  4662. const uint64_t ne21 = dst->ne[1];
  4663. const uint64_t r2 = ne12 / ne02;
  4664. const uint64_t r3 = ne13 / ne03;
  4665. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  4666. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  4667. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  4668. vk_buffer d_Qx = nullptr;
  4669. size_t qx_buf_offset = 0;
  4670. vk_buffer d_Qy = nullptr;
  4671. size_t qy_buf_offset = 0;
  4672. bool src0_uma = false;
  4673. bool src1_uma = false;
  4674. if (ctx->device->uma) {
  4675. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  4676. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  4677. src0_uma = d_Qx != nullptr;
  4678. src1_uma = d_Qy != nullptr;
  4679. }
  4680. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  4681. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  4682. !ggml_vk_dim01_contiguous(src0);
  4683. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  4684. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  4685. !ggml_vk_dim01_contiguous(src1);
  4686. // If src0 is BF16, try to use a BF16 x BF16 multiply
  4687. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  4688. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  4689. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && (ne11 * ne10) % 4 == 0;
  4690. // Check for mmq first
  4691. 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;
  4692. if (mmp == nullptr) {
  4693. // Fall back to f16 dequant mul mat
  4694. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  4695. quantize_y = false;
  4696. }
  4697. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  4698. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  4699. if (qx_needs_dequant) {
  4700. // Fall back to dequant + f16 mulmat
  4701. 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]);
  4702. }
  4703. // Not implemented
  4704. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  4705. 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)));
  4706. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8;
  4707. 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));
  4708. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  4709. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11;
  4710. const int x_ne = ne01 * ne00;
  4711. const int y_ne = padded_n * ne10;
  4712. const int d_ne = ne11 * ne01;
  4713. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, pipeline);
  4714. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  4715. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  4716. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  4717. 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);
  4718. const uint64_t d_sz = sizeof(float) * d_ne;
  4719. vk_pipeline to_fp16_vk_0 = nullptr;
  4720. vk_pipeline to_fp16_vk_1 = nullptr;
  4721. vk_pipeline to_q8_1 = nullptr;
  4722. if (x_non_contig) {
  4723. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  4724. } else {
  4725. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  4726. }
  4727. if (y_non_contig) {
  4728. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  4729. } else {
  4730. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  4731. }
  4732. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  4733. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  4734. if (quantize_y) {
  4735. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  4736. }
  4737. if (dryrun) {
  4738. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  4739. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  4740. const uint64_t split_k_size = split_k > 1 ? d_sz * ne12 * ne13 * split_k : 0;
  4741. if (
  4742. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  4743. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size) ||
  4744. (split_k > 1 && split_k_size > ctx->device->max_memory_allocation_size)) {
  4745. GGML_ABORT("Requested preallocation size is too large");
  4746. }
  4747. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  4748. ctx->prealloc_size_x = x_sz_upd;
  4749. }
  4750. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz_upd) {
  4751. ctx->prealloc_size_y = y_sz_upd;
  4752. }
  4753. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  4754. ctx->prealloc_size_split_k = split_k_size;
  4755. }
  4756. // Request descriptor sets
  4757. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  4758. if (qx_needs_dequant) {
  4759. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  4760. }
  4761. if (qy_needs_dequant) {
  4762. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  4763. }
  4764. if (quantize_y) {
  4765. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  4766. }
  4767. if (split_k > 1) {
  4768. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  4769. }
  4770. return;
  4771. }
  4772. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  4773. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  4774. GGML_ASSERT(d_D != nullptr);
  4775. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz * ne02 * ne03);
  4776. vk_buffer d_X;
  4777. uint64_t x_buf_offset = 0;
  4778. vk_buffer d_Y;
  4779. uint64_t y_buf_offset = 0;
  4780. if (!src0_uma) {
  4781. d_Qx = src0_buf_ctx->dev_buffer;
  4782. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  4783. GGML_ASSERT(d_Qx != nullptr);
  4784. }
  4785. if (!src1_uma) {
  4786. d_Qy = src1_buf_ctx->dev_buffer;
  4787. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  4788. GGML_ASSERT(d_Qy != nullptr);
  4789. }
  4790. if (qx_needs_dequant) {
  4791. d_X = ctx->prealloc_x;
  4792. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  4793. } else {
  4794. d_X = d_Qx;
  4795. x_buf_offset = qx_buf_offset;
  4796. GGML_ASSERT(qx_sz == x_sz);
  4797. }
  4798. if (qy_needs_dequant) {
  4799. d_Y = ctx->prealloc_y;
  4800. GGML_ASSERT(d_Y->size >= y_sz * ne12 * ne13);
  4801. } else if (quantize_y) {
  4802. d_Y = ctx->prealloc_y;
  4803. GGML_ASSERT(d_Y->size >= y_ne * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1));
  4804. } else {
  4805. d_Y = d_Qy;
  4806. y_buf_offset = qy_buf_offset;
  4807. GGML_ASSERT(qy_sz == y_sz);
  4808. }
  4809. if (x_non_contig) {
  4810. 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 });
  4811. } else if (qx_needs_dequant) {
  4812. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  4813. ggml_vk_sync_buffers(subctx);
  4814. 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});
  4815. }
  4816. if (y_non_contig) {
  4817. 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 });
  4818. }
  4819. if (quantize_y) {
  4820. 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);
  4821. }
  4822. uint32_t stride_batch_x = ne00*ne01;
  4823. uint32_t stride_batch_y = ne10*ne11;
  4824. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  4825. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  4826. }
  4827. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  4828. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  4829. }
  4830. // compute
  4831. ggml_vk_matmul(
  4832. ctx, subctx, pipeline,
  4833. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz * ne12 * ne13 },
  4834. { d_D, d_buf_offset, d_sz * ne12 * ne13 }, { ctx->prealloc_split_k, 0, d_sz * ne12 * ne13 * split_k },
  4835. ne01, ne11, ne10,
  4836. ne10, ne10, ne01, stride_batch_x, stride_batch_y, ne20*ne21,
  4837. split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n
  4838. ); // NOLINT
  4839. }
  4840. 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) {
  4841. 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];
  4842. 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];
  4843. 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];
  4844. std::cerr << "), " << (dryrun ? "dryrun" : "") << "),)");
  4845. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  4846. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  4847. const uint64_t ne00 = src0->ne[0];
  4848. const uint64_t ne01 = src0->ne[1];
  4849. const uint64_t ne02 = src0->ne[2];
  4850. const uint64_t ne03 = src0->ne[3];
  4851. const uint64_t ne10 = src1->ne[0];
  4852. const uint64_t ne11 = src1->ne[1];
  4853. const uint64_t ne12 = src1->ne[2];
  4854. const uint64_t ne13 = src1->ne[3];
  4855. const uint64_t ne20 = dst->ne[0];
  4856. const uint64_t ne21 = dst->ne[1];
  4857. const uint64_t ne22 = dst->ne[2];
  4858. const uint64_t ne23 = dst->ne[3];
  4859. const uint64_t r2 = ne12 / ne02;
  4860. const uint64_t r3 = ne13 / ne03;
  4861. // batch_n indicates that we need to compute a few vector results, and this assumes
  4862. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  4863. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  4864. bool batch_n = ne11 > 1;
  4865. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  4866. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  4867. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  4868. vk_buffer d_Qx = nullptr;
  4869. size_t qx_buf_offset = 0;
  4870. vk_buffer d_Qy = nullptr;
  4871. size_t qy_buf_offset = 0;
  4872. bool src0_uma = false;
  4873. bool src1_uma = false;
  4874. if (ctx->device->uma) {
  4875. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  4876. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  4877. src0_uma = d_Qx != nullptr;
  4878. src1_uma = d_Qy != nullptr;
  4879. }
  4880. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  4881. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  4882. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  4883. const bool qx_needs_dequant = x_non_contig;
  4884. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  4885. // Not implemented
  4886. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  4887. const uint64_t x_ne = ne01 * ne00;
  4888. const uint64_t y_ne = ne11 * ne10;
  4889. const uint64_t d_ne = ne11 * ne01;
  4890. 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);
  4891. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  4892. 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;
  4893. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  4894. const uint64_t d_sz = sizeof(float) * d_ne;
  4895. vk_pipeline to_fp16_vk_0 = nullptr;
  4896. vk_pipeline to_fp16_vk_1 = nullptr;
  4897. if (x_non_contig) {
  4898. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  4899. }
  4900. if (y_non_contig) {
  4901. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  4902. } else {
  4903. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  4904. }
  4905. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11);
  4906. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  4907. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  4908. GGML_ASSERT(dmmv != nullptr);
  4909. if (dryrun) {
  4910. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  4911. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  4912. if (
  4913. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  4914. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  4915. GGML_ABORT("Requested preallocation size is too large");
  4916. }
  4917. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  4918. ctx->prealloc_size_x = x_sz_upd;
  4919. }
  4920. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  4921. ctx->prealloc_size_y = y_sz_upd;
  4922. }
  4923. // Request descriptor sets
  4924. if (qx_needs_dequant) {
  4925. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  4926. }
  4927. if (qy_needs_dequant) {
  4928. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  4929. }
  4930. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  4931. return;
  4932. }
  4933. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  4934. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  4935. GGML_ASSERT(d_D != nullptr);
  4936. vk_buffer d_X;
  4937. uint64_t x_buf_offset = 0;
  4938. vk_buffer d_Y;
  4939. uint64_t y_buf_offset = 0;
  4940. if(!src0_uma) {
  4941. d_Qx = src0_buf_ctx->dev_buffer;
  4942. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  4943. GGML_ASSERT(d_Qx != nullptr);
  4944. }
  4945. if(!src1_uma) {
  4946. d_Qy = src1_buf_ctx->dev_buffer;
  4947. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  4948. GGML_ASSERT(d_Qy != nullptr);
  4949. }
  4950. if (qx_needs_dequant) {
  4951. d_X = ctx->prealloc_x;
  4952. } else {
  4953. d_X = d_Qx;
  4954. x_buf_offset = qx_buf_offset;
  4955. GGML_ASSERT(qx_sz == x_sz);
  4956. }
  4957. if (qy_needs_dequant) {
  4958. d_Y = ctx->prealloc_y;
  4959. } else {
  4960. d_Y = d_Qy;
  4961. y_buf_offset = qy_buf_offset;
  4962. GGML_ASSERT(qy_sz == y_sz);
  4963. }
  4964. if (x_non_contig) {
  4965. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  4966. 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 });
  4967. }
  4968. if (y_non_contig) {
  4969. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  4970. 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 });
  4971. }
  4972. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  4973. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  4974. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  4975. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  4976. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  4977. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  4978. }
  4979. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  4980. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  4981. }
  4982. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  4983. uint32_t groups_x = ne01;
  4984. uint32_t groups_z = 1;
  4985. if (ne01 > max_groups_x) {
  4986. groups_z = 64;
  4987. groups_x = CEIL_DIV(groups_x, groups_z);
  4988. }
  4989. // compute
  4990. const vk_mat_vec_push_constants pc = {
  4991. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  4992. stride_batch_x, stride_batch_y, stride_batch_d,
  4993. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  4994. };
  4995. ggml_vk_sync_buffers(subctx);
  4996. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  4997. { vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 }, vk_subbuffer{ d_Y, y_buf_offset, y_sz * ne12 * ne13 }, vk_subbuffer{ d_D, d_buf_offset, d_sz * ne22 * ne23} },
  4998. pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  4999. }
  5000. 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) {
  5001. 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];
  5002. 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];
  5003. 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];
  5004. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5005. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  5006. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  5007. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  5008. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  5009. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  5010. const uint64_t ne00 = src0->ne[0];
  5011. const uint64_t ne01 = src0->ne[1];
  5012. const uint64_t ne02 = src0->ne[2];
  5013. // const uint64_t ne03 = src0->ne[3];
  5014. const uint64_t ne10 = src1->ne[0];
  5015. const uint64_t ne11 = src1->ne[1];
  5016. const uint64_t ne12 = src1->ne[2];
  5017. // const uint64_t ne13 = src1->ne[3];
  5018. GGML_ASSERT(ne11 == 1);
  5019. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5020. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5021. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5022. vk_buffer d_Qy = nullptr;
  5023. size_t qy_buf_offset = 0;
  5024. bool src1_uma = false;
  5025. if (ctx->device->uma) {
  5026. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5027. src1_uma = d_Qy != nullptr;
  5028. }
  5029. const uint64_t x_ne = ne00 * ne01 * ne02;
  5030. const uint64_t y_ne = ne10 * ne11 * ne12;
  5031. const uint64_t d_ne = ne01 * ne11 * ne12;
  5032. 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);
  5033. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5034. const uint64_t d_sz = sizeof(float) * d_ne;
  5035. // With grouped query attention there are > 1 Q matrices per K, V matrix.
  5036. uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02;
  5037. if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) {
  5038. gqa_ratio = 1;
  5039. }
  5040. if (dryrun) {
  5041. // Request descriptor sets
  5042. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], 1);
  5043. return;
  5044. }
  5045. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5046. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5047. GGML_ASSERT(d_D != nullptr);
  5048. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  5049. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5050. GGML_ASSERT(d_Qx != nullptr);
  5051. if (!src1_uma) {
  5052. d_Qy = src1_buf_ctx->dev_buffer;
  5053. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5054. GGML_ASSERT(d_Qx != nullptr);
  5055. }
  5056. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5057. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  5058. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5059. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  5060. // compute
  5061. 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)) };
  5062. uint32_t workgroups_z = (uint32_t)ne12;
  5063. // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups
  5064. if (gqa_ratio > 1) {
  5065. workgroups_z /= gqa_ratio;
  5066. }
  5067. ggml_vk_sync_buffers(subctx);
  5068. 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 });
  5069. }
  5070. 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) {
  5071. 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];
  5072. 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];
  5073. 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];
  5074. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5075. GGML_ASSERT(!ggml_is_transposed(src0));
  5076. GGML_ASSERT(!ggml_is_transposed(src1));
  5077. GGML_ASSERT(!ggml_is_permuted(src0));
  5078. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  5079. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  5080. const uint64_t ne00 = src0->ne[0];
  5081. const uint64_t ne01 = src0->ne[1];
  5082. const uint64_t ne02 = src0->ne[2];
  5083. const uint64_t ne03 = src0->ne[3];
  5084. const uint64_t nb01 = src0->nb[1];
  5085. const uint64_t nb02 = src0->nb[2];
  5086. const uint64_t nb12 = src1->nb[2];
  5087. // const uint64_t ne10 = src1->ne[0];
  5088. const uint64_t ne11 = src1->ne[1];
  5089. const uint64_t ne12 = src1->ne[2];
  5090. // const uint64_t ne13 = src1->ne[3];
  5091. const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t));
  5092. const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float));
  5093. const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float));
  5094. GGML_ASSERT(ne11 == 1);
  5095. GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in supports_op
  5096. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5097. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5098. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5099. vk_buffer d_Qy = nullptr;
  5100. size_t qy_buf_offset = 0;
  5101. bool src1_uma = false;
  5102. if (ctx->device->uma) {
  5103. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5104. src1_uma = d_Qy != nullptr;
  5105. }
  5106. const uint64_t d_ne = ne01 * ne11 * ne12 * ne03;
  5107. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  5108. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  5109. const uint32_t channel_stride_y = nb12 / sizeof(float);
  5110. const uint64_t qx_sz = ggml_nbytes(src0);
  5111. const uint64_t qy_sz = ggml_nbytes(src1);
  5112. const uint64_t d_sz = sizeof(float) * d_ne;
  5113. if (dryrun) {
  5114. // Request descriptor sets
  5115. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  5116. return;
  5117. }
  5118. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5119. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5120. GGML_ASSERT(d_D != nullptr);
  5121. vk_buffer d_Qx = src0_buf_ctx->dev_buffer;
  5122. const uint64_t qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5123. GGML_ASSERT(d_Qx != nullptr);
  5124. if (!src1_uma) {
  5125. d_Qy = src1_buf_ctx->dev_buffer;
  5126. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5127. GGML_ASSERT(d_Qx != nullptr);
  5128. }
  5129. const uint64_t qy_buffer_offset = (qy_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5130. const uint64_t qy_shader_offset = qy_buf_offset - qy_buffer_offset;
  5131. const uint64_t d_buffer_offset = (d_buf_offset / ctx->device->properties.limits.minStorageBufferOffsetAlignment) * ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  5132. const uint64_t d_shader_offset = d_buf_offset - d_buffer_offset;
  5133. // compute
  5134. 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 };
  5135. ggml_vk_sync_buffers(subctx);
  5136. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  5137. { 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 });
  5138. }
  5139. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  5140. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  5141. if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  5142. // detect 0213 permutation, and batch size of 1
  5143. src0->nb[0] <= src0->nb[2] &&
  5144. src0->nb[2] <= src0->nb[1] &&
  5145. src0->nb[1] <= src0->nb[3] &&
  5146. src1->nb[0] <= src1->nb[2] &&
  5147. src1->nb[2] <= src1->nb[1] &&
  5148. src1->nb[1] <= src1->nb[3] &&
  5149. src0->ne[3] == 1 &&
  5150. src1->ne[3] == 1) {
  5151. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  5152. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  5153. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  5154. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, src0, src1, dst, dryrun);
  5155. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  5156. // when ne12 and ne13 are one.
  5157. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  5158. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
  5159. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, src0, src1, dst, dryrun);
  5160. } else {
  5161. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, dryrun);
  5162. }
  5163. }
  5164. 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) {
  5165. 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];
  5166. 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];
  5167. 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];
  5168. 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] << "),)");
  5169. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5170. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  5171. const uint64_t ne00 = src0->ne[0];
  5172. const uint64_t ne01 = src0->ne[1];
  5173. const uint64_t ne02 = src0->ne[2];
  5174. const uint64_t ne03 = src0->ne[3];
  5175. const uint64_t ne10 = src1->ne[0];
  5176. const uint64_t ne11 = src1->ne[1];
  5177. const uint64_t ne12 = src1->ne[2];
  5178. const uint64_t ne13 = src1->ne[3];
  5179. const uint64_t nei0 = ids->ne[0];
  5180. const uint64_t nei1 = ids->ne[1];
  5181. GGML_ASSERT(nei0 * nei1 <= 4096);
  5182. const uint32_t nbi1 = ids->nb[1];
  5183. const uint32_t nbi2 = ids->nb[2];
  5184. const uint64_t ne20 = dst->ne[0];
  5185. const uint64_t ne21 = dst->ne[1];
  5186. const uint64_t ne22 = dst->ne[2];
  5187. const uint64_t ne23 = dst->ne[3];
  5188. const uint64_t n_as = ne02;
  5189. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5190. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5191. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5192. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  5193. vk_buffer d_Qx = nullptr;
  5194. size_t qx_buf_offset = 0;
  5195. vk_buffer d_Qy = nullptr;
  5196. size_t qy_buf_offset = 0;
  5197. vk_buffer d_ids = nullptr;
  5198. size_t ids_buf_offset = 0;
  5199. bool src0_uma = false;
  5200. bool src1_uma = false;
  5201. bool ids_uma = false;
  5202. if (ctx->device->uma) {
  5203. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5204. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5205. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  5206. src0_uma = d_Qx != nullptr;
  5207. src1_uma = d_Qy != nullptr;
  5208. ids_uma = d_ids != nullptr;
  5209. }
  5210. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5211. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5212. !ggml_vk_dim01_contiguous(src0);
  5213. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5214. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5215. !ggml_vk_dim01_contiguous(src1);
  5216. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5217. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5218. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5219. 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]);
  5220. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5221. const bool qy_needs_dequant = (src1->type != f16_type && !y_f32_kernel) || y_non_contig;
  5222. if (qx_needs_dequant) {
  5223. // Fall back to dequant + f16 mulmat
  5224. 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]);
  5225. }
  5226. // Not implemented
  5227. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5228. 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));
  5229. const bool aligned = ne10 == kpad && ne01 > 8 && nei1 > 8;
  5230. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned, qx_needs_dequant ? f16_type : src0->type);
  5231. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  5232. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) :ne11;
  5233. const uint64_t x_ne = ne01 * ne00;
  5234. const uint64_t y_ne = padded_n * ne10;
  5235. const uint64_t d_ne = ne21 * ne20;
  5236. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  5237. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5238. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  5239. const uint64_t y_sz = y_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  5240. const uint64_t ids_sz = nbi2;
  5241. const uint64_t d_sz = sizeof(float) * d_ne;
  5242. vk_pipeline to_fp16_vk_0 = nullptr;
  5243. vk_pipeline to_fp16_vk_1 = nullptr;
  5244. if (x_non_contig) {
  5245. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  5246. } else {
  5247. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  5248. }
  5249. if (y_non_contig) {
  5250. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  5251. } else {
  5252. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5253. }
  5254. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5255. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5256. if (dryrun) {
  5257. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  5258. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  5259. if (
  5260. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  5261. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  5262. GGML_ABORT("Requested preallocation size is too large");
  5263. }
  5264. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  5265. ctx->prealloc_size_x = x_sz_upd;
  5266. }
  5267. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  5268. ctx->prealloc_size_y = y_sz_upd;
  5269. }
  5270. // Request descriptor sets
  5271. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  5272. if (qx_needs_dequant) {
  5273. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5274. }
  5275. if (qy_needs_dequant) {
  5276. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5277. }
  5278. return;
  5279. }
  5280. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5281. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5282. GGML_ASSERT(d_D != nullptr);
  5283. vk_buffer d_X;
  5284. uint64_t x_buf_offset = 0;
  5285. vk_buffer d_Y;
  5286. uint64_t y_buf_offset = 0;
  5287. if (!src0_uma) {
  5288. d_Qx = src0_buf_ctx->dev_buffer;
  5289. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5290. GGML_ASSERT(d_Qx != nullptr);
  5291. }
  5292. if (!src1_uma) {
  5293. d_Qy = src1_buf_ctx->dev_buffer;
  5294. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5295. GGML_ASSERT(d_Qy != nullptr);
  5296. }
  5297. if (!ids_uma) {
  5298. d_ids = ids_buf_ctx->dev_buffer;
  5299. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  5300. GGML_ASSERT(d_ids != nullptr);
  5301. }
  5302. if (qx_needs_dequant) {
  5303. d_X = ctx->prealloc_x;
  5304. GGML_ASSERT(d_X->size >= x_sz * ne02 * ne03);
  5305. } else {
  5306. d_X = d_Qx;
  5307. x_buf_offset = qx_buf_offset;
  5308. GGML_ASSERT(qx_sz == x_sz);
  5309. }
  5310. if (qy_needs_dequant) {
  5311. d_Y = ctx->prealloc_y;
  5312. GGML_ASSERT(d_Y->size >= y_sz * ne12 * ne13);
  5313. } else {
  5314. d_Y = d_Qy;
  5315. y_buf_offset = qy_buf_offset;
  5316. GGML_ASSERT(qy_sz == y_sz);
  5317. }
  5318. if (x_non_contig) {
  5319. 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 });
  5320. } else if (qx_needs_dequant) {
  5321. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  5322. ggml_vk_sync_buffers(subctx);
  5323. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  5324. { 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});
  5325. }
  5326. if (y_non_contig) {
  5327. 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 });
  5328. }
  5329. uint32_t stride_batch_x = ne00*ne01;
  5330. uint32_t stride_batch_y = ne10*ne11;
  5331. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5332. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5333. }
  5334. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  5335. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5336. }
  5337. // compute
  5338. ggml_vk_matmul_id(
  5339. ctx, subctx, pipeline,
  5340. { d_X, x_buf_offset, x_sz * ne02 * ne03 }, { d_Y, y_buf_offset, y_sz * ne12 * ne13 },
  5341. { d_D, d_buf_offset, d_sz * ne22 * ne23 }, { d_ids, ids_buf_offset, ids_sz },
  5342. ne01, ne21, ne10, ne10, ne10, ne01,
  5343. stride_batch_x, stride_batch_y, ne20*ne21,
  5344. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, padded_n
  5345. ); // NOLINT
  5346. }
  5347. 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) {
  5348. 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];
  5349. 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];
  5350. 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];
  5351. 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];
  5352. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5353. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5354. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5355. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  5356. const uint64_t ne00 = src0->ne[0];
  5357. const uint64_t ne01 = src0->ne[1];
  5358. const uint64_t ne02 = src0->ne[2];
  5359. const uint64_t ne03 = src0->ne[3];
  5360. const uint64_t ne10 = src1->ne[0];
  5361. const uint64_t ne11 = src1->ne[1];
  5362. const uint64_t ne12 = src1->ne[2];
  5363. const uint64_t ne13 = src1->ne[3];
  5364. const uint64_t nei0 = ids->ne[0];
  5365. const uint64_t nei1 = ids->ne[1];
  5366. const uint64_t nbi2 = ids->nb[2];
  5367. GGML_ASSERT(nei1 == 1);
  5368. const uint64_t ne20 = dst->ne[0];
  5369. const uint64_t ne21 = dst->ne[1];
  5370. const uint64_t ne22 = dst->ne[2];
  5371. const uint64_t ne23 = dst->ne[3];
  5372. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5373. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5374. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5375. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  5376. vk_buffer d_Qx = nullptr;
  5377. size_t qx_buf_offset = 0;
  5378. vk_buffer d_Qy = nullptr;
  5379. size_t qy_buf_offset = 0;
  5380. vk_buffer d_ids = nullptr;
  5381. size_t ids_buf_offset = 0;
  5382. bool src0_uma = false;
  5383. bool src1_uma = false;
  5384. bool ids_uma = false;
  5385. if (ctx->device->uma) {
  5386. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5387. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5388. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  5389. src0_uma = d_Qx != nullptr;
  5390. src1_uma = d_Qy != nullptr;
  5391. ids_uma = d_ids != nullptr;
  5392. }
  5393. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  5394. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  5395. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  5396. const bool qx_needs_dequant = x_non_contig;
  5397. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  5398. // Not implemented
  5399. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5400. const uint64_t x_ne = ne01 * ne00;
  5401. const uint64_t y_ne = ne11 * ne10;
  5402. const uint64_t d_ne = ne21 * ne20;
  5403. 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);
  5404. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5405. 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;
  5406. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  5407. const uint64_t ids_sz = nbi2;
  5408. const uint64_t d_sz = sizeof(float) * d_ne;
  5409. vk_pipeline to_fp16_vk_0 = nullptr;
  5410. vk_pipeline to_fp16_vk_1 = nullptr;
  5411. if (x_non_contig) {
  5412. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  5413. }
  5414. if (y_non_contig) {
  5415. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  5416. } else {
  5417. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5418. }
  5419. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type);
  5420. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5421. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5422. GGML_ASSERT(dmmv != nullptr);
  5423. if (dryrun) {
  5424. const uint64_t x_sz_upd = x_sz * ne02 * ne03;
  5425. const uint64_t y_sz_upd = y_sz * ne12 * ne13;
  5426. if (
  5427. (qx_needs_dequant && x_sz_upd > ctx->device->max_memory_allocation_size) ||
  5428. (qy_needs_dequant && y_sz_upd > ctx->device->max_memory_allocation_size)) {
  5429. GGML_ABORT("Requested preallocation size is too large");
  5430. }
  5431. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz_upd) {
  5432. ctx->prealloc_size_x = x_sz_upd;
  5433. }
  5434. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz_upd) {
  5435. ctx->prealloc_size_y = y_sz_upd;
  5436. }
  5437. // Request descriptor sets
  5438. if (qx_needs_dequant) {
  5439. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5440. }
  5441. if (qy_needs_dequant) {
  5442. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5443. }
  5444. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  5445. return;
  5446. }
  5447. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5448. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5449. GGML_ASSERT(d_D != nullptr);
  5450. vk_buffer d_X;
  5451. uint64_t x_buf_offset = 0;
  5452. vk_buffer d_Y;
  5453. uint64_t y_buf_offset = 0;
  5454. if(!src0_uma) {
  5455. d_Qx = src0_buf_ctx->dev_buffer;
  5456. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5457. GGML_ASSERT(d_Qx != nullptr);
  5458. }
  5459. if(!src1_uma) {
  5460. d_Qy = src1_buf_ctx->dev_buffer;
  5461. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5462. GGML_ASSERT(d_Qy != nullptr);
  5463. }
  5464. if(!ids_uma) {
  5465. d_ids = ids_buf_ctx->dev_buffer;
  5466. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  5467. GGML_ASSERT(d_ids != nullptr);
  5468. }
  5469. if (qx_needs_dequant) {
  5470. d_X = ctx->prealloc_x;
  5471. } else {
  5472. d_X = d_Qx;
  5473. x_buf_offset = qx_buf_offset;
  5474. GGML_ASSERT(qx_sz == x_sz);
  5475. }
  5476. if (qy_needs_dequant) {
  5477. d_Y = ctx->prealloc_y;
  5478. } else {
  5479. d_Y = d_Qy;
  5480. y_buf_offset = qy_buf_offset;
  5481. GGML_ASSERT(qy_sz == y_sz);
  5482. }
  5483. if (x_non_contig) {
  5484. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  5485. 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 });
  5486. }
  5487. if (y_non_contig) {
  5488. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  5489. 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 });
  5490. }
  5491. uint32_t stride_batch_y = ne10*ne11;
  5492. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  5493. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5494. }
  5495. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  5496. uint32_t groups_x = ne01;
  5497. uint32_t groups_z = 1;
  5498. if (ne01 > max_groups_x) {
  5499. groups_z = 64;
  5500. groups_x = CEIL_DIV(groups_x, groups_z);
  5501. }
  5502. // compute
  5503. const vk_mat_vec_id_push_constants pc = {
  5504. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  5505. (uint32_t)x_ne, stride_batch_y, (uint32_t)(ne20*ne21),
  5506. (uint32_t)nei0, (uint32_t)ne11,
  5507. };
  5508. ggml_vk_sync_buffers(subctx);
  5509. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  5510. { vk_subbuffer{ d_X, x_buf_offset, x_sz * ne02 * ne03 },
  5511. 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 } },
  5512. pc, { groups_x, (uint32_t)nei0, groups_z });
  5513. }
  5514. 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) {
  5515. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  5516. if (src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type))) {
  5517. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, src0, src1, src2, dst, dryrun);
  5518. } else {
  5519. // Split based on number of ids, to fit in shared memory
  5520. const uint32_t nei0 = (uint32_t)src2->ne[0];
  5521. const uint32_t nei1 = (uint32_t)src2->ne[1];
  5522. GGML_ASSERT(nei0 <= 4096);
  5523. const uint32_t split_size = std::min(nei1, 4096u / nei0);
  5524. ggml_tensor src1_copy = *src1;
  5525. ggml_tensor src2_copy = *src2;
  5526. ggml_tensor dst_copy = *dst;
  5527. for (uint32_t token_start = 0; token_start < nei1; token_start += split_size) {
  5528. const uint32_t n_tokens = std::min(split_size, nei1 - token_start);
  5529. src1_copy.view_offs = src1->view_offs + token_start * src1_copy.nb[2];
  5530. src2_copy.view_offs = src2->view_offs + token_start * src2_copy.nb[1];
  5531. dst_copy.view_offs = dst->view_offs + token_start * dst_copy.nb[2];
  5532. src1_copy.ne[2] = n_tokens;
  5533. src2_copy.ne[1] = n_tokens;
  5534. dst_copy.ne[2] = n_tokens;
  5535. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, &src1_copy, &src2_copy, &dst_copy, dryrun);
  5536. }
  5537. }
  5538. }
  5539. static bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv) {
  5540. // Needs to be kept up to date on shader changes
  5541. GGML_UNUSED(hsv);
  5542. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  5543. const uint32_t Br = get_fa_scalar_num_large_rows(hsv);
  5544. const uint32_t Bc = scalar_flash_attention_Bc;
  5545. const uint32_t tmpsh = wg_size * sizeof(float);
  5546. const uint32_t tmpshv4 = wg_size * 4 * sizeof(float);
  5547. const uint32_t masksh = Bc * Br * sizeof(float);
  5548. const uint32_t Qf = Br * (hsk / 4 + 2) * 4 * sizeof(float);
  5549. const uint32_t total_size = tmpsh + tmpshv4 + masksh + Qf;
  5550. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  5551. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported);
  5552. return supported;
  5553. }
  5554. static bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool f32acc) {
  5555. // Needs to be kept up to date on shader changes
  5556. GGML_UNUSED(hsv);
  5557. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  5558. const uint32_t Br = coopmat1_flash_attention_num_large_rows;
  5559. const uint32_t Bc = scalar_flash_attention_Bc;
  5560. const uint32_t acctype = f32acc ? 4 : 2;
  5561. const uint32_t f16vec4 = 8;
  5562. const uint32_t tmpsh = wg_size * sizeof(float);
  5563. const uint32_t tmpshv4 = wg_size * 4 * acctype;
  5564. const uint32_t Qf = Br * (hsk / 4 + 2) * f16vec4;
  5565. const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br;
  5566. const uint32_t sfsh = Bc * sfshstride * acctype;
  5567. const uint32_t kshstride = hsk / 4 + 2;
  5568. const uint32_t ksh = Bc * kshstride * f16vec4;
  5569. const uint32_t slope = Br * sizeof(float);
  5570. const uint32_t total_size = tmpsh + tmpshv4 + Qf + sfsh + ksh + slope;
  5571. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  5572. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported);
  5573. return supported;
  5574. }
  5575. 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) {
  5576. 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];
  5577. 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];
  5578. 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];
  5579. 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];
  5580. if (sinks) {
  5581. 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];
  5582. }
  5583. std::cerr << "), " << (dryrun ? "dryrun" : "") << ")");
  5584. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  5585. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  5586. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  5587. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  5588. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  5589. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  5590. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  5591. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  5592. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  5593. const uint32_t nem2 = mask ? mask->ne[2] : 0;
  5594. const uint32_t nem3 = mask ? mask->ne[3] : 0;
  5595. const uint32_t HSK = nek0;
  5596. const uint32_t HSV = nev0;
  5597. uint32_t N = neq1;
  5598. const uint32_t KV = nek1;
  5599. GGML_ASSERT(ne0 == HSV);
  5600. GGML_ASSERT(ne2 == N);
  5601. // input tensor rows must be contiguous
  5602. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  5603. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  5604. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  5605. GGML_ASSERT(neq0 == HSK);
  5606. GGML_ASSERT(neq1 == N);
  5607. GGML_ASSERT(nev1 == nek1);
  5608. // dst cannot be transposed or permuted
  5609. GGML_ASSERT(nb0 == sizeof(float));
  5610. GGML_ASSERT(nb0 <= nb1);
  5611. GGML_ASSERT(nb1 <= nb2);
  5612. GGML_ASSERT(nb2 <= nb3);
  5613. assert(dst->type == GGML_TYPE_F32);
  5614. assert(q->type == GGML_TYPE_F32);
  5615. assert(k->type == v->type);
  5616. FaCodePath path = ctx->device->coopmat2 ? FA_COOPMAT2 :
  5617. ctx->device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;
  5618. if (path == FA_COOPMAT1) {
  5619. const bool coopmat_shape_supported = (dst->op_params[3] == GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f32acc) ||
  5620. (dst->op_params[3] != GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f16acc);
  5621. const bool coopmat_shmem_supported = ggml_vk_flash_attn_coopmat_shmem_support(ctx->device, HSK, HSV, dst->op_params[3] == GGML_PREC_F32);
  5622. if (!coopmat_shape_supported || !coopmat_shmem_supported) {
  5623. path = FA_SCALAR;
  5624. }
  5625. }
  5626. uint32_t gqa_ratio = 1;
  5627. uint32_t qk_ratio = neq2 / nek2;
  5628. uint32_t workgroups_x = (uint32_t)neq1;
  5629. uint32_t workgroups_y = (uint32_t)neq2;
  5630. uint32_t workgroups_z = (uint32_t)neq3;
  5631. // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga.
  5632. // For coopmat2 FA, we always use the small size (which is still pretty large for gqa).
  5633. uint32_t max_gqa;
  5634. switch (path) {
  5635. case FA_SCALAR:
  5636. case FA_COOPMAT1:
  5637. // We may switch from coopmat1 to scalar, so use the scalar limit for both
  5638. max_gqa = get_fa_scalar_num_large_rows(HSV);
  5639. break;
  5640. case FA_COOPMAT2:
  5641. max_gqa = get_fa_num_small_rows(FA_COOPMAT2);
  5642. break;
  5643. default:
  5644. GGML_ASSERT(0);
  5645. }
  5646. if (N == 1 && qk_ratio > 1 && qk_ratio <= max_gqa &&
  5647. qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) {
  5648. // grouped query attention - make the N dimension equal to gqa_ratio, reduce
  5649. // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1
  5650. // and change addressing calculations to index Q's dimension 2.
  5651. gqa_ratio = qk_ratio;
  5652. N = gqa_ratio;
  5653. workgroups_y /= N;
  5654. }
  5655. vk_pipeline *pipelines;
  5656. bool small_rows = N <= get_fa_num_small_rows(path);
  5657. // coopmat1 does not actually support "small rows" (it needs 16 rows).
  5658. // So use scalar instead.
  5659. if (small_rows && path == FA_COOPMAT1) {
  5660. path = FA_SCALAR;
  5661. }
  5662. // scalar is faster than coopmat2 when N==1
  5663. if (N == 1 && path == FA_COOPMAT2) {
  5664. path = FA_SCALAR;
  5665. }
  5666. // with large hsk/hsv, scalar path may need to use small_rows to fit in shared memory
  5667. if (path == FA_SCALAR &&
  5668. !ggml_vk_flash_attn_scalar_shmem_support(ctx->device, HSK, HSV)) {
  5669. small_rows = true;
  5670. }
  5671. bool f32acc = path == FA_SCALAR || dst->op_params[3] == GGML_PREC_F32;
  5672. FaHeadSizes head_sizes = fa_get_head_sizes(k->ne[0], v->ne[0]);
  5673. switch (path) {
  5674. case FA_SCALAR:
  5675. pipelines = &ctx->device->pipeline_flash_attn_f32_f16[k->type][head_sizes][f32acc][small_rows][0];
  5676. break;
  5677. case FA_COOPMAT1:
  5678. pipelines = &ctx->device->pipeline_flash_attn_f32_f16_cm1[k->type][head_sizes][f32acc][small_rows][0];
  5679. break;
  5680. case FA_COOPMAT2:
  5681. pipelines = &ctx->device->pipeline_flash_attn_f32_f16_cm2[k->type][head_sizes][f32acc][small_rows][0];
  5682. break;
  5683. default:
  5684. GGML_ASSERT(0);
  5685. }
  5686. assert(pipelines);
  5687. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  5688. const uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  5689. const uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  5690. bool aligned = (KV % pipelines[1]->align) == 0 &&
  5691. // the "aligned" shader variant will forcibly align strides, for performance
  5692. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  5693. // mask dim1 is padded to 64, we rely on this to avoid clamping mask loads
  5694. GGML_ASSERT((nem1 % GGML_KQ_MASK_PAD) == 0);
  5695. vk_pipeline pipeline = pipelines[aligned];
  5696. assert(pipeline);
  5697. uint32_t split_kv = KV;
  5698. uint32_t split_k = 1;
  5699. // Use a placeholder core count if one isn't available. split_k is a big help for perf.
  5700. const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count : 16;
  5701. // Try to use split_k when KV is large enough to be worth the overhead
  5702. if (workgroups_x == 1 && shader_core_count > 0) {
  5703. // Try to run two workgroups per SM.
  5704. split_k = shader_core_count * 2 / (workgroups_y * workgroups_z);
  5705. if (split_k > 1) {
  5706. // Try to evenly split KV into split_k chunks, but it needs to be a multiple
  5707. // of "align", so recompute split_k based on that.
  5708. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), pipelines[1]->align);
  5709. split_k = CEIL_DIV(KV, split_kv);
  5710. workgroups_x = split_k;
  5711. }
  5712. }
  5713. // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1)
  5714. // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows.
  5715. const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne3 : 0;
  5716. if (split_k_size > ctx->device->max_memory_allocation_size) {
  5717. GGML_ABORT("Requested preallocation size is too large");
  5718. }
  5719. if (ctx->prealloc_size_split_k < split_k_size) {
  5720. ctx->prealloc_size_split_k = split_k_size;
  5721. }
  5722. if (dryrun) {
  5723. // Request descriptor sets
  5724. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  5725. if (split_k > 1) {
  5726. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1);
  5727. }
  5728. return;
  5729. }
  5730. float scale = 1.0f;
  5731. float max_bias = 0.0f;
  5732. float logit_softcap = 0.0f;
  5733. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  5734. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  5735. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  5736. if (logit_softcap != 0) {
  5737. scale /= logit_softcap;
  5738. }
  5739. const uint32_t n_head_kv = neq2;
  5740. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  5741. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  5742. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  5743. vk_buffer d_Q = nullptr, d_K = nullptr, d_V = nullptr, d_D = nullptr, d_M = nullptr, d_S = nullptr;
  5744. 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;
  5745. bool Q_uma = false, K_uma = false, V_uma = false, D_uma = false, M_uma = false, S_uma = false;
  5746. if (ctx->device->uma) {
  5747. ggml_vk_host_get(ctx->device, q->data, d_Q, q_buf_offset);
  5748. ggml_vk_host_get(ctx->device, k->data, d_K, k_buf_offset);
  5749. ggml_vk_host_get(ctx->device, v->data, d_V, v_buf_offset);
  5750. ggml_vk_host_get(ctx->device, dst->data, d_D, d_buf_offset);
  5751. Q_uma = d_Q != nullptr;
  5752. K_uma = d_K != nullptr;
  5753. V_uma = d_V != nullptr;
  5754. D_uma = d_D != nullptr;
  5755. if (mask) {
  5756. ggml_vk_host_get(ctx->device, mask->data, d_M, m_buf_offset);
  5757. M_uma = d_M != nullptr;
  5758. }
  5759. if (sinks) {
  5760. ggml_vk_host_get(ctx->device, sinks->data, d_S, s_buf_offset);
  5761. S_uma = d_S != nullptr;
  5762. }
  5763. }
  5764. ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5765. ggml_backend_vk_buffer_context * q_buf_ctx = (ggml_backend_vk_buffer_context *)q->buffer->context;
  5766. ggml_backend_vk_buffer_context * k_buf_ctx = (ggml_backend_vk_buffer_context *)k->buffer->context;
  5767. ggml_backend_vk_buffer_context * v_buf_ctx = (ggml_backend_vk_buffer_context *)v->buffer->context;
  5768. if (!Q_uma) {
  5769. d_Q = q_buf_ctx->dev_buffer;
  5770. q_buf_offset = vk_tensor_offset(q) + q->view_offs;
  5771. }
  5772. if (!K_uma) {
  5773. d_K = k_buf_ctx->dev_buffer;
  5774. k_buf_offset = vk_tensor_offset(k) + k->view_offs;
  5775. }
  5776. if (!V_uma) {
  5777. d_V = v_buf_ctx->dev_buffer;
  5778. v_buf_offset = vk_tensor_offset(v) + v->view_offs;
  5779. }
  5780. if (!D_uma) {
  5781. d_D = d_buf_ctx->dev_buffer;
  5782. d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5783. }
  5784. if (!M_uma) {
  5785. d_M = d_Q;
  5786. m_buf_offset = q_buf_offset;
  5787. if (mask) {
  5788. ggml_backend_vk_buffer_context * m_buf_ctx = (ggml_backend_vk_buffer_context*)mask->buffer->context;
  5789. d_M = m_buf_ctx->dev_buffer;
  5790. m_buf_offset = vk_tensor_offset(mask) + mask->view_offs;
  5791. }
  5792. }
  5793. if (!S_uma) {
  5794. d_S = d_Q;
  5795. s_buf_offset = q_buf_offset;
  5796. if (sinks) {
  5797. ggml_backend_vk_buffer_context * s_buf_ctx = (ggml_backend_vk_buffer_context*)sinks->buffer->context;
  5798. d_S = s_buf_ctx->dev_buffer;
  5799. s_buf_offset = vk_tensor_offset(sinks) + sinks->view_offs;
  5800. }
  5801. }
  5802. uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | ((mask != nullptr) << 16) | n_head_log2;
  5803. const vk_flash_attn_push_constants pc = { N, KV,
  5804. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  5805. (uint32_t)neq2, (uint32_t)neq3,
  5806. (uint32_t)nek2, (uint32_t)nek3,
  5807. (uint32_t)nev2, (uint32_t)nev3,
  5808. nem1, nem2, nem3,
  5809. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  5810. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  5811. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  5812. scale, max_bias, logit_softcap,
  5813. mask_n_head_log2, m0, m1,
  5814. gqa_ratio, split_kv, split_k };
  5815. ggml_vk_sync_buffers(subctx);
  5816. if (split_k > 1) {
  5817. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  5818. {
  5819. vk_subbuffer{d_Q, q_buf_offset, VK_WHOLE_SIZE},
  5820. vk_subbuffer{d_K, k_buf_offset, VK_WHOLE_SIZE},
  5821. vk_subbuffer{d_V, v_buf_offset, VK_WHOLE_SIZE},
  5822. vk_subbuffer{d_M, m_buf_offset, VK_WHOLE_SIZE},
  5823. vk_subbuffer{d_S, s_buf_offset, VK_WHOLE_SIZE},
  5824. vk_subbuffer{ctx->prealloc_split_k, 0, VK_WHOLE_SIZE},
  5825. },
  5826. // We only use split_k when group query attention is enabled, which means
  5827. // there's no more than one tile of rows (i.e. workgroups_x would have been
  5828. // one). We reuse workgroups_x to mean the number of splits, so we need to
  5829. // cancel out the divide by wg_denoms[0].
  5830. pc, { workgroups_x * pipeline->wg_denoms[0], workgroups_y, workgroups_z });
  5831. ggml_vk_sync_buffers(subctx);
  5832. const std::array<uint32_t, 5> pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne3, split_k, (sinks != nullptr) };
  5833. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce,
  5834. {
  5835. vk_subbuffer{ctx->prealloc_split_k, 0, VK_WHOLE_SIZE},
  5836. vk_subbuffer{d_S, s_buf_offset, VK_WHOLE_SIZE},
  5837. vk_subbuffer{d_D, d_buf_offset, VK_WHOLE_SIZE},
  5838. },
  5839. pc2, { (uint32_t)ne1, HSV, (uint32_t)ne3 });
  5840. } else {
  5841. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  5842. {
  5843. vk_subbuffer{d_Q, q_buf_offset, VK_WHOLE_SIZE},
  5844. vk_subbuffer{d_K, k_buf_offset, VK_WHOLE_SIZE},
  5845. vk_subbuffer{d_V, v_buf_offset, VK_WHOLE_SIZE},
  5846. vk_subbuffer{d_M, m_buf_offset, VK_WHOLE_SIZE},
  5847. vk_subbuffer{d_S, s_buf_offset, VK_WHOLE_SIZE},
  5848. vk_subbuffer{d_D, d_buf_offset, VK_WHOLE_SIZE},
  5849. },
  5850. pc, { workgroups_x, workgroups_y, workgroups_z });
  5851. }
  5852. }
  5853. static std::array<uint32_t, 3> ggml_vk_get_conv_elements(const ggml_tensor *dst) {
  5854. const ggml_tensor *src0 = dst->src[0];
  5855. const ggml_tensor *src1 = dst->src[1];
  5856. // src0 - kernel: [KW, KH, Cin, Cout]
  5857. // src1 - input: [W, H, Cin, N]
  5858. // dst - result: [OW, OH, Cout, N]
  5859. // Copied from ggml.c: int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d)
  5860. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  5861. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  5862. };
  5863. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  5864. int64_t W = src1->ne[0];
  5865. int64_t H = src1->ne[1];
  5866. int64_t KW = src0->ne[0];
  5867. int64_t KH = src0->ne[1];
  5868. int64_t Cout = src0->ne[3];
  5869. int64_t N = src1->ne[3];
  5870. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[1], dst->op_params[3], dst->op_params[5]);
  5871. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], dst->op_params[2], dst->op_params[4]);
  5872. int64_t NPQ = N * OW * OH;
  5873. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  5874. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  5875. return elements;
  5876. }
  5877. static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, ggml_op op) {
  5878. switch (op) {
  5879. case GGML_OP_GET_ROWS:
  5880. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  5881. if (dst->type == GGML_TYPE_F16) {
  5882. return ctx->device->pipeline_get_rows[src0->type];
  5883. }
  5884. if (dst->type == GGML_TYPE_F32) {
  5885. return ctx->device->pipeline_get_rows_f32[src0->type];
  5886. }
  5887. return nullptr;
  5888. case GGML_OP_ACC:
  5889. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  5890. return ctx->device->pipeline_acc_f32;
  5891. }
  5892. return nullptr;
  5893. case GGML_OP_ADD:
  5894. case GGML_OP_SUB:
  5895. case GGML_OP_MUL:
  5896. case GGML_OP_DIV:
  5897. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  5898. (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
  5899. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
  5900. return nullptr;
  5901. }
  5902. switch (op) {
  5903. case GGML_OP_ADD:
  5904. {
  5905. if (ctx->num_additional_fused_ops > 0) {
  5906. return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  5907. }
  5908. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add;
  5909. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  5910. }
  5911. case GGML_OP_SUB:
  5912. {
  5913. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub;
  5914. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  5915. }
  5916. case GGML_OP_MUL:
  5917. {
  5918. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul;
  5919. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  5920. }
  5921. case GGML_OP_DIV:
  5922. {
  5923. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div;
  5924. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  5925. }
  5926. default:
  5927. break;
  5928. }
  5929. return nullptr;
  5930. case GGML_OP_ADD_ID:
  5931. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) {
  5932. return ctx->device->pipeline_add_id_f32;
  5933. }
  5934. return nullptr;
  5935. case GGML_OP_CONCAT:
  5936. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  5937. return ctx->device->pipeline_concat_f32;
  5938. }
  5939. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  5940. return ctx->device->pipeline_concat_f16;
  5941. }
  5942. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  5943. return ctx->device->pipeline_concat_i32;
  5944. }
  5945. return nullptr;
  5946. case GGML_OP_UPSCALE:
  5947. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  5948. int mode = ggml_get_op_params_i32(dst, 0);
  5949. switch (mode) {
  5950. case GGML_SCALE_MODE_NEAREST:
  5951. return ctx->device->pipeline_upscale_nearest_f32;
  5952. case GGML_SCALE_MODE_BILINEAR:
  5953. return ctx->device->pipeline_upscale_bilinear_f32;
  5954. case GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ALIGN_CORNERS:
  5955. return ctx->device->pipeline_upscale_bilinear_ac_f32;
  5956. }
  5957. }
  5958. return nullptr;
  5959. case GGML_OP_SCALE:
  5960. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  5961. return ctx->device->pipeline_scale_f32;
  5962. }
  5963. return nullptr;
  5964. case GGML_OP_SQR:
  5965. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  5966. return ctx->device->pipeline_sqr_f32;
  5967. }
  5968. return nullptr;
  5969. case GGML_OP_SIN:
  5970. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  5971. return ctx->device->pipeline_sin_f32;
  5972. }
  5973. return nullptr;
  5974. case GGML_OP_COS:
  5975. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  5976. return ctx->device->pipeline_cos_f32;
  5977. }
  5978. return nullptr;
  5979. case GGML_OP_CLAMP:
  5980. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  5981. return ctx->device->pipeline_clamp_f32;
  5982. }
  5983. return nullptr;
  5984. case GGML_OP_PAD:
  5985. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  5986. return ctx->device->pipeline_pad_f32;
  5987. }
  5988. return nullptr;
  5989. case GGML_OP_ROLL:
  5990. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  5991. return ctx->device->pipeline_roll_f32;
  5992. }
  5993. return nullptr;
  5994. case GGML_OP_REPEAT:
  5995. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  5996. return ctx->device->pipeline_repeat_f32;
  5997. }
  5998. return nullptr;
  5999. case GGML_OP_REPEAT_BACK:
  6000. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6001. return ctx->device->pipeline_repeat_back_f32;
  6002. }
  6003. return nullptr;
  6004. case GGML_OP_CPY:
  6005. case GGML_OP_CONT:
  6006. case GGML_OP_DUP:
  6007. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  6008. case GGML_OP_SET_ROWS:
  6009. return ctx->device->pipeline_set_rows[dst->type];
  6010. case GGML_OP_SILU_BACK:
  6011. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6012. return ctx->device->pipeline_silu_back_f32;
  6013. }
  6014. return nullptr;
  6015. case GGML_OP_NORM:
  6016. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6017. return ctx->device->pipeline_norm_f32;
  6018. }
  6019. return nullptr;
  6020. case GGML_OP_GROUP_NORM:
  6021. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6022. return ctx->device->pipeline_group_norm_f32;
  6023. }
  6024. return nullptr;
  6025. case GGML_OP_RMS_NORM:
  6026. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6027. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32;
  6028. }
  6029. return nullptr;
  6030. case GGML_OP_RMS_NORM_BACK:
  6031. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6032. return ctx->device->pipeline_rms_norm_back_f32;
  6033. }
  6034. return nullptr;
  6035. case GGML_OP_L2_NORM:
  6036. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6037. return ctx->device->pipeline_l2_norm_f32;
  6038. }
  6039. return nullptr;
  6040. case GGML_OP_UNARY:
  6041. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  6042. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  6043. (src0->type != dst->type)) {
  6044. return nullptr;
  6045. }
  6046. switch (ggml_get_unary_op(dst)) {
  6047. case GGML_UNARY_OP_SILU:
  6048. return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16];
  6049. case GGML_UNARY_OP_GELU:
  6050. return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16];
  6051. case GGML_UNARY_OP_GELU_ERF:
  6052. return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16];
  6053. case GGML_UNARY_OP_GELU_QUICK:
  6054. return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16];
  6055. case GGML_UNARY_OP_RELU:
  6056. return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16];
  6057. case GGML_UNARY_OP_TANH:
  6058. return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16];
  6059. case GGML_UNARY_OP_SIGMOID:
  6060. return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16];
  6061. default:
  6062. break;
  6063. }
  6064. return nullptr;
  6065. case GGML_OP_GLU:
  6066. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  6067. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  6068. (src0->type != dst->type)) {
  6069. return nullptr;
  6070. }
  6071. switch (ggml_get_glu_op(dst)) {
  6072. case GGML_GLU_OP_GEGLU:
  6073. return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16];
  6074. case GGML_GLU_OP_REGLU:
  6075. return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16];
  6076. case GGML_GLU_OP_SWIGLU:
  6077. return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16];
  6078. case GGML_GLU_OP_SWIGLU_OAI:
  6079. return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16];
  6080. case GGML_GLU_OP_GEGLU_ERF:
  6081. return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16];
  6082. case GGML_GLU_OP_GEGLU_QUICK:
  6083. return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16];
  6084. default:
  6085. break;
  6086. }
  6087. return nullptr;
  6088. case GGML_OP_DIAG_MASK_INF:
  6089. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6090. return ctx->device->pipeline_diag_mask_inf_f32;
  6091. }
  6092. return nullptr;
  6093. case GGML_OP_SOFT_MAX:
  6094. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  6095. GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32);
  6096. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  6097. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  6098. }
  6099. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  6100. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  6101. }
  6102. return nullptr;
  6103. case GGML_OP_SOFT_MAX_BACK:
  6104. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6105. return ctx->device->pipeline_soft_max_back_f32;
  6106. }
  6107. return nullptr;
  6108. case GGML_OP_ROPE:
  6109. case GGML_OP_ROPE_BACK:
  6110. {
  6111. const int mode = ((const int32_t *) dst->op_params)[2];
  6112. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  6113. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  6114. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  6115. if (is_neox) {
  6116. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6117. return ctx->device->pipeline_rope_neox_f32;
  6118. }
  6119. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6120. return ctx->device->pipeline_rope_neox_f16;
  6121. }
  6122. } else if (is_mrope && !is_vision) {
  6123. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6124. return ctx->device->pipeline_rope_multi_f32;
  6125. }
  6126. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6127. return ctx->device->pipeline_rope_multi_f16;
  6128. }
  6129. } else if (is_vision) {
  6130. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6131. return ctx->device->pipeline_rope_vision_f32;
  6132. }
  6133. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6134. return ctx->device->pipeline_rope_vision_f16;
  6135. }
  6136. } else {
  6137. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6138. return ctx->device->pipeline_rope_norm_f32;
  6139. }
  6140. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6141. return ctx->device->pipeline_rope_norm_f16;
  6142. }
  6143. }
  6144. return nullptr;
  6145. }
  6146. case GGML_OP_ARGSORT:
  6147. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  6148. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  6149. return ctx->device->pipeline_argsort_f32[idx];
  6150. }
  6151. return nullptr;
  6152. case GGML_OP_SUM:
  6153. case GGML_OP_SUM_ROWS:
  6154. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6155. return ctx->device->pipeline_sum_rows_f32;
  6156. }
  6157. return nullptr;
  6158. case GGML_OP_ARGMAX:
  6159. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  6160. return ctx->device->pipeline_argmax_f32;
  6161. }
  6162. return nullptr;
  6163. case GGML_OP_COUNT_EQUAL:
  6164. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) {
  6165. return ctx->device->pipeline_count_equal_i32;
  6166. }
  6167. return nullptr;
  6168. case GGML_OP_IM2COL:
  6169. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6170. return ctx->device->pipeline_im2col_f32;
  6171. }
  6172. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  6173. return ctx->device->pipeline_im2col_f32_f16;
  6174. }
  6175. return nullptr;
  6176. case GGML_OP_TIMESTEP_EMBEDDING:
  6177. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6178. return ctx->device->pipeline_timestep_embedding_f32;
  6179. }
  6180. return nullptr;
  6181. case GGML_OP_CONV_TRANSPOSE_1D:
  6182. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6183. return ctx->device->pipeline_conv_transpose_1d_f32;
  6184. }
  6185. return nullptr;
  6186. case GGML_OP_POOL_2D:
  6187. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6188. return ctx->device->pipeline_pool2d_f32;
  6189. }
  6190. return nullptr;
  6191. case GGML_OP_RWKV_WKV6:
  6192. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6193. return ctx->device->pipeline_rwkv_wkv6_f32;
  6194. }
  6195. return nullptr;
  6196. case GGML_OP_RWKV_WKV7:
  6197. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6198. return ctx->device->pipeline_rwkv_wkv7_f32;
  6199. }
  6200. return nullptr;
  6201. case GGML_OP_OPT_STEP_ADAMW:
  6202. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6203. return ctx->device->pipeline_opt_step_adamw_f32;
  6204. }
  6205. return nullptr;
  6206. case GGML_OP_OPT_STEP_SGD:
  6207. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6208. return ctx->device->pipeline_opt_step_sgd_f32;
  6209. }
  6210. return nullptr;
  6211. case GGML_OP_LEAKY_RELU:
  6212. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6213. return ctx->device->pipeline_leaky_relu_f32;
  6214. }
  6215. return nullptr;
  6216. case GGML_OP_CONV_2D:
  6217. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 &&
  6218. ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst)) {
  6219. auto elements = ggml_vk_get_conv_elements(dst);
  6220. vk_conv_shapes shape;
  6221. uint32_t tiles[CONV_SHAPE_COUNT];
  6222. for (uint32_t i = 0; i < CONV_SHAPE_COUNT; ++i) {
  6223. 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]);
  6224. }
  6225. // We can't query number of shader cores on Intel, use 32 as a placeholder
  6226. // so small convolutions will still choose a smaller tile.
  6227. const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32;
  6228. if (elements[0] > 64 && tiles[CONV_SHAPE_128x128] >= shader_core_count * 2) {
  6229. shape = CONV_SHAPE_128x128;
  6230. } else if (elements[0] <= 32 && tiles[CONV_SHAPE_32x256] >= shader_core_count * 2) {
  6231. shape = CONV_SHAPE_32x256;
  6232. } else {
  6233. shape = CONV_SHAPE_64x32;
  6234. }
  6235. if (src0->type == GGML_TYPE_F32) {
  6236. return ctx->device->pipeline_conv2d_f32[shape];
  6237. } else if (src0->type == GGML_TYPE_F16) {
  6238. return ctx->device->pipeline_conv2d_f16_f32[shape];
  6239. }
  6240. }
  6241. return nullptr;
  6242. case GGML_OP_CONV_2D_DW:
  6243. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6244. if (ggml_is_contiguous(src1)) {
  6245. return ctx->device->pipeline_conv2d_dw_whcn_f32;
  6246. } else if (ggml_is_contiguous_channels(src1)) {
  6247. return ctx->device->pipeline_conv2d_dw_cwhn_f32;
  6248. }
  6249. }
  6250. return nullptr;
  6251. default:
  6252. return nullptr;
  6253. }
  6254. GGML_UNUSED(src2);
  6255. }
  6256. static bool ggml_vk_op_supports_incontiguous(ggml_op op) {
  6257. switch (op) {
  6258. case GGML_OP_CPY:
  6259. case GGML_OP_GET_ROWS:
  6260. case GGML_OP_ADD:
  6261. case GGML_OP_SUB:
  6262. case GGML_OP_MUL:
  6263. case GGML_OP_DIV:
  6264. case GGML_OP_ADD_ID:
  6265. case GGML_OP_CONCAT:
  6266. case GGML_OP_UPSCALE:
  6267. case GGML_OP_SQR:
  6268. case GGML_OP_SIN:
  6269. case GGML_OP_COS:
  6270. case GGML_OP_CLAMP:
  6271. case GGML_OP_PAD:
  6272. case GGML_OP_REPEAT:
  6273. case GGML_OP_REPEAT_BACK:
  6274. case GGML_OP_ROPE:
  6275. case GGML_OP_RMS_NORM:
  6276. case GGML_OP_CONV_2D_DW:
  6277. case GGML_OP_IM2COL:
  6278. case GGML_OP_SET_ROWS:
  6279. return true;
  6280. default:
  6281. return false;
  6282. }
  6283. }
  6284. static uint32_t get_misalign_bytes(ggml_backend_vk_context * ctx, const ggml_tensor * t)
  6285. {
  6286. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  6287. }
  6288. 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) {
  6289. GGML_UNUSED(p);
  6290. GGML_UNUSED(src0);
  6291. GGML_UNUSED(src1);
  6292. GGML_UNUSED(src2);
  6293. GGML_UNUSED(dst);
  6294. static_assert(!std::is_const<T>::value, "unexpected type");
  6295. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  6296. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  6297. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  6298. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  6299. }
  6300. 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) {
  6301. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  6302. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  6303. p.misalign_offsets = (a_offset << 16) | d_offset;
  6304. GGML_UNUSED(src1);
  6305. GGML_UNUSED(src2);
  6306. }
  6307. 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) {
  6308. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  6309. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  6310. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  6311. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  6312. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  6313. GGML_UNUSED(src2);
  6314. }
  6315. 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) {
  6316. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  6317. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  6318. p.a_offset = a_offset;
  6319. p.d_offset = d_offset;
  6320. GGML_UNUSED(src1);
  6321. GGML_UNUSED(src2);
  6322. }
  6323. template<typename PC>
  6324. 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) {
  6325. 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];
  6326. if (src1 != nullptr) {
  6327. 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];
  6328. }
  6329. if (src2 != nullptr) {
  6330. 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];
  6331. }
  6332. 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];
  6333. std::cerr << "), " << ggml_op_name(op) << ", " << (dryrun ? "dryrun" : "") << ")");
  6334. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  6335. GGML_ASSERT(ggml_vk_op_supports_incontiguous(op) || ggml_vk_dim01_contiguous(src0)); // NOLINT
  6336. GGML_ASSERT(dst->buffer != nullptr);
  6337. const uint64_t ne00 = src0->ne[0];
  6338. const uint64_t ne01 = src0->ne[1];
  6339. const uint64_t ne02 = src0->ne[2];
  6340. const uint64_t ne03 = src0->ne[3];
  6341. const uint64_t ne0 = ne00 * ne01;
  6342. const bool use_src1 = src1 != nullptr;
  6343. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  6344. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  6345. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  6346. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  6347. const uint64_t ne1 = ne10 * ne11;
  6348. // const uint64_t nb10 = use_src1 ? src1->nb[0] : 0;
  6349. const bool use_src2 = src2 != nullptr;
  6350. const uint64_t ne20 = use_src2 ? src2->ne[0] : 0;
  6351. const uint64_t ne21 = use_src2 ? src2->ne[1] : 0;
  6352. const uint64_t ne22 = use_src2 ? src2->ne[2] : 0;
  6353. const uint64_t ne23 = use_src2 ? src2->ne[3] : 0;
  6354. const uint64_t ne2 = ne20 * ne21;
  6355. const uint64_t ned0 = dst->ne[0];
  6356. const uint64_t ned1 = dst->ne[1];
  6357. const uint64_t ned2 = dst->ne[2];
  6358. const uint64_t ned3 = dst->ne[3];
  6359. const uint64_t ned = ned0 * ned1;
  6360. init_pushconst_fastdiv(pc);
  6361. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  6362. if (pipeline == nullptr) {
  6363. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  6364. if (src1 != nullptr) {
  6365. std::cerr << " and " << ggml_type_name(src1->type);
  6366. }
  6367. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  6368. GGML_ABORT("fatal error");
  6369. }
  6370. if (dryrun) {
  6371. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6372. return;
  6373. }
  6374. const bool op_supports_incontiguous = ggml_vk_op_supports_incontiguous(op);
  6375. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6376. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6377. ggml_backend_vk_buffer_context * src1_buf_ctx = use_src1 ? (ggml_backend_vk_buffer_context *)src1->buffer->context : nullptr;
  6378. ggml_backend_vk_buffer_context * src2_buf_ctx = use_src2 ? (ggml_backend_vk_buffer_context *)src2->buffer->context : nullptr;
  6379. vk_buffer d_X = nullptr;
  6380. size_t x_buf_offset = 0;
  6381. vk_buffer d_Y = nullptr;
  6382. size_t y_buf_offset = 0;
  6383. vk_buffer d_Z = nullptr;
  6384. size_t z_buf_offset = 0;
  6385. bool src0_uma = false;
  6386. bool src1_uma = false;
  6387. bool src2_uma = false;
  6388. if (ctx->device->uma) {
  6389. ggml_vk_host_get(ctx->device, src0->data, d_X, x_buf_offset);
  6390. src0_uma = d_X != nullptr;
  6391. if (use_src1) {
  6392. ggml_vk_host_get(ctx->device, src1->data, d_Y, y_buf_offset);
  6393. src1_uma = d_Y != nullptr;
  6394. }
  6395. if (use_src2) {
  6396. ggml_vk_host_get(ctx->device, src2->data, d_Z, z_buf_offset);
  6397. src2_uma = d_Z != nullptr;
  6398. }
  6399. }
  6400. uint64_t x_sz = ggml_type_size(src0->type)/ggml_blck_size(src0->type) * ne0;
  6401. uint64_t y_sz = use_src1 ? ggml_type_size(src1->type) * ne1 : 0;
  6402. uint64_t z_sz = use_src2 ? ggml_type_size(src2->type) * ne2 : 0;
  6403. uint64_t d_sz = ggml_type_size(dst->type) * ned;
  6404. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6405. // Workaround for tiny tensor inputs on ROPE
  6406. if (op == GGML_OP_ROPE && use_src1 && y_sz > d_D->size) {
  6407. y_sz = VK_WHOLE_SIZE;
  6408. }
  6409. GGML_ASSERT(d_D != nullptr);
  6410. uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6411. if(!src0_uma) {
  6412. d_X = src0_buf_ctx->dev_buffer;
  6413. x_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6414. GGML_ASSERT(d_X != nullptr);
  6415. }
  6416. if (use_src1 && !src1_uma) {
  6417. d_Y = src1_buf_ctx->dev_buffer;
  6418. y_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6419. GGML_ASSERT(d_Y != nullptr);
  6420. }
  6421. if (use_src2 && !src2_uma) {
  6422. d_Z = src2_buf_ctx->dev_buffer;
  6423. z_buf_offset = vk_tensor_offset(src2) + src2->view_offs;
  6424. GGML_ASSERT(d_Z != nullptr);
  6425. }
  6426. // Compute misalignment offset for descriptors and store it in in push constants, then align the descriptor offsets.
  6427. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, dst);
  6428. x_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  6429. y_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  6430. z_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  6431. d_buf_offset &= ~(ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  6432. if (op_supports_incontiguous) {
  6433. x_sz = ggml_nbytes(src0);
  6434. y_sz = use_src1 ? ggml_nbytes(src1) : 0;
  6435. z_sz = use_src2 ? ggml_nbytes(src2) : 0;
  6436. d_sz = ggml_nbytes(dst);
  6437. if (x_buf_offset + x_sz >= d_X->size) {
  6438. x_sz = VK_WHOLE_SIZE;
  6439. }
  6440. if (use_src1 && y_buf_offset + y_sz >= d_Y->size) {
  6441. y_sz = VK_WHOLE_SIZE;
  6442. }
  6443. if (use_src2 && z_buf_offset + z_sz >= d_Z->size) {
  6444. z_sz = VK_WHOLE_SIZE;
  6445. }
  6446. if (d_buf_offset + d_sz >= d_D->size) {
  6447. d_sz = VK_WHOLE_SIZE;
  6448. }
  6449. }
  6450. std::array<uint32_t, 3> elements;
  6451. // Single call if dimension 2 is contiguous
  6452. GGML_ASSERT(op_supports_incontiguous || (ggml_is_contiguous(src0) && (src1 == nullptr || ggml_is_contiguous(src1))));
  6453. switch (op) {
  6454. case GGML_OP_NORM:
  6455. case GGML_OP_RMS_NORM_BACK:
  6456. case GGML_OP_L2_NORM:
  6457. case GGML_OP_SOFT_MAX:
  6458. case GGML_OP_SOFT_MAX_BACK:
  6459. case GGML_OP_SUM_ROWS:
  6460. case GGML_OP_ARGMAX:
  6461. {
  6462. const uint32_t nr = ggml_nrows(src0);
  6463. if (nr > 262144) {
  6464. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  6465. } else if (nr > 512) {
  6466. elements = { 512, CEIL_DIV(nr, 512), 1 };
  6467. } else {
  6468. elements = { nr, 1, 1 };
  6469. }
  6470. } break;
  6471. case GGML_OP_RMS_NORM:
  6472. elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 };
  6473. break;
  6474. case GGML_OP_SUM:
  6475. // We use GGML_OP_SUM_ROWS with 1 row.
  6476. elements = { 1, 1, 1 };
  6477. break;
  6478. case GGML_OP_GROUP_NORM:
  6479. {
  6480. const uint32_t num_groups = dst->op_params[0];
  6481. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  6482. } break;
  6483. case GGML_OP_DIAG_MASK_INF:
  6484. case GGML_OP_ROPE:
  6485. case GGML_OP_ROPE_BACK:
  6486. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  6487. break;
  6488. case GGML_OP_GET_ROWS:
  6489. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  6490. break;
  6491. case GGML_OP_ARGSORT:
  6492. elements = { (uint32_t)ne00, (uint32_t)ggml_nrows(src0), 1 };
  6493. break;
  6494. case GGML_OP_IM2COL:
  6495. {
  6496. const bool is_2D = dst->op_params[6] == 1;
  6497. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  6498. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  6499. const uint32_t KW = src0->ne[0];
  6500. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  6501. const uint32_t OW = dst->ne[1];
  6502. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  6503. elements = { OW * KW * KH, OH, batch * IC };
  6504. } break;
  6505. case GGML_OP_TIMESTEP_EMBEDDING:
  6506. {
  6507. const uint32_t dim = dst->op_params[0];
  6508. uint32_t half_ceil = (dim + 1) / 2;
  6509. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  6510. } break;
  6511. case GGML_OP_CONV_TRANSPOSE_1D:
  6512. {
  6513. elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1}
  6514. } break;
  6515. case GGML_OP_POOL_2D:
  6516. {
  6517. const uint32_t N = dst->ne[3];
  6518. const uint32_t OC = dst->ne[2];
  6519. const uint32_t OH = dst->ne[1];
  6520. const uint32_t OW = dst->ne[0];
  6521. elements = { N * OC * OH * OW, 1, 1};
  6522. } break;
  6523. case GGML_OP_CONV_2D:
  6524. {
  6525. elements = ggml_vk_get_conv_elements(dst);
  6526. } break;
  6527. case GGML_OP_ADD:
  6528. case GGML_OP_SUB:
  6529. case GGML_OP_DIV:
  6530. case GGML_OP_MUL:
  6531. case GGML_OP_SCALE:
  6532. case GGML_OP_SQR:
  6533. case GGML_OP_SIN:
  6534. case GGML_OP_COS:
  6535. case GGML_OP_CLAMP:
  6536. case GGML_OP_PAD:
  6537. case GGML_OP_ROLL:
  6538. case GGML_OP_REPEAT:
  6539. case GGML_OP_REPEAT_BACK:
  6540. case GGML_OP_CPY:
  6541. case GGML_OP_CONCAT:
  6542. case GGML_OP_UPSCALE:
  6543. case GGML_OP_UNARY:
  6544. case GGML_OP_GLU:
  6545. case GGML_OP_CONV_2D_DW:
  6546. {
  6547. uint32_t ne = ggml_nelements(dst);
  6548. if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  6549. // Convert from number of logical elements to 2- or 4-byte units.
  6550. ne /= ggml_blck_size(src0->type);
  6551. if ((ggml_type_size(src0->type) % 4) == 0) {
  6552. ne *= ggml_type_size(src0->type) / 4;
  6553. } else {
  6554. ne *= ggml_type_size(src0->type) / 2;
  6555. }
  6556. }
  6557. // copy_to_quant has block size of 32, and each thread does QUANT_K elements.
  6558. // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements.
  6559. // So divide by block size here before splitting into 512x512 groups.
  6560. if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  6561. ne = CEIL_DIV(ne, ggml_blck_size(dst->type));
  6562. }
  6563. if (ne > 262144) {
  6564. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  6565. } else if (ne > 512) {
  6566. elements = { 512, CEIL_DIV(ne, 512), 1 };
  6567. } else {
  6568. elements = { ne, 1, 1 };
  6569. }
  6570. } break;
  6571. case GGML_OP_ADD_ID:
  6572. {
  6573. elements = { (uint32_t)ne01, (uint32_t)ne02, 1 };
  6574. } break;
  6575. case GGML_OP_SET_ROWS:
  6576. {
  6577. uint32_t ne = ggml_nelements(src0);
  6578. if (ggml_is_quantized(dst->type)) {
  6579. // quants run 32 threads each doing QUANT_K elements
  6580. ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type));
  6581. } else {
  6582. // scalar types do one element per thread, running 512 threads
  6583. ne = CEIL_DIV(ne, 512);
  6584. }
  6585. if (ne > 262144) {
  6586. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  6587. } else if (ne > 512) {
  6588. elements = { 512, CEIL_DIV(ne, 512), 1 };
  6589. } else {
  6590. elements = { ne, 1, 1 };
  6591. }
  6592. }
  6593. break;
  6594. default:
  6595. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  6596. break;
  6597. }
  6598. if (!op_supports_incontiguous) {
  6599. if (x_sz != VK_WHOLE_SIZE) {
  6600. x_sz *= ne02 * ne03;
  6601. }
  6602. if (use_src1 && y_sz != VK_WHOLE_SIZE) {
  6603. y_sz *= ne12 * ne13;
  6604. }
  6605. if (use_src2 && z_sz != VK_WHOLE_SIZE) {
  6606. z_sz *= ne22 * ne23;
  6607. }
  6608. if (d_sz != VK_WHOLE_SIZE) {
  6609. d_sz *= ned2 * ned3;
  6610. }
  6611. }
  6612. if (op == GGML_OP_GLU) {
  6613. // Empty src1 is possible in glu, but the shader needs a buffer
  6614. vk_subbuffer subbuf_y;
  6615. if (use_src1) {
  6616. subbuf_y = { d_Y, y_buf_offset, y_sz };
  6617. } else {
  6618. subbuf_y = { d_X, 0, x_sz };
  6619. }
  6620. ggml_vk_sync_buffers(subctx);
  6621. 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);
  6622. } else if (op == GGML_OP_SOFT_MAX) {
  6623. // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer
  6624. vk_subbuffer subbuf_y;
  6625. if (use_src1) {
  6626. subbuf_y = { d_Y, y_buf_offset, y_sz };
  6627. } else {
  6628. subbuf_y = { d_X, 0, x_sz };
  6629. }
  6630. vk_subbuffer subbuf_z;
  6631. if (use_src2) {
  6632. subbuf_z = { d_Z, z_buf_offset, z_sz };
  6633. } else {
  6634. subbuf_z = { d_X, 0, x_sz };
  6635. }
  6636. ggml_vk_sync_buffers(subctx);
  6637. 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);
  6638. } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) {
  6639. // Empty src2 is possible in rope, but the shader needs a buffer
  6640. vk_subbuffer subbuf_z;
  6641. if (use_src2) {
  6642. subbuf_z = { d_Z, z_buf_offset, z_sz };
  6643. } else {
  6644. subbuf_z = { d_X, 0, x_sz };
  6645. }
  6646. ggml_vk_sync_buffers(subctx);
  6647. 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);
  6648. } else if (op == GGML_OP_IM2COL) {
  6649. // im2col uses only src1 and dst buffers
  6650. ggml_vk_sync_buffers(subctx);
  6651. 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);
  6652. } else if (op == GGML_OP_COUNT_EQUAL) {
  6653. ggml_vk_sync_buffers(subctx);
  6654. // count_equal assumes that destination buffer is initialized with zeroes
  6655. ggml_vk_buffer_memset_async(subctx, d_D, d_buf_offset, 0, d_sz);
  6656. ggml_vk_sync_buffers(subctx);
  6657. 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);
  6658. } else if (op == GGML_OP_OPT_STEP_SGD) {
  6659. // OPT_STEP_SGD works on src0, it does not need dst
  6660. ggml_vk_sync_buffers(subctx);
  6661. 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);
  6662. } else if (use_src2) {
  6663. ggml_vk_sync_buffers(subctx);
  6664. 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);
  6665. } else if (use_src1) {
  6666. ggml_vk_sync_buffers(subctx);
  6667. 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);
  6668. } else {
  6669. ggml_vk_sync_buffers(subctx);
  6670. 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);
  6671. }
  6672. }
  6673. 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) {
  6674. const uint32_t src0_type_size = ggml_type_size(src0->type);
  6675. const uint32_t src1_type_size = ggml_type_size(src1->type);
  6676. const uint32_t dst_type_size = ggml_type_size(dst->type);
  6677. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_GET_ROWS, {
  6678. (uint32_t)ggml_nelements(src0),
  6679. (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,
  6680. (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,
  6681. (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,
  6682. 0,
  6683. 0.0f, 0.0f, 0,
  6684. }, dryrun);
  6685. }
  6686. 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) {
  6687. const uint32_t src0_type_size = ggml_type_size(src0->type);
  6688. const uint32_t src1_type_size = ggml_type_size(src1->type);
  6689. const uint32_t dst_type_size = ggml_type_size(dst->type);
  6690. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  6691. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  6692. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  6693. int offset = dst->op_params[3] / 4; // offset in bytes
  6694. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ACC, {
  6695. (uint32_t)ggml_nelements(src0),
  6696. (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,
  6697. (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,
  6698. (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,
  6699. 0,
  6700. 0.0f, 0.0f, offset,
  6701. }, dryrun);
  6702. }
  6703. static void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx, bool dryrun = false) {
  6704. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  6705. const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  6706. // Make a list of all the tensors used by the op.
  6707. // Last element of the list is the dest tensor.
  6708. const ggml_tensor *tensors[MAX_PARAMETER_COUNT];
  6709. uint32_t num_srcs = ctx->num_additional_fused_ops + 2;
  6710. uint32_t num_tensors = num_srcs + 1;
  6711. GGML_ASSERT(num_tensors <= MAX_PARAMETER_COUNT);
  6712. tensors[0] = first_node->src[0];
  6713. tensors[1] = first_node->src[1];
  6714. for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) {
  6715. // check whether the previous result is src[0] or src[1]
  6716. if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) {
  6717. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1];
  6718. } else {
  6719. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0];
  6720. }
  6721. }
  6722. tensors[num_srcs] = dst;
  6723. vk_op_multi_add_push_constants pc;
  6724. pc.ne20 = (uint32_t)dst->ne[0];
  6725. pc.ne21 = (uint32_t)dst->ne[1];
  6726. pc.ne22 = (uint32_t)dst->ne[2];
  6727. pc.ne23 = (uint32_t)dst->ne[3];
  6728. for (uint32_t i = 0; i < num_tensors; ++i) {
  6729. const ggml_tensor *t = tensors[i];
  6730. pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float);
  6731. pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float);
  6732. pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float);
  6733. pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float);
  6734. }
  6735. vk_pipeline pipeline = ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  6736. if (pipeline == nullptr) {
  6737. std::cerr << "ggml_vulkan: Error: Missing multi_add";
  6738. GGML_ABORT("fatal error");
  6739. }
  6740. if (dryrun) {
  6741. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6742. return;
  6743. }
  6744. ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT];
  6745. vk_buffer buf[MAX_PARAMETER_COUNT];
  6746. size_t offset[MAX_PARAMETER_COUNT];
  6747. bool uma[MAX_PARAMETER_COUNT];
  6748. for (uint32_t i = 0; i < num_tensors; ++i) {
  6749. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  6750. buf[i] = nullptr;
  6751. offset[i] = 0;
  6752. uma[i] = false;
  6753. if (ctx->device->uma) {
  6754. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  6755. uma[i] = buf[i] != nullptr;
  6756. }
  6757. if (!uma[i]) {
  6758. buf[i] = buf_ctx[i]->dev_buffer;
  6759. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  6760. }
  6761. GGML_ASSERT(buf[i] != nullptr);
  6762. }
  6763. // If any remaining descriptors are unused, just point them at src[0]
  6764. for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) {
  6765. buf[i] = buf[0];
  6766. offset[i] = 0;
  6767. }
  6768. std::array<uint32_t, 3> elements;
  6769. uint32_t ne = ggml_nelements(dst);
  6770. if (ne > 262144) {
  6771. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  6772. } else if (ne > 512) {
  6773. elements = { 512, CEIL_DIV(ne, 512), 1 };
  6774. } else {
  6775. elements = { ne, 1, 1 };
  6776. }
  6777. ggml_vk_sync_buffers(subctx);
  6778. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6779. {
  6780. vk_subbuffer{ buf[0], offset[0], VK_WHOLE_SIZE },
  6781. vk_subbuffer{ buf[1], offset[1], VK_WHOLE_SIZE },
  6782. vk_subbuffer{ buf[2], offset[2], VK_WHOLE_SIZE },
  6783. vk_subbuffer{ buf[3], offset[3], VK_WHOLE_SIZE },
  6784. vk_subbuffer{ buf[4], offset[4], VK_WHOLE_SIZE },
  6785. vk_subbuffer{ buf[5], offset[5], VK_WHOLE_SIZE },
  6786. vk_subbuffer{ buf[6], offset[6], VK_WHOLE_SIZE },
  6787. vk_subbuffer{ buf[7], offset[7], VK_WHOLE_SIZE },
  6788. }, pc, elements);
  6789. }
  6790. 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) {
  6791. const uint32_t src0_type_size = ggml_type_size(src0->type);
  6792. const uint32_t src1_type_size = ggml_type_size(src1->type);
  6793. const uint32_t dst_type_size = ggml_type_size(dst->type);
  6794. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_ADD, {
  6795. (uint32_t)ggml_nelements(src0),
  6796. (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,
  6797. (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,
  6798. (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,
  6799. 0,
  6800. 0.0f, 0.0f, 0,
  6801. }, dryrun);
  6802. }
  6803. 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) {
  6804. const uint32_t src0_type_size = ggml_type_size(src0->type);
  6805. const uint32_t src1_type_size = ggml_type_size(src1->type);
  6806. const uint32_t dst_type_size = ggml_type_size(dst->type);
  6807. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_SUB, {
  6808. (uint32_t)ggml_nelements(src0),
  6809. (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,
  6810. (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,
  6811. (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,
  6812. 0,
  6813. 0.0f, 0.0f, 0,
  6814. }, dryrun);
  6815. }
  6816. 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) {
  6817. const uint32_t src0_type_size = ggml_type_size(src0->type);
  6818. const uint32_t src1_type_size = ggml_type_size(src1->type);
  6819. const uint32_t dst_type_size = ggml_type_size(dst->type);
  6820. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_MUL, {
  6821. (uint32_t)ggml_nelements(src0),
  6822. (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,
  6823. (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,
  6824. (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,
  6825. 0,
  6826. 0.0f, 0.0f, 0,
  6827. }, dryrun);
  6828. }
  6829. 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) {
  6830. const uint32_t src0_type_size = ggml_type_size(src0->type);
  6831. const uint32_t src1_type_size = ggml_type_size(src1->type);
  6832. const uint32_t dst_type_size = ggml_type_size(dst->type);
  6833. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_DIV, {
  6834. (uint32_t)ggml_nelements(src0),
  6835. (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,
  6836. (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,
  6837. (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,
  6838. 0,
  6839. 0.0f, 0.0f, 0,
  6840. }, dryrun);
  6841. }
  6842. 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) {
  6843. const uint32_t src0_type_size = ggml_type_size(src0->type);
  6844. const uint32_t src1_type_size = ggml_type_size(src1->type);
  6845. const uint32_t src2_type_size = ggml_type_size(src2->type);
  6846. ggml_vk_op_f32<vk_op_add_id_push_constants>(ctx, subctx, src0, src1, src2, dst, GGML_OP_ADD_ID, {
  6847. (uint32_t)dst->ne[0],
  6848. (uint32_t)dst->ne[1],
  6849. (uint32_t)src0->nb[1] / src0_type_size,
  6850. (uint32_t)src0->nb[2] / src0_type_size,
  6851. (uint32_t)src1->nb[1] / src1_type_size,
  6852. (uint32_t)src2->nb[1] / src2_type_size,
  6853. }, dryrun);
  6854. }
  6855. 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) {
  6856. GGML_ASSERT(version == 6 || version == 7);
  6857. int num_srcs = version == 6 ? 6 : 7;
  6858. for (int i = 0; i < num_srcs; i++) {
  6859. GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type));
  6860. }
  6861. GGML_ASSERT(dst->buffer != nullptr);
  6862. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op);
  6863. GGML_ASSERT(pipeline != nullptr);
  6864. if (dryrun) {
  6865. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6866. return;
  6867. }
  6868. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6869. ggml_backend_vk_buffer_context * src_buf_ctxs[7] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
  6870. for (int i = 0; i < num_srcs; i++) {
  6871. src_buf_ctxs[i] = (ggml_backend_vk_buffer_context *)dst->src[i]->buffer->context;
  6872. }
  6873. ggml_vk_sync_buffers(subctx);
  6874. vk_buffer d_D = nullptr, d_srcs[7] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr };
  6875. size_t dst_offset = 0, src_offsets[7] = { 0, 0, 0, 0, 0, 0, 0 };
  6876. bool dst_uma = false, srcs_uma[7] = { false, false, false, false, false, false, false };
  6877. if (ctx->device->uma) {
  6878. for (int i = 0; i < num_srcs; i++) {
  6879. ggml_vk_host_get(ctx->device, dst->src[i]->data, d_srcs[i], src_offsets[i]);
  6880. srcs_uma[i] = d_srcs[i] != nullptr;
  6881. }
  6882. ggml_vk_host_get(ctx->device, dst->data, d_D, dst_offset);
  6883. dst_uma = d_D != nullptr;
  6884. }
  6885. uint64_t src_sizes[7] = { 0, 0, 0, 0, 0, 0, 0 };
  6886. for (int i = 0; i < num_srcs; i++) {
  6887. src_sizes[i] = ggml_nbytes(dst->src[i]);
  6888. if (!srcs_uma[i]) {
  6889. d_srcs[i] = src_buf_ctxs[i]->dev_buffer;
  6890. src_offsets[i] = vk_tensor_offset(dst->src[i]) + dst->src[i]->view_offs;
  6891. }
  6892. }
  6893. const uint64_t dst_size = ggml_nbytes(dst);
  6894. if (!dst_uma) {
  6895. d_D = dst_buf_ctx->dev_buffer;
  6896. dst_offset = vk_tensor_offset(dst) + dst->view_offs;
  6897. }
  6898. std::array<uint32_t, 3> elements = {
  6899. (uint32_t)(pc.B * pc.H),
  6900. 1,
  6901. 1
  6902. };
  6903. if (version == 6) {
  6904. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  6905. vk_subbuffer{ d_srcs[0], src_offsets[0], src_sizes[0] },
  6906. vk_subbuffer{ d_srcs[1], src_offsets[1], src_sizes[1] },
  6907. vk_subbuffer{ d_srcs[2], src_offsets[2], src_sizes[2] },
  6908. vk_subbuffer{ d_srcs[3], src_offsets[3], src_sizes[3] },
  6909. vk_subbuffer{ d_srcs[4], src_offsets[4], src_sizes[4] },
  6910. vk_subbuffer{ d_srcs[5], src_offsets[5], src_sizes[5] },
  6911. vk_subbuffer{ d_D, dst_offset, dst_size }
  6912. }, pc, elements);
  6913. } else if (version == 7) {
  6914. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  6915. vk_subbuffer{ d_srcs[0], src_offsets[0], src_sizes[0] },
  6916. vk_subbuffer{ d_srcs[1], src_offsets[1], src_sizes[1] },
  6917. vk_subbuffer{ d_srcs[2], src_offsets[2], src_sizes[2] },
  6918. vk_subbuffer{ d_srcs[3], src_offsets[3], src_sizes[3] },
  6919. vk_subbuffer{ d_srcs[4], src_offsets[4], src_sizes[4] },
  6920. vk_subbuffer{ d_srcs[5], src_offsets[5], src_sizes[5] },
  6921. vk_subbuffer{ d_srcs[6], src_offsets[6], src_sizes[6] },
  6922. vk_subbuffer{ d_D, dst_offset, dst_size }
  6923. }, pc, elements);
  6924. } else {
  6925. // shouldn't happen
  6926. GGML_ASSERT(false);
  6927. }
  6928. }
  6929. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  6930. const size_t seq_length = dst->src[0]->ne[2];
  6931. const size_t n_embed = dst->ne[0];
  6932. const size_t n_heads = dst->src[0]->ne[1];
  6933. const size_t n_seqs = dst->src[5]->ne[1];
  6934. ggml_vk_op_f32_wkv(
  6935. ctx, subctx, dst,
  6936. {
  6937. (uint32_t)n_seqs,
  6938. (uint32_t)seq_length,
  6939. (uint32_t)n_embed,
  6940. (uint32_t)n_heads,
  6941. },
  6942. 6,
  6943. dryrun
  6944. );
  6945. }
  6946. static void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  6947. const size_t seq_length = dst->src[0]->ne[2];
  6948. const size_t n_embed = dst->ne[0];
  6949. const size_t n_heads = dst->src[0]->ne[1];
  6950. const size_t n_seqs = dst->src[6]->ne[1];
  6951. ggml_vk_op_f32_wkv(
  6952. ctx, subctx, dst,
  6953. {
  6954. (uint32_t)n_seqs,
  6955. (uint32_t)seq_length,
  6956. (uint32_t)n_embed,
  6957. (uint32_t)n_heads,
  6958. },
  6959. 7,
  6960. dryrun
  6961. );
  6962. }
  6963. 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) {
  6964. const ggml_tensor * x = dst->src[0];
  6965. const ggml_tensor * g = dst->src[1];
  6966. const ggml_tensor * gm = dst->src[2];
  6967. const ggml_tensor * gv = dst->src[3];
  6968. const ggml_tensor * p = dst->src[4];
  6969. GGML_ASSERT(x->type == GGML_TYPE_F32);
  6970. GGML_ASSERT(g->type == GGML_TYPE_F32);
  6971. GGML_ASSERT(gm->type == GGML_TYPE_F32);
  6972. GGML_ASSERT(gv->type == GGML_TYPE_F32);
  6973. GGML_ASSERT(p->type == GGML_TYPE_F32);
  6974. GGML_ASSERT(dst->buffer != nullptr);
  6975. GGML_ASSERT(ggml_is_contiguous(x));
  6976. GGML_ASSERT(ggml_is_contiguous(g));
  6977. GGML_ASSERT(ggml_is_contiguous(gm));
  6978. GGML_ASSERT(ggml_is_contiguous(gv));
  6979. GGML_ASSERT(ggml_is_contiguous(p));
  6980. GGML_ASSERT(ggml_are_same_shape(x, g));
  6981. GGML_ASSERT(ggml_are_same_shape(x, gm));
  6982. GGML_ASSERT(ggml_are_same_shape(x, gv));
  6983. GGML_ASSERT(ggml_nelements(p) == 7);
  6984. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW);
  6985. GGML_ASSERT(pipeline != nullptr);
  6986. if (dryrun) {
  6987. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6988. return;
  6989. }
  6990. ggml_backend_vk_buffer_context * x_buf_ctx = (ggml_backend_vk_buffer_context *)x->buffer->context;
  6991. ggml_backend_vk_buffer_context * g_buf_ctx = (ggml_backend_vk_buffer_context *)g->buffer->context;
  6992. ggml_backend_vk_buffer_context * gm_buf_ctx = (ggml_backend_vk_buffer_context *)gm->buffer->context;
  6993. ggml_backend_vk_buffer_context * gv_buf_ctx = (ggml_backend_vk_buffer_context *)gv->buffer->context;
  6994. ggml_backend_vk_buffer_context * p_buf_ctx = (ggml_backend_vk_buffer_context *)p->buffer->context;
  6995. ggml_vk_sync_buffers(subctx);
  6996. vk_buffer d_X = nullptr, d_G = nullptr, d_GM = nullptr, d_GV = nullptr, d_P = nullptr;
  6997. size_t x_offset = 0, g_offset = 0, gm_offset = 0, gv_offset = 0, p_offset = 0;
  6998. bool X_uma = false, G_uma = false, GM_uma = false, GV_uma = false, P_uma = false;
  6999. if (ctx->device->uma) {
  7000. ggml_vk_host_get(ctx->device, x->data, d_X, x_offset);
  7001. ggml_vk_host_get(ctx->device, g->data, d_G, g_offset);
  7002. ggml_vk_host_get(ctx->device, gm->data, d_GM, gm_offset);
  7003. ggml_vk_host_get(ctx->device, gv->data, d_GV, gv_offset);
  7004. ggml_vk_host_get(ctx->device, p->data, d_P, p_offset);
  7005. X_uma = d_X != nullptr;
  7006. G_uma = d_G != nullptr;
  7007. GM_uma = d_GM != nullptr;
  7008. GV_uma = d_GV != nullptr;
  7009. P_uma = d_P != nullptr;
  7010. }
  7011. if (!X_uma) {
  7012. d_X = x_buf_ctx->dev_buffer;
  7013. x_offset = vk_tensor_offset(x) + x->view_offs;
  7014. }
  7015. if (!G_uma) {
  7016. d_G = g_buf_ctx->dev_buffer;
  7017. g_offset = vk_tensor_offset(g) + g->view_offs;
  7018. }
  7019. if (!GM_uma) {
  7020. d_GM = gm_buf_ctx->dev_buffer;
  7021. gm_offset = vk_tensor_offset(gm) + gm->view_offs;
  7022. }
  7023. if (!GV_uma) {
  7024. d_GV = gv_buf_ctx->dev_buffer;
  7025. gv_offset = vk_tensor_offset(gv) + gv->view_offs;
  7026. }
  7027. if (!P_uma) {
  7028. d_P = p_buf_ctx->dev_buffer;
  7029. p_offset = vk_tensor_offset(p) + p->view_offs;
  7030. }
  7031. const uint64_t x_size = ggml_nbytes(x);
  7032. const uint64_t g_size = ggml_nbytes(g);
  7033. const uint64_t gm_size = ggml_nbytes(gm);
  7034. const uint64_t gv_size = ggml_nbytes(gv);
  7035. const uint64_t p_size = ggml_nbytes(p);
  7036. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(x), 1, 1 };
  7037. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {
  7038. vk_subbuffer{ d_X, x_offset, x_size },
  7039. vk_subbuffer{ d_G, g_offset, g_size },
  7040. vk_subbuffer{ d_GM, gm_offset, gm_size },
  7041. vk_subbuffer{ d_GV, gv_offset, gv_size },
  7042. vk_subbuffer{ d_P, p_offset, p_size },
  7043. }, pc, elements);
  7044. }
  7045. static void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst, bool dryrun = false) {
  7046. const size_t n = ggml_nelements(dst->src[0]);
  7047. ggml_vk_op_f32_opt_step_adamw(
  7048. ctx, subctx, dst,
  7049. { (uint32_t)n, 0, 0.0f, 0.0f },
  7050. dryrun
  7051. );
  7052. }
  7053. 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) {
  7054. const size_t n = ggml_nelements(dst->src[0]);
  7055. 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);
  7056. }
  7057. 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) {
  7058. int * op_params = (int *)dst->op_params;
  7059. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7060. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7061. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7062. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONCAT, {
  7063. (uint32_t)ggml_nelements(dst),
  7064. (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,
  7065. (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,
  7066. (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,
  7067. 0,
  7068. 0.0f, 0.0f, op_params[0],
  7069. }, dryrun);
  7070. }
  7071. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7072. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7073. const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0);
  7074. float sf0 = (float)dst->ne[0] / src0->ne[0];
  7075. float sf1 = (float)dst->ne[1] / src0->ne[1];
  7076. float sf2 = (float)dst->ne[2] / src0->ne[2];
  7077. float sf3 = (float)dst->ne[3] / src0->ne[3];
  7078. if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) {
  7079. sf0 = (float)(dst->ne[0] - 1) / (src0->ne[0] - 1);
  7080. sf1 = (float)(dst->ne[1] - 1) / (src0->ne[1] - 1);
  7081. }
  7082. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  7083. (uint32_t)ggml_nelements(dst), 0, 0,
  7084. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1],
  7085. (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,
  7086. (uint32_t)dst->ne[0], (uint32_t)dst->ne[1], (uint32_t)dst->ne[2],(uint32_t)dst->ne[3],
  7087. sf0, sf1, sf2, sf3,
  7088. }, dryrun);
  7089. }
  7090. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7091. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  7092. p.param1 = ggml_get_op_params_f32(dst, 0);
  7093. p.param2 = ggml_get_op_params_f32(dst, 1);
  7094. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p), dryrun);
  7095. }
  7096. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7097. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst), dryrun);
  7098. }
  7099. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7100. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst), dryrun);
  7101. }
  7102. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7103. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst), dryrun);
  7104. }
  7105. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7106. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  7107. p.param1 = ggml_get_op_params_f32(dst, 0);
  7108. p.param2 = ggml_get_op_params_f32(dst, 1);
  7109. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p), dryrun);
  7110. }
  7111. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7112. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  7113. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p), dryrun);
  7114. }
  7115. static void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7116. const int32_t s0 = ggml_get_op_params_i32(dst, 0);
  7117. const int32_t s1 = ggml_get_op_params_i32(dst, 1);
  7118. const int32_t s2 = ggml_get_op_params_i32(dst, 2);
  7119. const int32_t s3 = ggml_get_op_params_i32(dst, 3);
  7120. const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
  7121. const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
  7122. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  7123. memcpy(&p.param1, &s01_packed, sizeof(float));
  7124. memcpy(&p.param2, &s23_packed, sizeof(float));
  7125. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p), dryrun);
  7126. }
  7127. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7128. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  7129. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p), dryrun);
  7130. }
  7131. static void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7132. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  7133. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p), dryrun);
  7134. }
  7135. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7136. uint32_t ne = (uint32_t)ggml_nelements(src0);
  7137. if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7138. // Convert from number of logical elements to 2- or 4-byte units.
  7139. ne /= ggml_blck_size(src0->type);
  7140. if ((ggml_type_size(src0->type) % 4) == 0) {
  7141. ne *= ggml_type_size(src0->type) / 4;
  7142. } else {
  7143. ne *= ggml_type_size(src0->type) / 2;
  7144. }
  7145. }
  7146. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne);
  7147. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p), dryrun);
  7148. }
  7149. 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) {
  7150. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7151. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7152. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7153. // Skip empty skip_rows operations. For most ops the empty check at the start
  7154. // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst
  7155. // with empty srcs.
  7156. if (ggml_is_empty(src0) || ggml_is_empty(src1)) {
  7157. return;
  7158. }
  7159. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_SET_ROWS, {
  7160. (uint32_t)ggml_nelements(src0),
  7161. (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,
  7162. (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,
  7163. (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,
  7164. 0,
  7165. 0.0f, 0.0f, 0,
  7166. }, dryrun);
  7167. }
  7168. 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) {
  7169. 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);
  7170. }
  7171. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7172. float * op_params = (float *)dst->op_params;
  7173. 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);
  7174. }
  7175. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7176. const int * int_op_params = (const int *)dst->op_params;
  7177. const float * float_op_params = (const float *)dst->op_params;
  7178. const uint32_t num_groups = int_op_params[0];
  7179. const float eps = float_op_params[1];
  7180. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  7181. 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);
  7182. }
  7183. 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) {
  7184. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7185. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7186. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7187. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_RMS_NORM, {
  7188. (uint32_t)ggml_nelements(src0),
  7189. (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,
  7190. (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,
  7191. (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,
  7192. 0,
  7193. op_params[0], 0.0f, 0,
  7194. }, dryrun);
  7195. }
  7196. 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) {
  7197. float * op_params = (float *)dst->op_params;
  7198. 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);
  7199. }
  7200. static void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7201. float * op_params = (float *)dst->op_params;
  7202. 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);
  7203. }
  7204. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7205. 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);
  7206. }
  7207. 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) {
  7208. const float * op_params_f = (const float *)dst->op_params;
  7209. const bool swapped = (bool)dst->op_params[1];
  7210. const bool split = src1 != nullptr;
  7211. const float alpha = op_params_f[2];
  7212. const float limit = op_params_f[3];
  7213. GGML_ASSERT(ggml_is_contiguous(src0));
  7214. if (!split) {
  7215. GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]);
  7216. } else {
  7217. GGML_ASSERT(src0->ne[0] == src1->ne[0]);
  7218. GGML_ASSERT(src0->ne[0] == dst->ne[0]);
  7219. GGML_ASSERT(src0->type == src1->type);
  7220. }
  7221. const uint32_t mode = split ? 2 : (swapped ? 1 : 0);
  7222. ggml_vk_op_f32<vk_op_glu_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_GLU,
  7223. {
  7224. (uint32_t)ggml_nelements(dst),
  7225. (uint32_t)src0->ne[0],
  7226. (uint32_t)dst->ne[0],
  7227. mode,
  7228. alpha,
  7229. limit
  7230. }, dryrun);
  7231. }
  7232. 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) {
  7233. int32_t * op_params = (int32_t *)dst->op_params;
  7234. 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);
  7235. }
  7236. 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) {
  7237. float * op_params = (float *)dst->op_params;
  7238. float scale = op_params[0];
  7239. float max_bias = op_params[1];
  7240. const uint32_t ncols = (uint32_t)src0->ne[0];
  7241. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  7242. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  7243. const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u;
  7244. const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u;
  7245. const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u;
  7246. const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u;
  7247. const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u;
  7248. const uint32_t n_head_kv = src0->ne[2];
  7249. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  7250. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  7251. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  7252. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, dst, GGML_OP_SOFT_MAX, {
  7253. ncols,
  7254. src1 != nullptr ? nrows_y : (uint32_t)0,
  7255. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],
  7256. ne12, ne13,
  7257. nb11, nb12, nb13,
  7258. scale, max_bias,
  7259. m0, m1,
  7260. n_head_log2,
  7261. nrows_x,
  7262. src2 != nullptr
  7263. }, dryrun);
  7264. }
  7265. 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) {
  7266. float * op_params = (float *)dst->op_params;
  7267. 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)src0->ne[1], op_params[0], op_params[1] }, dryrun);
  7268. }
  7269. 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) {
  7270. const int n_dims = ((int32_t *) dst->op_params)[1];
  7271. const int mode = ((int32_t *) dst->op_params)[2];
  7272. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  7273. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  7274. const float freq_base = ((float *) dst->op_params)[5];
  7275. const float freq_scale = ((float *) dst->op_params)[6];
  7276. const float ext_factor = ((float *) dst->op_params)[7];
  7277. const float attn_factor = ((float *) dst->op_params)[8];
  7278. const float beta_fast = ((float *) dst->op_params)[9];
  7279. const float beta_slow = ((float *) dst->op_params)[10];
  7280. int sections[4] {};
  7281. if (mode & GGML_ROPE_TYPE_MROPE) {
  7282. memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4);
  7283. }
  7284. float corr_dims[2];
  7285. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  7286. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  7287. uint32_t s1 = src0->nb[1] / ggml_type_size(src0->type);
  7288. uint32_t s2 = src0->nb[2] / ggml_type_size(src0->type);
  7289. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, dst, GGML_OP_ROPE, {
  7290. (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  7291. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  7292. src2 != nullptr, (uint32_t)src0->ne[2], s1, s2,
  7293. { sections[0], sections[1], sections[2], sections[3] }, backprop
  7294. }, dryrun);
  7295. }
  7296. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7297. int32_t * op_params = (int32_t *)dst->op_params;
  7298. uint32_t ncols = src0->ne[0];
  7299. ggml_vk_op_f32<vk_op_argsort_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_ARGSORT, {
  7300. ncols,
  7301. op_params[0],
  7302. }, dryrun);
  7303. }
  7304. static void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7305. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SUM, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f }, dryrun);
  7306. }
  7307. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7308. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, { (uint32_t)src0->ne[0], 0, 0.0f, 0.0f }, dryrun);
  7309. }
  7310. static void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7311. 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);
  7312. }
  7313. 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) {
  7314. 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);
  7315. }
  7316. 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) {
  7317. const int32_t s0 = dst->op_params[0];
  7318. const int32_t s1 = dst->op_params[1];
  7319. const int32_t p0 = dst->op_params[2];
  7320. const int32_t p1 = dst->op_params[3];
  7321. const int32_t d0 = dst->op_params[4];
  7322. const int32_t d1 = dst->op_params[5];
  7323. const bool is_2D = dst->op_params[6] == 1;
  7324. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  7325. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  7326. const uint32_t IW = src1->ne[0];
  7327. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  7328. const uint32_t KW = src0->ne[0];
  7329. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  7330. const uint32_t OW = dst->ne[1];
  7331. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  7332. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  7333. const uint32_t pelements = OW * KW * KH;
  7334. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_IM2COL, {
  7335. batch_offset, offset_delta,
  7336. IC, IW, IH, OW, OH, KW, KH,
  7337. pelements,
  7338. IC * KH * KW,
  7339. s0, s1, p0, p1, d0, d1,
  7340. }, dryrun);
  7341. }
  7342. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7343. const uint32_t dim = dst->op_params[0];
  7344. const uint32_t max_period = dst->op_params[1];
  7345. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  7346. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  7347. nb1, dim, max_period,
  7348. }, dryrun);
  7349. }
  7350. 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) {
  7351. // src0: (K, Cout, Cin, 1) -- kernel
  7352. // src1: (L, Cin, 1, 1) -- input
  7353. // dst: (*, Cout, 1, 1)
  7354. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  7355. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  7356. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  7357. GGML_TENSOR_BINARY_OP_LOCALS
  7358. GGML_ASSERT(nb00 == sizeof(float));
  7359. GGML_ASSERT(nb10 == sizeof(float));
  7360. const int32_t s0 = dst->op_params[0];
  7361. vk_op_conv_transpose_1d_push_constants p{};
  7362. p.Cout = static_cast<uint32_t>(ne01);
  7363. p.Cin = static_cast<uint32_t>(ne02);
  7364. p.K = static_cast<uint32_t>(ne00);
  7365. p.L = static_cast<uint32_t>(ne10);
  7366. p.KL = static_cast<uint32_t>(ne0);
  7367. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  7368. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  7369. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  7370. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  7371. p.s0 = static_cast<uint32_t>(s0);
  7372. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p), dryrun);
  7373. }
  7374. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7375. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  7376. const int32_t k1 = dst->op_params[1];
  7377. const int32_t k0 = dst->op_params[2];
  7378. const int32_t s1 = dst->op_params[3];
  7379. const int32_t s0 = dst->op_params[4];
  7380. const int32_t p1 = dst->op_params[5];
  7381. const int32_t p0 = dst->op_params[6];
  7382. const uint32_t IH = src0->ne[1];
  7383. const uint32_t IW = src0->ne[0];
  7384. const uint32_t N = dst->ne[3];
  7385. const uint32_t OC = dst->ne[2];
  7386. const uint32_t OH = dst->ne[1];
  7387. const uint32_t OW = dst->ne[0];
  7388. const uint32_t parallel_elements = N * OC * OH * OW;
  7389. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  7390. IW, IH, OW, OH, OC,
  7391. parallel_elements,
  7392. op,
  7393. k0, k1, s0, s1, p0, p1,
  7394. }, dryrun);
  7395. }
  7396. static void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  7397. const ggml_tensor * src1, ggml_tensor * dst, bool dryrun = false) {
  7398. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  7399. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  7400. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  7401. GGML_TENSOR_BINARY_OP_LOCALS
  7402. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  7403. GGML_ASSERT(nb10 == sizeof(float));
  7404. GGML_ASSERT(nb0 == sizeof(float));
  7405. vk_op_conv2d_push_constants p{};
  7406. p.Cout = static_cast<uint32_t>(ne03);
  7407. p.Cin = static_cast<uint32_t>(ne02);
  7408. p.N = static_cast<uint32_t>(ne13);
  7409. p.KW = static_cast<uint32_t>(ne00);
  7410. p.KH = static_cast<uint32_t>(ne01);
  7411. p.W = static_cast<uint32_t>(ne10);
  7412. p.H = static_cast<uint32_t>(ne11);
  7413. p.OW = static_cast<uint32_t>(ne0);
  7414. p.OH = static_cast<uint32_t>(ne1);
  7415. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  7416. p.s1 = static_cast<uint32_t>(dst->op_params[1]);
  7417. p.p0 = static_cast<uint32_t>(dst->op_params[2]);
  7418. p.p1 = static_cast<uint32_t>(dst->op_params[3]);
  7419. p.d0 = static_cast<uint32_t>(dst->op_params[4]);
  7420. p.d1 = static_cast<uint32_t>(dst->op_params[5]);
  7421. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  7422. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  7423. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  7424. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  7425. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  7426. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  7427. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  7428. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  7429. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  7430. GGML_ASSERT(ne03 == ne2);
  7431. GGML_ASSERT(ne02 == ne12);
  7432. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONV_2D, std::move(p), dryrun);
  7433. }
  7434. 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) {
  7435. vk_op_conv2d_dw_push_constants p{};
  7436. p.ne = ggml_nelements(dst);
  7437. p.channels = dst->ne[2];
  7438. p.batches = dst->ne[3];
  7439. p.dst_w = dst->ne[0];
  7440. p.dst_h = dst->ne[1];
  7441. p.src_w = src1->ne[0];
  7442. p.src_h = src1->ne[1];
  7443. p.knl_w = src0->ne[0];
  7444. p.knl_h = src0->ne[1];
  7445. p.stride_x = dst->op_params[0];
  7446. p.stride_y = dst->op_params[1];
  7447. p.pad_x = dst->op_params[2];
  7448. p.pad_y = dst->op_params[3];
  7449. p.dilation_x = dst->op_params[4];
  7450. p.dilation_y = dst->op_params[5];
  7451. GGML_ASSERT(src0->ne[3] == p.channels);
  7452. GGML_ASSERT(src1->ne[3] == p.batches);
  7453. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p), dryrun);
  7454. }
  7455. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst, bool dryrun = false) {
  7456. const float * op_params = (const float *)dst->op_params;
  7457. 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);
  7458. }
  7459. #ifdef GGML_VULKAN_RUN_TESTS
  7460. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  7461. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  7462. return;
  7463. }
  7464. i0 = std::max(i0, 5);
  7465. i1 = std::max(i1, 5);
  7466. i2 = std::max(i2, 0);
  7467. fprintf(stderr, " ");
  7468. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  7469. fprintf(stderr, "%7d ", idx1);
  7470. }
  7471. fprintf(stderr, "\n");
  7472. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  7473. fprintf(stderr, "%7d: ", idx0);
  7474. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  7475. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  7476. float val;
  7477. if (type == GGML_TYPE_F32) {
  7478. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  7479. } else if (type == GGML_TYPE_F16) {
  7480. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  7481. } else {
  7482. GGML_ABORT("fatal error");
  7483. }
  7484. fprintf(stderr, "% 7.2f ", val);
  7485. } else {
  7486. fprintf(stderr, " ");
  7487. }
  7488. }
  7489. fprintf(stderr, "\n");
  7490. }
  7491. }
  7492. template <typename X_TYPE, typename Y_TYPE>
  7493. 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) {
  7494. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  7495. const size_t x_ne = m * k * batch;
  7496. const size_t y_ne = k * n * batch;
  7497. const size_t d_ne = m * n * batch;
  7498. vk_pipeline p;
  7499. std::string shname;
  7500. if (shader_size == 0) {
  7501. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  7502. p = ctx->device->pipeline_matmul_f32->a_s;
  7503. shname = "F32_ALIGNED_S";
  7504. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  7505. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  7506. shname = "F32_F16_ALIGNED_S";
  7507. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  7508. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  7509. shname = "F16_F32_ALIGNED_S";
  7510. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  7511. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  7512. shname = "F16_ALIGNED_S";
  7513. } else {
  7514. GGML_ABORT("fatal error");
  7515. }
  7516. } else if (shader_size == 1) {
  7517. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  7518. p = ctx->device->pipeline_matmul_f32->a_m;
  7519. shname = "F32_ALIGNED_M";
  7520. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  7521. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  7522. shname = "F32_F16_ALIGNED_M";
  7523. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  7524. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  7525. shname = "F16_F32_ALIGNED_M";
  7526. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  7527. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  7528. shname = "F16_ALIGNED_M";
  7529. } else {
  7530. GGML_ABORT("fatal error");
  7531. }
  7532. } else if (shader_size == 2) {
  7533. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  7534. p = ctx->device->pipeline_matmul_f32->a_l;
  7535. shname = "F32_ALIGNED_L";
  7536. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  7537. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  7538. shname = "F32_F16_ALIGNED_L";
  7539. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  7540. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  7541. shname = "F16_F32_ALIGNED_L";
  7542. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  7543. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  7544. shname = "F16_ALIGNED_L";
  7545. } else {
  7546. GGML_ABORT("fatal error");
  7547. }
  7548. } else {
  7549. GGML_ASSERT(0);
  7550. }
  7551. const size_t kpad = ggml_vk_align_size(k, p->align);
  7552. if (k != kpad) {
  7553. if (shader_size == 0) {
  7554. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  7555. p = ctx->device->pipeline_matmul_f32->s;
  7556. shname = "F32_S";
  7557. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  7558. p = ctx->device->pipeline_matmul_f32_f16->s;
  7559. shname = "F32_F16_S";
  7560. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  7561. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  7562. shname = "F16_F32_S";
  7563. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  7564. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  7565. shname = "F16_S";
  7566. }
  7567. } else if (shader_size == 1) {
  7568. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  7569. p = ctx->device->pipeline_matmul_f32->m;
  7570. shname = "F32_M";
  7571. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  7572. p = ctx->device->pipeline_matmul_f32_f16->m;
  7573. shname = "F32_F16_M";
  7574. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  7575. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  7576. shname = "F16_F32_M";
  7577. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  7578. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  7579. shname = "F16_M";
  7580. }
  7581. } else if (shader_size == 2) {
  7582. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  7583. p = ctx->device->pipeline_matmul_f32->l;
  7584. shname = "F32_L";
  7585. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  7586. p = ctx->device->pipeline_matmul_f32_f16->l;
  7587. shname = "F32_F16_L";
  7588. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  7589. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  7590. shname = "F16_F32_L";
  7591. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  7592. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  7593. shname = "F16_L";
  7594. }
  7595. }
  7596. }
  7597. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  7598. if (split_k > 1) {
  7599. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  7600. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  7601. // Resize buffer
  7602. if (ctx->prealloc_split_k != nullptr) {
  7603. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  7604. }
  7605. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, vk::MemoryPropertyFlagBits::eDeviceLocal);
  7606. }
  7607. }
  7608. if (ctx->device->need_compiles) {
  7609. ggml_vk_load_shaders(ctx->device);
  7610. }
  7611. ggml_pipeline_allocate_descriptor_sets(ctx);
  7612. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  7613. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  7614. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, vk::MemoryPropertyFlagBits::eDeviceLocal);
  7615. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  7616. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  7617. float* d = (float *) malloc(sizeof(float) * d_ne);
  7618. for (size_t i = 0; i < x_ne; i++) {
  7619. if (std::is_same<float, X_TYPE>()) {
  7620. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  7621. // x[i] = 1.0f;
  7622. // x[i] = i + 1;
  7623. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  7624. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  7625. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  7626. // x[i] = ggml_fp32_to_fp16(1.0f);
  7627. // x[i] = ggml_fp32_to_fp16(i + 1);
  7628. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  7629. } else {
  7630. GGML_ABORT("fatal error");
  7631. }
  7632. }
  7633. for (size_t i = 0; i < y_ne; i++) {
  7634. if (std::is_same<float, Y_TYPE>()) {
  7635. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  7636. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  7637. // y[i] = i + 1;
  7638. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  7639. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  7640. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  7641. // y[i] = ggml_fp32_to_fp16(i + 1);
  7642. } else {
  7643. GGML_ABORT("fatal error");
  7644. }
  7645. }
  7646. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  7647. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  7648. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  7649. ggml_vk_ctx_begin(ctx->device, subctx);
  7650. for (size_t i = 0; i < num_it; i++) {
  7651. ggml_vk_matmul(
  7652. 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),
  7653. m, n, k,
  7654. k, k, m, k*m, k*n, m*n,
  7655. split_k, batch, batch, batch, 1, 1, n
  7656. );
  7657. }
  7658. ggml_vk_ctx_end(subctx);
  7659. auto begin = std::chrono::high_resolution_clock::now();
  7660. ggml_vk_submit(subctx, ctx->fence);
  7661. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  7662. ctx->device->device.resetFences({ ctx->fence });
  7663. ggml_vk_queue_command_pools_cleanup(ctx->device);
  7664. auto end = std::chrono::high_resolution_clock::now();
  7665. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  7666. // copy dst to host
  7667. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  7668. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  7669. ggml_init_params iparams = {
  7670. /*.mem_size =*/ 1024*1024*1024,
  7671. /*.mem_buffer =*/ NULL,
  7672. /*.no_alloc =*/ true,
  7673. };
  7674. ggml_context * ggml_ctx = ggml_init(iparams);
  7675. ggml_type src0_type;
  7676. ggml_type src1_type;
  7677. if (std::is_same<float, X_TYPE>()) {
  7678. src0_type = GGML_TYPE_F32;
  7679. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  7680. src0_type = GGML_TYPE_F16;
  7681. } else {
  7682. GGML_ABORT("fatal error");
  7683. }
  7684. if (std::is_same<float, Y_TYPE>()) {
  7685. src1_type = GGML_TYPE_F32;
  7686. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  7687. src1_type = GGML_TYPE_F16;
  7688. } else {
  7689. GGML_ABORT("fatal error");
  7690. }
  7691. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  7692. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  7693. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  7694. src0_ggml->data = x;
  7695. src1_ggml->data = y;
  7696. tensor_ggml->data = d_chk;
  7697. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  7698. ggml_build_forward_expand(cgraph, tensor_ggml);
  7699. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  7700. ggml_free(ggml_ctx);
  7701. double avg_err = 0.0;
  7702. int first_err_n = -1;
  7703. int first_err_m = -1;
  7704. int first_err_b = -1;
  7705. for (size_t i = 0; i < m*n*batch; i++) {
  7706. double err = std::fabs(d[i] - d_chk[i]);
  7707. avg_err += err;
  7708. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  7709. first_err_b = i / (m * n);
  7710. first_err_n = (i % (m * n)) / m;
  7711. first_err_m = (i % (m * n)) % m;
  7712. }
  7713. }
  7714. avg_err /= m * n;
  7715. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  7716. 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;
  7717. if (avg_err > 0.1 || std::isnan(avg_err)) {
  7718. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  7719. std::cerr << "Actual result: " << std::endl << std::endl;
  7720. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  7721. std::cerr << "Expected result: " << std::endl << std::endl;
  7722. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  7723. if (split_k > 1) {
  7724. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  7725. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  7726. std::cerr << "d_buf0: " << std::endl << std::endl;
  7727. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  7728. std::cerr << "d_buf1: " << std::endl << std::endl;
  7729. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  7730. std::cerr << "d_buf2: " << std::endl << std::endl;
  7731. 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);
  7732. std::cerr << "d_buf3: " << std::endl << std::endl;
  7733. 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);
  7734. free(split_k_buf);
  7735. }
  7736. }
  7737. free(d_chk);
  7738. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  7739. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  7740. ggml_vk_destroy_buffer(d_X);
  7741. ggml_vk_destroy_buffer(d_Y);
  7742. ggml_vk_destroy_buffer(d_D);
  7743. free(x);
  7744. free(y);
  7745. free(d);
  7746. }
  7747. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  7748. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  7749. return;
  7750. }
  7751. i0 = std::max(i0, 5);
  7752. i1 = std::max(i1, 5);
  7753. i2 = std::max(i2, 0);
  7754. i3 = std::max(i3, 0);
  7755. fprintf(stderr, " ");
  7756. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  7757. fprintf(stderr, "%7d ", idx1);
  7758. }
  7759. fprintf(stderr, "\n");
  7760. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  7761. fprintf(stderr, "%7d: ", idx0);
  7762. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  7763. 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]) {
  7764. float val;
  7765. if (tensor->type == GGML_TYPE_F32) {
  7766. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  7767. } else if (tensor->type == GGML_TYPE_F16) {
  7768. 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]));
  7769. } else {
  7770. GGML_ABORT("fatal error");
  7771. }
  7772. fprintf(stderr, "% 7.2f ", val);
  7773. } else {
  7774. fprintf(stderr, " ");
  7775. }
  7776. }
  7777. fprintf(stderr, "\n");
  7778. }
  7779. }
  7780. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  7781. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  7782. }
  7783. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  7784. if (quant == GGML_TYPE_F32) {
  7785. memcpy(to, from, sizeof(float) * ne);
  7786. return;
  7787. }
  7788. const auto * tt = ggml_get_type_traits(quant);
  7789. ggml_to_float_t dequant_fn = tt->to_float;
  7790. dequant_fn(from, to, ne);
  7791. }
  7792. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  7793. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  7794. const size_t x_sz = sizeof(float) * ne;
  7795. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  7796. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  7797. float * x = (float *) malloc(x_sz);
  7798. void * qx = malloc(qx_sz);
  7799. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  7800. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, vk::MemoryPropertyFlagBits::eDeviceLocal);
  7801. float * x_ref = (float *) malloc(x_sz);
  7802. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  7803. for (size_t i = 0; i < ne; i++) {
  7804. x[i] = rand() / (float)RAND_MAX;
  7805. }
  7806. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  7807. ggml_vk_quantize_data(x, qx, ne, quant);
  7808. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  7809. ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  7810. if (ctx->device->need_compiles) {
  7811. ggml_vk_load_shaders(ctx->device);
  7812. }
  7813. ggml_pipeline_allocate_descriptor_sets(ctx);
  7814. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  7815. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  7816. ggml_vk_ctx_begin(ctx->device, subctx);
  7817. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  7818. 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});
  7819. ggml_vk_ctx_end(subctx);
  7820. auto begin = std::chrono::high_resolution_clock::now();
  7821. ggml_vk_submit(subctx, ctx->fence);
  7822. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  7823. ctx->device->device.resetFences({ ctx->fence });
  7824. ggml_vk_queue_command_pools_cleanup(ctx->device);
  7825. auto end = std::chrono::high_resolution_clock::now();
  7826. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  7827. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  7828. int first_err = -1;
  7829. double avg_err = 0.0;
  7830. for (size_t i = 0; i < ne; i++) {
  7831. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  7832. avg_err += error;
  7833. if (first_err < 0 && error > 0.05) {
  7834. first_err = i;
  7835. }
  7836. }
  7837. avg_err /= ne;
  7838. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  7839. if (avg_err > 0.1) {
  7840. std::cerr << "first_error = " << first_err << std::endl;
  7841. std::cerr << "Actual result: " << std::endl << std::endl;
  7842. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  7843. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  7844. }
  7845. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  7846. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  7847. std::cerr << x_ref[i] << ", ";
  7848. }
  7849. std::cerr << std::endl;
  7850. }
  7851. ggml_vk_destroy_buffer(x_buf);
  7852. ggml_vk_destroy_buffer(qx_buf);
  7853. free(x);
  7854. free(qx);
  7855. free(x_ref);
  7856. free(x_chk);
  7857. }
  7858. // This does not work without ggml q8_1 quantization support
  7859. //
  7860. // typedef uint16_t ggml_half;
  7861. // typedef uint32_t ggml_half2;
  7862. //
  7863. // #define QK8_1 32
  7864. // typedef struct {
  7865. // union {
  7866. // struct {
  7867. // ggml_half d; // delta
  7868. // ggml_half s; // d * sum(qs[i])
  7869. // } GGML_COMMON_AGGR_S;
  7870. // ggml_half2 ds;
  7871. // } GGML_COMMON_AGGR_U;
  7872. // int8_t qs[QK8_1]; // quants
  7873. // } block_q8_1;
  7874. //
  7875. // static void ggml_vk_test_quantize(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  7876. // VK_LOG_DEBUG("ggml_vk_test_quantize(" << ne << ")");
  7877. // GGML_ASSERT(quant == GGML_TYPE_Q8_1);
  7878. //
  7879. // const size_t x_sz = sizeof(float) * ne;
  7880. // const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  7881. // float * x = (float *) malloc(x_sz);
  7882. // block_q8_1 * qx = (block_q8_1 *)malloc(qx_sz);
  7883. // block_q8_1 * qx_res = (block_q8_1 *)malloc(qx_sz);
  7884. // vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  7885. // vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  7886. //
  7887. // for (size_t i = 0; i < ne; i++) {
  7888. // x[i] = rand() / (float)RAND_MAX;
  7889. // }
  7890. //
  7891. // vk_pipeline p = ggml_vk_get_quantize_pipeline(ctx, quant);
  7892. //
  7893. // ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  7894. //
  7895. // if (ctx->device->need_compiles) {
  7896. // ggml_vk_load_shaders(ctx->device);
  7897. // }
  7898. //
  7899. // ggml_pipeline_allocate_descriptor_sets(ctx);
  7900. //
  7901. // ggml_vk_buffer_write(x_buf, 0, x, x_sz);
  7902. //
  7903. // vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  7904. // ggml_vk_ctx_begin(ctx->device, subctx);
  7905. // ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(x_buf), ggml_vk_subbuffer(qx_buf), ne);
  7906. // ggml_vk_ctx_end(subctx);
  7907. //
  7908. // auto begin = std::chrono::high_resolution_clock::now();
  7909. //
  7910. // ggml_vk_submit(subctx, ctx->fence);
  7911. // VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_quantize waitForFences");
  7912. // ctx->device->device.resetFences({ ctx->fence });
  7913. // ggml_vk_queue_command_pools_cleanup(ctx->device);
  7914. //
  7915. // auto end = std::chrono::high_resolution_clock::now();
  7916. //
  7917. // double ms_quant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  7918. // ggml_vk_buffer_read(qx_buf, 0, qx, qx_sz);
  7919. //
  7920. // ggml_vk_quantize_data(x, qx_res, ne, quant);
  7921. //
  7922. // int first_err = -1;
  7923. //
  7924. // for (size_t i = 0; i < ne / 32; i++) {
  7925. // 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));
  7926. //
  7927. // if (first_err < 0 && error > 0.1) {
  7928. // first_err = i;
  7929. // }
  7930. //
  7931. // 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));
  7932. //
  7933. // if (first_err < 0 && error > 0.1) {
  7934. // first_err = i;
  7935. // }
  7936. //
  7937. // for (size_t j = 0; j < 32; j++) {
  7938. // uint64_t error = std::abs(qx_res[i].qs[j] - qx[i].qs[j]);
  7939. //
  7940. // if (first_err < 0 && error > 1) {
  7941. // first_err = i;
  7942. // }
  7943. // }
  7944. // }
  7945. //
  7946. // std::cerr << "TEST QUANTIZE " << ggml_type_name(quant) << " time=" << ms_quant << "ms " << (first_err == -1 ? "CORRECT" : "INCORRECT") << std::endl;
  7947. //
  7948. // if (first_err != -1) {
  7949. // std::cerr << "first_error = " << first_err << std::endl;
  7950. // std::cerr << "Actual result: " << std::endl << std::endl;
  7951. // 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) << " ";
  7952. // for (size_t j = 0; j < 32; j++) {
  7953. // std::cout << " qs" << j << "=" << (uint32_t)qx[first_err].qs[j] << " ";
  7954. // }
  7955. // std::cerr << std::endl << std::endl << "Expected result: " << std::endl << std::endl;
  7956. // 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) << " ";
  7957. // for (size_t j = 0; j < 32; j++) {
  7958. // std::cout << " qs" << j << "=" << (uint32_t)qx_res[first_err].qs[j] << " ";
  7959. // }
  7960. // std::cerr << std::endl;
  7961. // }
  7962. //
  7963. // ggml_vk_destroy_buffer(x_buf);
  7964. // ggml_vk_destroy_buffer(qx_buf);
  7965. //
  7966. // free(x);
  7967. // free(qx);
  7968. // free(qx_res);
  7969. // }
  7970. 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) {
  7971. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  7972. const size_t x_ne = m * k * batch;
  7973. const size_t y_ne = k * n * batch;
  7974. const size_t d_ne = m * n * batch;
  7975. vk_matmul_pipeline2 * pipelines;
  7976. if (mmq) {
  7977. pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1;
  7978. } else {
  7979. pipelines = ctx->device->pipeline_dequant_mul_mat_mat;
  7980. }
  7981. const bool fp16acc = ctx->device->fp16;
  7982. vk_pipeline p;
  7983. std::string shname;
  7984. if (shader_size == 0) {
  7985. p = fp16acc ? pipelines[quant].f16acc->a_s : pipelines[quant].f32acc->a_s;
  7986. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  7987. } else if (shader_size == 1) {
  7988. p = fp16acc ? pipelines[quant].f16acc->a_m : pipelines[quant].f32acc->a_m;
  7989. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  7990. } else if (shader_size == 2) {
  7991. p = fp16acc ? pipelines[quant].f16acc->a_l : pipelines[quant].f32acc->a_l;
  7992. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  7993. } else {
  7994. GGML_ASSERT(0);
  7995. }
  7996. const size_t kpad = mmq ? 0 : ggml_vk_align_size(k, p->align);
  7997. if (mmq || k != kpad) {
  7998. if (shader_size == 0) {
  7999. p = fp16acc ? pipelines[quant].f16acc->s : pipelines[quant].f32acc->s;
  8000. shname = std::string(ggml_type_name(quant)) + "_S";
  8001. } else if (shader_size == 1) {
  8002. p = fp16acc ? pipelines[quant].f16acc->m : pipelines[quant].f32acc->m;
  8003. shname = std::string(ggml_type_name(quant)) + "_M";
  8004. } else if (shader_size == 2) {
  8005. p = fp16acc ? pipelines[quant].f16acc->l : pipelines[quant].f32acc->l;
  8006. shname = std::string(ggml_type_name(quant)) + "_L";
  8007. } else {
  8008. GGML_ASSERT(0);
  8009. }
  8010. }
  8011. if (p == nullptr) {
  8012. std::cerr << "error: no pipeline for ggml_vk_test_dequant_matmul " << ggml_type_name(quant) << std::endl;
  8013. return;
  8014. }
  8015. const size_t x_sz = sizeof(float) * x_ne;
  8016. const size_t y_sz = sizeof(float) * y_ne;
  8017. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  8018. const size_t qy_sz = mmq ? y_ne * ggml_type_size(GGML_TYPE_Q8_1)/ggml_blck_size(GGML_TYPE_Q8_1) : y_sz;
  8019. const size_t d_sz = sizeof(float) * d_ne;
  8020. float * x = (float *) malloc(x_sz);
  8021. float * y = (float *) malloc(y_sz);
  8022. void * qx = malloc(qx_sz);
  8023. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  8024. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  8025. vk_buffer qy_buf = ggml_vk_create_buffer_check(ctx->device, qy_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  8026. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, vk::MemoryPropertyFlagBits::eDeviceLocal);
  8027. float * d = (float *) malloc(d_sz);
  8028. float * d_chk = (float *) malloc(d_sz);
  8029. for (size_t i = 0; i < x_ne; i++) {
  8030. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  8031. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  8032. // x[i] = i % k;
  8033. }
  8034. ggml_vk_quantize_data(x, qx, x_ne, quant);
  8035. for (size_t i = 0; i < y_ne; i++) {
  8036. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  8037. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  8038. // y[i] = i % k;
  8039. }
  8040. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  8041. if (split_k > 1) {
  8042. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  8043. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  8044. // Resize buffer
  8045. if (ctx->prealloc_split_k != nullptr) {
  8046. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  8047. }
  8048. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, vk::MemoryPropertyFlagBits::eDeviceLocal);
  8049. }
  8050. }
  8051. if (mmq) {
  8052. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_quantize_q8_1, num_it);
  8053. }
  8054. if (ctx->device->need_compiles) {
  8055. ggml_vk_load_shaders(ctx->device);
  8056. }
  8057. ggml_pipeline_allocate_descriptor_sets(ctx);
  8058. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  8059. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  8060. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  8061. ggml_vk_ctx_begin(ctx->device, subctx);
  8062. if (mmq) {
  8063. for (size_t i = 0; i < num_it; i++) {
  8064. ggml_vk_quantize_q8_1(ctx, subctx, { y_buf, 0, y_sz }, { qy_buf, 0, qy_sz }, y_ne);
  8065. ggml_vk_matmul(
  8066. 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 },
  8067. m, n, k,
  8068. k, k, m, k*m, k*n, m*n,
  8069. split_k, batch, batch, batch, 1, 1, n
  8070. );
  8071. }
  8072. } else {
  8073. for (size_t i = 0; i < num_it; i++) {
  8074. ggml_vk_matmul(
  8075. 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 },
  8076. m, n, k,
  8077. k, k, m, k*m, k*n, m*n,
  8078. split_k, batch, batch, batch, 1, 1, n
  8079. );
  8080. }
  8081. }
  8082. ggml_vk_ctx_end(subctx);
  8083. auto begin = std::chrono::high_resolution_clock::now();
  8084. ggml_vk_submit(subctx, ctx->fence);
  8085. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  8086. ctx->device->device.resetFences({ ctx->fence });
  8087. ggml_vk_queue_command_pools_cleanup(ctx->device);
  8088. auto end = std::chrono::high_resolution_clock::now();
  8089. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  8090. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  8091. ggml_init_params iparams = {
  8092. /*.mem_size =*/ 1024*1024*1024,
  8093. /*.mem_buffer =*/ NULL,
  8094. /*.no_alloc =*/ true,
  8095. };
  8096. ggml_context * ggml_ctx = ggml_init(iparams);
  8097. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  8098. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  8099. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  8100. src0_ggml->data = qx;
  8101. src1_ggml->data = y;
  8102. tensor_ggml->data = d_chk;
  8103. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  8104. ggml_build_forward_expand(cgraph, tensor_ggml);
  8105. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  8106. ggml_free(ggml_ctx);
  8107. double avg_err = 0.0;
  8108. int first_err_n = -1;
  8109. int first_err_m = -1;
  8110. int first_err_b = -1;
  8111. for (size_t i = 0; i < m*n*batch; i++) {
  8112. double err = std::fabs(d[i] - d_chk[i]);
  8113. avg_err += err;
  8114. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  8115. first_err_b = i / (m * n);
  8116. first_err_n = (i % (m * n)) / m;
  8117. first_err_m = (i % (m * n)) % m;
  8118. }
  8119. }
  8120. avg_err /= m * n;
  8121. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  8122. std::cerr << "TEST dequant matmul " << shname;
  8123. if (mmq) {
  8124. std::cerr << " mmq";
  8125. }
  8126. 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;
  8127. if (avg_err > 0.01 || std::isnan(avg_err)) {
  8128. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  8129. std::cerr << "Actual result: " << std::endl << std::endl;
  8130. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  8131. std::cerr << std::endl;
  8132. std::cerr << "Expected result: " << std::endl << std::endl;
  8133. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  8134. std::cerr << "src0: " << std::endl << std::endl;
  8135. ggml_vk_print_matrix_area(x, GGML_TYPE_F32, k, m, first_err_m, first_err_n, first_err_b);
  8136. std::cerr << std::endl;
  8137. std::cerr << "src1: " << std::endl << std::endl;
  8138. ggml_vk_print_matrix_area(y, GGML_TYPE_F32, k, n, first_err_m, first_err_n, first_err_b);
  8139. if (split_k > 1) {
  8140. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  8141. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  8142. std::cerr << "d_buf0: " << std::endl << std::endl;
  8143. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  8144. std::cerr << "d_buf1: " << std::endl << std::endl;
  8145. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  8146. std::cerr << "d_buf2: " << std::endl << std::endl;
  8147. 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);
  8148. std::cerr << "d_buf3: " << std::endl << std::endl;
  8149. 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);
  8150. free(split_k_buf);
  8151. }
  8152. }
  8153. ggml_vk_destroy_buffer(qx_buf);
  8154. ggml_vk_destroy_buffer(y_buf);
  8155. ggml_vk_destroy_buffer(qy_buf);
  8156. ggml_vk_destroy_buffer(d_buf);
  8157. free(x);
  8158. free(qx);
  8159. free(y);
  8160. free(d);
  8161. free(d_chk);
  8162. }
  8163. #endif
  8164. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx) {
  8165. #if defined(GGML_VULKAN_RUN_TESTS)
  8166. const std::vector<size_t> vals {
  8167. 512, 512, 128,
  8168. 128, 512, 512,
  8169. 4096, 512, 4096,
  8170. 11008, 512, 4096,
  8171. 4096, 512, 11008,
  8172. 32000, 512, 4096,
  8173. 8, 8, 8,
  8174. 100, 46, 576,
  8175. 623, 111, 128,
  8176. 100, 46, 558,
  8177. 512, 1, 256,
  8178. 128, 110, 622,
  8179. 511, 511, 127,
  8180. 511, 511, 7,
  8181. 511, 511, 17,
  8182. 49, 49, 128,
  8183. 128, 49, 49,
  8184. 4096, 49, 4096,
  8185. };
  8186. const size_t num_it = 100;
  8187. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  8188. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  8189. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  8190. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true);
  8191. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true);
  8192. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true);
  8193. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0);
  8194. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0);
  8195. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0);
  8196. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true);
  8197. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true);
  8198. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true);
  8199. abort();
  8200. for (size_t i = 0; i < vals.size(); i += 3) {
  8201. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  8202. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  8203. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  8204. std::cerr << '\n';
  8205. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  8206. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  8207. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  8208. std::cerr << '\n';
  8209. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  8210. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  8211. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  8212. std::cerr << '\n' << std::endl;
  8213. if (vals[i + 2] % 32 == 0) {
  8214. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  8215. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  8216. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  8217. std::cerr << '\n';
  8218. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  8219. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  8220. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  8221. std::cerr << '\n';
  8222. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  8223. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  8224. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  8225. std::cerr << '\n' << std::endl;
  8226. }
  8227. if (vals[i + 2] % 256 == 0) {
  8228. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  8229. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  8230. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  8231. std::cerr << '\n';
  8232. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  8233. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  8234. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  8235. std::cerr << '\n';
  8236. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  8237. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  8238. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  8239. std::cerr << '\n' << std::endl;
  8240. }
  8241. }
  8242. GGML_ABORT("fatal error");
  8243. #endif
  8244. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  8245. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  8246. // Resize buffer
  8247. if (ctx->prealloc_x != nullptr) {
  8248. ggml_vk_destroy_buffer(ctx->prealloc_x);
  8249. }
  8250. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  8251. }
  8252. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  8253. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  8254. // Resize buffer
  8255. if (ctx->prealloc_y != nullptr) {
  8256. ggml_vk_destroy_buffer(ctx->prealloc_y);
  8257. }
  8258. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  8259. }
  8260. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  8261. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  8262. // Resize buffer
  8263. if (ctx->prealloc_split_k != nullptr) {
  8264. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  8265. }
  8266. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  8267. }
  8268. }
  8269. 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);
  8270. // Returns true if node has enqueued work into the queue, false otherwise
  8271. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  8272. 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){
  8273. ggml_tensor * node = cgraph->nodes[node_idx];
  8274. if (ggml_is_empty(node) || !node->buffer) {
  8275. return false;
  8276. }
  8277. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  8278. ctx->semaphore_idx = 0;
  8279. const ggml_tensor * src0 = node->src[0];
  8280. const ggml_tensor * src1 = node->src[1];
  8281. const ggml_tensor * src2 = node->src[2];
  8282. const ggml_tensor * src3 = node->src[3];
  8283. switch (node->op) {
  8284. // Return on empty ops to avoid generating a compute_ctx and setting exit_tensor
  8285. case GGML_OP_RESHAPE:
  8286. case GGML_OP_VIEW:
  8287. case GGML_OP_PERMUTE:
  8288. case GGML_OP_TRANSPOSE:
  8289. case GGML_OP_NONE:
  8290. return false;
  8291. case GGML_OP_UNARY:
  8292. switch (ggml_get_unary_op(node)) {
  8293. case GGML_UNARY_OP_SILU:
  8294. case GGML_UNARY_OP_GELU:
  8295. case GGML_UNARY_OP_GELU_ERF:
  8296. case GGML_UNARY_OP_GELU_QUICK:
  8297. case GGML_UNARY_OP_RELU:
  8298. case GGML_UNARY_OP_TANH:
  8299. case GGML_UNARY_OP_SIGMOID:
  8300. break;
  8301. default:
  8302. return false;
  8303. }
  8304. break;
  8305. case GGML_OP_GLU:
  8306. switch (ggml_get_glu_op(node)) {
  8307. case GGML_GLU_OP_GEGLU:
  8308. case GGML_GLU_OP_REGLU:
  8309. case GGML_GLU_OP_SWIGLU:
  8310. case GGML_GLU_OP_SWIGLU_OAI:
  8311. case GGML_GLU_OP_GEGLU_ERF:
  8312. case GGML_GLU_OP_GEGLU_QUICK:
  8313. break;
  8314. default:
  8315. return false;
  8316. }
  8317. break;
  8318. case GGML_OP_REPEAT:
  8319. case GGML_OP_REPEAT_BACK:
  8320. case GGML_OP_GET_ROWS:
  8321. case GGML_OP_ADD:
  8322. case GGML_OP_ADD_ID:
  8323. case GGML_OP_ACC:
  8324. case GGML_OP_SUB:
  8325. case GGML_OP_MUL:
  8326. case GGML_OP_DIV:
  8327. case GGML_OP_CONCAT:
  8328. case GGML_OP_UPSCALE:
  8329. case GGML_OP_SCALE:
  8330. case GGML_OP_SQR:
  8331. case GGML_OP_SIN:
  8332. case GGML_OP_COS:
  8333. case GGML_OP_CLAMP:
  8334. case GGML_OP_PAD:
  8335. case GGML_OP_ROLL:
  8336. case GGML_OP_CPY:
  8337. case GGML_OP_SET_ROWS:
  8338. case GGML_OP_CONT:
  8339. case GGML_OP_DUP:
  8340. case GGML_OP_SILU_BACK:
  8341. case GGML_OP_NORM:
  8342. case GGML_OP_GROUP_NORM:
  8343. case GGML_OP_RMS_NORM:
  8344. case GGML_OP_RMS_NORM_BACK:
  8345. case GGML_OP_L2_NORM:
  8346. case GGML_OP_DIAG_MASK_INF:
  8347. case GGML_OP_SOFT_MAX:
  8348. case GGML_OP_SOFT_MAX_BACK:
  8349. case GGML_OP_ROPE:
  8350. case GGML_OP_ROPE_BACK:
  8351. case GGML_OP_MUL_MAT:
  8352. case GGML_OP_MUL_MAT_ID:
  8353. case GGML_OP_ARGSORT:
  8354. case GGML_OP_SUM:
  8355. case GGML_OP_SUM_ROWS:
  8356. case GGML_OP_ARGMAX:
  8357. case GGML_OP_COUNT_EQUAL:
  8358. case GGML_OP_IM2COL:
  8359. case GGML_OP_TIMESTEP_EMBEDDING:
  8360. case GGML_OP_CONV_TRANSPOSE_1D:
  8361. case GGML_OP_POOL_2D:
  8362. case GGML_OP_CONV_2D:
  8363. case GGML_OP_CONV_2D_DW:
  8364. case GGML_OP_RWKV_WKV6:
  8365. case GGML_OP_RWKV_WKV7:
  8366. case GGML_OP_LEAKY_RELU:
  8367. case GGML_OP_FLASH_ATTN_EXT:
  8368. case GGML_OP_OPT_STEP_ADAMW:
  8369. case GGML_OP_OPT_STEP_SGD:
  8370. break;
  8371. default:
  8372. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(node->op) << std::endl;
  8373. GGML_ABORT("fatal error");
  8374. }
  8375. vk_context compute_ctx;
  8376. if (!dryrun) {
  8377. if (ctx->compute_ctx.expired()) {
  8378. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  8379. ctx->compute_ctx = compute_ctx;
  8380. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  8381. } else {
  8382. compute_ctx = ctx->compute_ctx.lock();
  8383. }
  8384. } else {
  8385. switch (node->op) {
  8386. case GGML_OP_REPEAT:
  8387. case GGML_OP_REPEAT_BACK:
  8388. case GGML_OP_ACC:
  8389. case GGML_OP_GET_ROWS:
  8390. case GGML_OP_ADD:
  8391. case GGML_OP_SUB:
  8392. case GGML_OP_MUL:
  8393. case GGML_OP_DIV:
  8394. case GGML_OP_CONCAT:
  8395. case GGML_OP_UPSCALE:
  8396. case GGML_OP_SCALE:
  8397. case GGML_OP_SQR:
  8398. case GGML_OP_SIN:
  8399. case GGML_OP_COS:
  8400. case GGML_OP_CLAMP:
  8401. case GGML_OP_PAD:
  8402. case GGML_OP_CPY:
  8403. case GGML_OP_SET_ROWS:
  8404. case GGML_OP_CONT:
  8405. case GGML_OP_DUP:
  8406. case GGML_OP_SILU_BACK:
  8407. case GGML_OP_NORM:
  8408. case GGML_OP_GROUP_NORM:
  8409. case GGML_OP_RMS_NORM:
  8410. case GGML_OP_RMS_NORM_BACK:
  8411. case GGML_OP_L2_NORM:
  8412. case GGML_OP_UNARY:
  8413. case GGML_OP_GLU:
  8414. case GGML_OP_DIAG_MASK_INF:
  8415. case GGML_OP_SOFT_MAX:
  8416. case GGML_OP_SOFT_MAX_BACK:
  8417. case GGML_OP_ROPE:
  8418. case GGML_OP_ROPE_BACK:
  8419. case GGML_OP_ARGSORT:
  8420. case GGML_OP_SUM:
  8421. case GGML_OP_SUM_ROWS:
  8422. case GGML_OP_ARGMAX:
  8423. case GGML_OP_COUNT_EQUAL:
  8424. case GGML_OP_IM2COL:
  8425. case GGML_OP_TIMESTEP_EMBEDDING:
  8426. case GGML_OP_CONV_TRANSPOSE_1D:
  8427. case GGML_OP_POOL_2D:
  8428. case GGML_OP_CONV_2D:
  8429. case GGML_OP_CONV_2D_DW:
  8430. case GGML_OP_LEAKY_RELU:
  8431. case GGML_OP_OPT_STEP_SGD:
  8432. {
  8433. // These operations all go through ggml_vk_op_f32, so short-circuit and
  8434. // do the only thing needed for the dryrun.
  8435. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, node, node->op);
  8436. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8437. return false;
  8438. }
  8439. default:
  8440. break;
  8441. }
  8442. }
  8443. switch (node->op) {
  8444. case GGML_OP_REPEAT:
  8445. ggml_vk_repeat(ctx, compute_ctx, src0, node, dryrun);
  8446. break;
  8447. case GGML_OP_REPEAT_BACK:
  8448. ggml_vk_repeat_back(ctx, compute_ctx, src0, node, dryrun);
  8449. break;
  8450. case GGML_OP_ACC:
  8451. ggml_vk_acc(ctx, compute_ctx, src0, src1, node, dryrun);
  8452. break;
  8453. case GGML_OP_GET_ROWS:
  8454. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node, dryrun);
  8455. break;
  8456. case GGML_OP_ADD:
  8457. if (ctx->num_additional_fused_ops) {
  8458. ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx, dryrun);
  8459. } else {
  8460. ggml_vk_add(ctx, compute_ctx, src0, src1, node, dryrun);
  8461. }
  8462. break;
  8463. case GGML_OP_SUB:
  8464. ggml_vk_sub(ctx, compute_ctx, src0, src1, node, dryrun);
  8465. break;
  8466. case GGML_OP_MUL:
  8467. ggml_vk_mul(ctx, compute_ctx, src0, src1, node, dryrun);
  8468. break;
  8469. case GGML_OP_DIV:
  8470. ggml_vk_div(ctx, compute_ctx, src0, src1, node, dryrun);
  8471. break;
  8472. case GGML_OP_ADD_ID:
  8473. ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  8474. break;
  8475. case GGML_OP_CONCAT:
  8476. ggml_vk_concat(ctx, compute_ctx, src0, src1, node, dryrun);
  8477. break;
  8478. case GGML_OP_UPSCALE:
  8479. ggml_vk_upscale(ctx, compute_ctx, src0, node, dryrun);
  8480. break;
  8481. case GGML_OP_SCALE:
  8482. ggml_vk_scale(ctx, compute_ctx, src0, node, dryrun);
  8483. break;
  8484. case GGML_OP_SQR:
  8485. ggml_vk_sqr(ctx, compute_ctx, src0, node, dryrun);
  8486. break;
  8487. case GGML_OP_SIN:
  8488. ggml_vk_sin(ctx, compute_ctx, src0, node, dryrun);
  8489. break;
  8490. case GGML_OP_COS:
  8491. ggml_vk_cos(ctx, compute_ctx, src0, node, dryrun);
  8492. break;
  8493. case GGML_OP_CLAMP:
  8494. ggml_vk_clamp(ctx, compute_ctx, src0, node, dryrun);
  8495. break;
  8496. case GGML_OP_PAD:
  8497. ggml_vk_pad(ctx, compute_ctx, src0, node, dryrun);
  8498. break;
  8499. case GGML_OP_ROLL:
  8500. ggml_vk_roll(ctx, compute_ctx, src0, node, dryrun);
  8501. break;
  8502. case GGML_OP_CPY:
  8503. case GGML_OP_CONT:
  8504. case GGML_OP_DUP:
  8505. ggml_vk_cpy(ctx, compute_ctx, src0, node, dryrun);
  8506. break;
  8507. case GGML_OP_SET_ROWS:
  8508. ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node, dryrun);
  8509. break;
  8510. case GGML_OP_SILU_BACK:
  8511. ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node, dryrun);
  8512. break;
  8513. case GGML_OP_NORM:
  8514. ggml_vk_norm(ctx, compute_ctx, src0, node, dryrun);
  8515. break;
  8516. case GGML_OP_GROUP_NORM:
  8517. ggml_vk_group_norm(ctx, compute_ctx, src0, node, dryrun);
  8518. break;
  8519. case GGML_OP_RMS_NORM:
  8520. if (ctx->num_additional_fused_ops > 0) {
  8521. // fused rms_norm + mul
  8522. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8523. ggml_tensor *other_src = mul->src[0] == node ? mul->src[1] : mul->src[0];
  8524. ggml_vk_rms_norm(ctx, compute_ctx, src0, other_src, mul, (float *)node->op_params, dryrun);
  8525. } else {
  8526. ggml_vk_rms_norm(ctx, compute_ctx, src0, src0, node, (float *)node->op_params, dryrun);
  8527. }
  8528. break;
  8529. case GGML_OP_RMS_NORM_BACK:
  8530. ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node, dryrun);
  8531. break;
  8532. case GGML_OP_L2_NORM:
  8533. ggml_vk_l2_norm(ctx, compute_ctx, src0, node, dryrun);
  8534. break;
  8535. case GGML_OP_UNARY:
  8536. switch (ggml_get_unary_op(node)) {
  8537. case GGML_UNARY_OP_SILU:
  8538. case GGML_UNARY_OP_GELU:
  8539. case GGML_UNARY_OP_GELU_ERF:
  8540. case GGML_UNARY_OP_GELU_QUICK:
  8541. case GGML_UNARY_OP_RELU:
  8542. case GGML_UNARY_OP_TANH:
  8543. case GGML_UNARY_OP_SIGMOID:
  8544. ggml_vk_unary(ctx, compute_ctx, src0, node, dryrun);
  8545. break;
  8546. default:
  8547. return false;
  8548. }
  8549. break;
  8550. case GGML_OP_GLU:
  8551. switch (ggml_get_glu_op(node)) {
  8552. case GGML_GLU_OP_GEGLU:
  8553. case GGML_GLU_OP_REGLU:
  8554. case GGML_GLU_OP_SWIGLU:
  8555. case GGML_GLU_OP_SWIGLU_OAI:
  8556. case GGML_GLU_OP_GEGLU_ERF:
  8557. case GGML_GLU_OP_GEGLU_QUICK:
  8558. ggml_vk_glu(ctx, compute_ctx, src0, src1, node, dryrun);
  8559. break;
  8560. default:
  8561. return false;
  8562. }
  8563. break;
  8564. case GGML_OP_DIAG_MASK_INF:
  8565. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node, dryrun);
  8566. break;
  8567. case GGML_OP_SOFT_MAX:
  8568. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  8569. break;
  8570. case GGML_OP_SOFT_MAX_BACK:
  8571. ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node, dryrun);
  8572. break;
  8573. case GGML_OP_ROPE:
  8574. ggml_vk_rope(ctx, compute_ctx, src0, src1, src2, node, false, dryrun);
  8575. break;
  8576. case GGML_OP_ROPE_BACK:
  8577. ggml_vk_rope(ctx, compute_ctx, src0, src1, src2, node, true, dryrun);
  8578. break;
  8579. case GGML_OP_ARGSORT:
  8580. ggml_vk_argsort(ctx, compute_ctx, src0, node, dryrun);
  8581. break;
  8582. case GGML_OP_SUM:
  8583. ggml_vk_sum(ctx, compute_ctx, src0, node, dryrun);
  8584. break;
  8585. case GGML_OP_SUM_ROWS:
  8586. ggml_vk_sum_rows(ctx, compute_ctx, src0, node, dryrun);
  8587. break;
  8588. case GGML_OP_ARGMAX:
  8589. ggml_vk_argmax(ctx, compute_ctx, src0, node, dryrun);
  8590. break;
  8591. case GGML_OP_COUNT_EQUAL:
  8592. ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node, dryrun);
  8593. break;
  8594. case GGML_OP_IM2COL:
  8595. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node, dryrun);
  8596. break;
  8597. case GGML_OP_TIMESTEP_EMBEDDING:
  8598. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node, dryrun);
  8599. break;
  8600. case GGML_OP_CONV_TRANSPOSE_1D:
  8601. ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node, dryrun);
  8602. break;
  8603. case GGML_OP_POOL_2D:
  8604. ggml_vk_pool_2d(ctx, compute_ctx, src0, node, dryrun);
  8605. break;
  8606. case GGML_OP_CONV_2D:
  8607. ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node, dryrun);
  8608. break;
  8609. case GGML_OP_CONV_2D_DW:
  8610. ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node, dryrun);
  8611. break;
  8612. case GGML_OP_LEAKY_RELU:
  8613. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node, dryrun);
  8614. break;
  8615. case GGML_OP_MUL_MAT:
  8616. ggml_vk_mul_mat(ctx, compute_ctx, src0, src1, node, dryrun);
  8617. break;
  8618. case GGML_OP_MUL_MAT_ID:
  8619. ggml_vk_mul_mat_id(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  8620. break;
  8621. case GGML_OP_FLASH_ATTN_EXT:
  8622. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node, dryrun);
  8623. break;
  8624. case GGML_OP_RWKV_WKV6:
  8625. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node, dryrun);
  8626. break;
  8627. case GGML_OP_RWKV_WKV7:
  8628. ggml_vk_rwkv_wkv7(ctx, compute_ctx, node, dryrun);
  8629. break;
  8630. case GGML_OP_OPT_STEP_ADAMW:
  8631. ggml_vk_opt_step_adamw(ctx, compute_ctx, node, dryrun);
  8632. break;
  8633. case GGML_OP_OPT_STEP_SGD:
  8634. ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node, dryrun);
  8635. break;
  8636. default:
  8637. return false;
  8638. }
  8639. if (dryrun) {
  8640. return false;
  8641. }
  8642. ctx->tensor_ctxs[node_idx] = compute_ctx;
  8643. #if defined(GGML_VULKAN_CHECK_RESULTS)
  8644. // Force context reset on each node so that each tensor ends up in its own context
  8645. // and can be run and compared to its CPU equivalent separately
  8646. last_node = true;
  8647. #endif
  8648. if (submit || last_node) {
  8649. ggml_vk_ctx_end(compute_ctx);
  8650. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  8651. if (last_node) {
  8652. compute_ctx->exit_tensor_idx = node_idx_begin;
  8653. }
  8654. else {
  8655. compute_ctx->exit_tensor_idx = -1;
  8656. }
  8657. ctx->compute_ctx.reset();
  8658. bool ok = ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, false, almost_ready);
  8659. if (!ok) {
  8660. if (node->op == GGML_OP_UNARY) {
  8661. 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;
  8662. } else if (node->op == GGML_OP_GLU) {
  8663. 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;
  8664. } else {
  8665. std::cerr << __func__ << ": error: op not supported " << node->name << " (" << ggml_op_name(node->op) << ")" << std::endl;
  8666. }
  8667. }
  8668. }
  8669. return true;
  8670. }
  8671. 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) {
  8672. GGML_UNUSED(cgraph);
  8673. ggml_backend_buffer * buf = nullptr;
  8674. switch (tensor->op) {
  8675. case GGML_OP_ADD:
  8676. case GGML_OP_ACC:
  8677. case GGML_OP_GET_ROWS:
  8678. case GGML_OP_SUB:
  8679. case GGML_OP_MUL:
  8680. case GGML_OP_DIV:
  8681. case GGML_OP_ADD_ID:
  8682. case GGML_OP_CONCAT:
  8683. case GGML_OP_UPSCALE:
  8684. case GGML_OP_SCALE:
  8685. case GGML_OP_SQR:
  8686. case GGML_OP_SIN:
  8687. case GGML_OP_COS:
  8688. case GGML_OP_CLAMP:
  8689. case GGML_OP_PAD:
  8690. case GGML_OP_ROLL:
  8691. case GGML_OP_CPY:
  8692. case GGML_OP_SET_ROWS:
  8693. case GGML_OP_CONT:
  8694. case GGML_OP_DUP:
  8695. case GGML_OP_SILU_BACK:
  8696. case GGML_OP_NORM:
  8697. case GGML_OP_GROUP_NORM:
  8698. case GGML_OP_RMS_NORM:
  8699. case GGML_OP_RMS_NORM_BACK:
  8700. case GGML_OP_L2_NORM:
  8701. case GGML_OP_DIAG_MASK_INF:
  8702. case GGML_OP_SOFT_MAX:
  8703. case GGML_OP_SOFT_MAX_BACK:
  8704. case GGML_OP_ROPE:
  8705. case GGML_OP_ROPE_BACK:
  8706. case GGML_OP_RESHAPE:
  8707. case GGML_OP_VIEW:
  8708. case GGML_OP_PERMUTE:
  8709. case GGML_OP_TRANSPOSE:
  8710. case GGML_OP_NONE:
  8711. case GGML_OP_ARGSORT:
  8712. case GGML_OP_SUM:
  8713. case GGML_OP_SUM_ROWS:
  8714. case GGML_OP_ARGMAX:
  8715. case GGML_OP_COUNT_EQUAL:
  8716. case GGML_OP_IM2COL:
  8717. case GGML_OP_TIMESTEP_EMBEDDING:
  8718. case GGML_OP_CONV_TRANSPOSE_1D:
  8719. case GGML_OP_POOL_2D:
  8720. case GGML_OP_CONV_2D:
  8721. case GGML_OP_CONV_2D_DW:
  8722. case GGML_OP_RWKV_WKV6:
  8723. case GGML_OP_RWKV_WKV7:
  8724. case GGML_OP_LEAKY_RELU:
  8725. case GGML_OP_REPEAT:
  8726. case GGML_OP_REPEAT_BACK:
  8727. case GGML_OP_OPT_STEP_ADAMW:
  8728. case GGML_OP_OPT_STEP_SGD:
  8729. buf = tensor->buffer;
  8730. break;
  8731. case GGML_OP_UNARY:
  8732. switch (ggml_get_unary_op(tensor)) {
  8733. case GGML_UNARY_OP_SILU:
  8734. case GGML_UNARY_OP_GELU:
  8735. case GGML_UNARY_OP_GELU_ERF:
  8736. case GGML_UNARY_OP_GELU_QUICK:
  8737. case GGML_UNARY_OP_RELU:
  8738. case GGML_UNARY_OP_TANH:
  8739. case GGML_UNARY_OP_SIGMOID:
  8740. buf = tensor->buffer;
  8741. break;
  8742. default:
  8743. return false;
  8744. }
  8745. break;
  8746. case GGML_OP_GLU:
  8747. switch (ggml_get_glu_op(tensor)) {
  8748. case GGML_GLU_OP_GEGLU:
  8749. case GGML_GLU_OP_REGLU:
  8750. case GGML_GLU_OP_SWIGLU:
  8751. case GGML_GLU_OP_SWIGLU_OAI:
  8752. case GGML_GLU_OP_GEGLU_ERF:
  8753. case GGML_GLU_OP_GEGLU_QUICK:
  8754. buf = tensor->buffer;
  8755. break;
  8756. default:
  8757. return false;
  8758. }
  8759. break;
  8760. case GGML_OP_MUL_MAT:
  8761. case GGML_OP_MUL_MAT_ID:
  8762. case GGML_OP_FLASH_ATTN_EXT:
  8763. buf = tensor->buffer;
  8764. break;
  8765. default:
  8766. return false;
  8767. }
  8768. if (buf == nullptr) {
  8769. return false;
  8770. }
  8771. 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 << ")");
  8772. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  8773. // always wait for the GPU work to be done for the last submit
  8774. if (tensor_idx == subctx->exit_tensor_idx) {
  8775. use_fence = true;
  8776. }
  8777. // Only run if ctx hasn't been submitted yet
  8778. if (!subctx->seqs.empty()) {
  8779. #ifdef GGML_VULKAN_CHECK_RESULTS
  8780. ggml_vk_check_results_0(ctx, cgraph, tensor_idx);
  8781. use_fence = true;
  8782. #endif
  8783. // Do staging buffer copies
  8784. for (auto& cpy : subctx->in_memcpys) {
  8785. memcpy(cpy.dst, cpy.src, cpy.n);
  8786. }
  8787. if (almost_ready && !ctx->almost_ready_fence_pending && !use_fence) {
  8788. ggml_vk_submit(subctx, ctx->almost_ready_fence);
  8789. ctx->almost_ready_fence_pending = true;
  8790. } else {
  8791. ggml_vk_submit(subctx, use_fence ? ctx->fence : vk::Fence{});
  8792. }
  8793. if (use_fence) {
  8794. ggml_vk_wait_for_fence(ctx);
  8795. }
  8796. #ifdef GGML_VULKAN_CHECK_RESULTS
  8797. ggml_vk_check_results_1(ctx, cgraph, tensor_idx);
  8798. #endif
  8799. }
  8800. if (tensor_idx == subctx->exit_tensor_idx) {
  8801. // Do staging buffer copies
  8802. for (auto& cpy : subctx->out_memcpys) {
  8803. memcpy(cpy.dst, cpy.src, cpy.n);
  8804. }
  8805. subctx->in_memcpys.clear();
  8806. subctx->out_memcpys.clear();
  8807. }
  8808. return true;
  8809. }
  8810. // Clean up after graph processing is done
  8811. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  8812. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  8813. for (auto& buffer : ctx->gc.temp_buffers) {
  8814. ggml_vk_pool_free(ctx, buffer);
  8815. }
  8816. ctx->gc.temp_buffers.clear();
  8817. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  8818. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  8819. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  8820. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  8821. }
  8822. ctx->gc.semaphores.clear();
  8823. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  8824. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  8825. }
  8826. ctx->gc.tl_semaphores.clear();
  8827. ctx->semaphore_idx = 0;
  8828. ctx->event_idx = 0;
  8829. for (auto& event : ctx->gc.events) {
  8830. ctx->device->device.resetEvent(event);
  8831. }
  8832. ctx->tensor_ctxs.clear();
  8833. ctx->gc.contexts.clear();
  8834. ctx->pipeline_descriptor_set_requirements = 0;
  8835. ctx->descriptor_set_idx = 0;
  8836. }
  8837. // Clean up on backend free
  8838. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  8839. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  8840. ggml_vk_graph_cleanup(ctx);
  8841. ggml_vk_destroy_buffer(ctx->prealloc_x);
  8842. ggml_vk_destroy_buffer(ctx->prealloc_y);
  8843. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  8844. for (auto& buffer : ctx->buffer_pool) {
  8845. ggml_vk_destroy_buffer(buffer);
  8846. }
  8847. ctx->prealloc_size_x = 0;
  8848. ctx->prealloc_size_y = 0;
  8849. ctx->prealloc_size_split_k = 0;
  8850. for (auto& event : ctx->gc.events) {
  8851. ctx->device->device.destroyEvent(event);
  8852. }
  8853. ctx->gc.events.clear();
  8854. ctx->device->device.destroyFence(ctx->fence);
  8855. ctx->device->device.destroyFence(ctx->almost_ready_fence);
  8856. for (auto& pool : ctx->descriptor_pools) {
  8857. ctx->device->device.destroyDescriptorPool(pool);
  8858. }
  8859. ctx->descriptor_pools.clear();
  8860. ctx->descriptor_sets.clear();
  8861. ctx->compute_cmd_pool.destroy(ctx->device->device);
  8862. ctx->transfer_cmd_pool.destroy(ctx->device->device);
  8863. }
  8864. static int ggml_vk_get_device_count() {
  8865. ggml_vk_instance_init();
  8866. return vk_instance.device_indices.size();
  8867. }
  8868. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  8869. ggml_vk_instance_init();
  8870. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  8871. vk::PhysicalDeviceProperties props;
  8872. devices[device].getProperties(&props);
  8873. snprintf(description, description_size, "%s", props.deviceName.data());
  8874. }
  8875. // backend interface
  8876. #define UNUSED GGML_UNUSED
  8877. // device backend
  8878. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  8879. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  8880. }
  8881. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  8882. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  8883. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  8884. ggml_vk_destroy_buffer(ctx->dev_buffer);
  8885. delete ctx;
  8886. }
  8887. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  8888. return vk_ptr_base;
  8889. UNUSED(buffer);
  8890. }
  8891. static enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  8892. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  8893. if (tensor->view_src != nullptr) {
  8894. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  8895. }
  8896. return GGML_STATUS_SUCCESS;
  8897. }
  8898. 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) {
  8899. VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")");
  8900. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  8901. vk_buffer buf = buf_ctx->dev_buffer;
  8902. uint32_t val32 = (uint32_t)value * 0x01010101;
  8903. ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size);
  8904. }
  8905. 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) {
  8906. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  8907. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  8908. vk_buffer buf = buf_ctx->dev_buffer;
  8909. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  8910. }
  8911. 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) {
  8912. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  8913. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  8914. vk_buffer buf = buf_ctx->dev_buffer;
  8915. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  8916. }
  8917. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  8918. if (ggml_backend_buffer_is_vk(src->buffer)) {
  8919. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  8920. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8921. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  8922. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  8923. 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));
  8924. return true;
  8925. }
  8926. return false;
  8927. UNUSED(buffer);
  8928. }
  8929. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  8930. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  8931. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  8932. }
  8933. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  8934. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  8935. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  8936. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  8937. /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor,
  8938. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  8939. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  8940. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  8941. /* .clear = */ ggml_backend_vk_buffer_clear,
  8942. /* .reset = */ NULL,
  8943. };
  8944. // vk buffer type
  8945. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  8946. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  8947. return ctx->name.c_str();
  8948. }
  8949. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  8950. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  8951. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  8952. vk_buffer dev_buffer = nullptr;
  8953. try {
  8954. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  8955. } catch (const vk::SystemError& e) {
  8956. return nullptr;
  8957. }
  8958. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  8959. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  8960. }
  8961. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  8962. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  8963. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  8964. }
  8965. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  8966. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  8967. return ctx->device->suballocation_block_size;
  8968. }
  8969. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  8970. return ggml_nbytes(tensor);
  8971. UNUSED(buft);
  8972. }
  8973. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  8974. ggml_vk_instance_init();
  8975. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  8976. vk_device dev = ggml_vk_get_device(dev_num);
  8977. return &dev->buffer_type;
  8978. }
  8979. // host buffer type
  8980. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  8981. return GGML_VK_NAME "_Host";
  8982. UNUSED(buft);
  8983. }
  8984. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  8985. return GGML_VK_NAME "_Host";
  8986. UNUSED(buffer);
  8987. }
  8988. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  8989. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  8990. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  8991. }
  8992. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  8993. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  8994. size += 32; // Behave like the CPU buffer type
  8995. void * ptr = nullptr;
  8996. try {
  8997. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  8998. } catch (vk::SystemError& e) {
  8999. GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory (%s)\n", e.what());
  9000. // fallback to cpu buffer
  9001. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  9002. }
  9003. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  9004. buffer->buft = buft;
  9005. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  9006. return buffer;
  9007. UNUSED(buft);
  9008. }
  9009. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  9010. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  9011. UNUSED(buft);
  9012. }
  9013. static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  9014. return vk_instance.devices[0]->suballocation_block_size;
  9015. UNUSED(buft);
  9016. }
  9017. // Should be changed to return device-specific host buffer type
  9018. // but that probably requires changes in llama.cpp
  9019. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  9020. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  9021. /* .iface = */ {
  9022. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  9023. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  9024. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  9025. /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size,
  9026. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  9027. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  9028. },
  9029. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  9030. /* .context = */ nullptr,
  9031. };
  9032. // Make sure device 0 is initialized
  9033. ggml_vk_instance_init();
  9034. ggml_vk_get_device(0);
  9035. return &ggml_backend_vk_buffer_type_host;
  9036. }
  9037. // backend
  9038. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  9039. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  9040. return ctx->name.c_str();
  9041. }
  9042. static void ggml_backend_vk_free(ggml_backend_t backend) {
  9043. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  9044. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  9045. ggml_vk_cleanup(ctx);
  9046. delete ctx;
  9047. delete backend;
  9048. }
  9049. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  9050. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  9051. return &ctx->device->buffer_type;
  9052. }
  9053. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  9054. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  9055. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  9056. 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");
  9057. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  9058. vk_context transfer_ctx;
  9059. if (ctx->transfer_ctx.expired()) {
  9060. // Initialize new transfer context
  9061. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  9062. ctx->transfer_ctx = transfer_ctx;
  9063. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  9064. } else {
  9065. transfer_ctx = ctx->transfer_ctx.lock();
  9066. }
  9067. vk_buffer buf = buf_ctx->dev_buffer;
  9068. ggml_vk_buffer_write_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  9069. }
  9070. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  9071. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  9072. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  9073. 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");
  9074. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  9075. vk_context transfer_ctx;
  9076. if (ctx->transfer_ctx.expired()) {
  9077. // Initialize new transfer context
  9078. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  9079. ctx->transfer_ctx = transfer_ctx;
  9080. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  9081. } else {
  9082. transfer_ctx = ctx->transfer_ctx.lock();
  9083. }
  9084. vk_buffer buf = buf_ctx->dev_buffer;
  9085. ggml_vk_buffer_read_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  9086. }
  9087. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  9088. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  9089. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  9090. 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)) {
  9091. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  9092. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  9093. vk_context transfer_ctx;
  9094. if (ctx->transfer_ctx.expired()) {
  9095. // Initialize new transfer context
  9096. transfer_ctx = ggml_vk_create_context(ctx, ctx->transfer_cmd_pool);
  9097. ctx->transfer_ctx = transfer_ctx;
  9098. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  9099. } else {
  9100. transfer_ctx = ctx->transfer_ctx.lock();
  9101. }
  9102. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  9103. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  9104. 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));
  9105. return true;
  9106. }
  9107. return false;
  9108. }
  9109. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  9110. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  9111. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  9112. if(ctx->transfer_ctx.expired()) {
  9113. return;
  9114. }
  9115. vk_context transfer_ctx = ctx->transfer_ctx.lock();
  9116. ggml_vk_ctx_end(transfer_ctx);
  9117. for (auto& cpy : transfer_ctx->in_memcpys) {
  9118. memcpy(cpy.dst, cpy.src, cpy.n);
  9119. }
  9120. ggml_vk_submit(transfer_ctx, ctx->fence);
  9121. ggml_vk_wait_for_fence(ctx);
  9122. for (auto& cpy : transfer_ctx->out_memcpys) {
  9123. memcpy(cpy.dst, cpy.src, cpy.n);
  9124. }
  9125. ctx->transfer_ctx.reset();
  9126. }
  9127. static bool ggml_vk_is_empty(ggml_tensor * node) {
  9128. 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;
  9129. }
  9130. static bool ggml_vk_can_fuse(const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list<enum ggml_op> ops) {
  9131. if (!ggml_can_fuse(cgraph, node_idx, ops)) {
  9132. return false;
  9133. }
  9134. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
  9135. // additional constraints specific to this fusion
  9136. const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
  9137. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  9138. GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
  9139. GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
  9140. // rms_norm only supports f32
  9141. if (mul->src[0]->type != GGML_TYPE_F32 ||
  9142. mul->src[1]->type != GGML_TYPE_F32 ||
  9143. mul->type != GGML_TYPE_F32) {
  9144. return false;
  9145. }
  9146. // if rms_norm is the B operand, then we don't handle broadcast
  9147. if (rms_norm == mul->src[1] &&
  9148. !ggml_are_same_shape(mul->src[0], rms_norm)) {
  9149. return false;
  9150. }
  9151. // rms_norm shader assumes contiguous rows
  9152. if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
  9153. return false;
  9154. }
  9155. }
  9156. return true;
  9157. }
  9158. static uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) {
  9159. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  9160. if (first_node->op != GGML_OP_ADD) {
  9161. return 0;
  9162. }
  9163. if (!ctx->device->multi_add) {
  9164. return 0;
  9165. }
  9166. int32_t num_adds = 1;
  9167. while (node_idx + num_adds < cgraph->n_nodes &&
  9168. cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD &&
  9169. num_adds < MAX_FUSED_ADDS) {
  9170. num_adds++;
  9171. }
  9172. // The shader currently requires same shapes (but different strides are allowed),
  9173. // everything f32, and no misalignment
  9174. for (int32_t i = 0; i < num_adds; ++i) {
  9175. const ggml_tensor *next_node = cgraph->nodes[node_idx + i];
  9176. if (!ggml_are_same_shape(first_node, next_node->src[0]) ||
  9177. !ggml_are_same_shape(first_node, next_node->src[1]) ||
  9178. next_node->type != GGML_TYPE_F32 ||
  9179. next_node->src[0]->type != GGML_TYPE_F32 ||
  9180. next_node->src[1]->type != GGML_TYPE_F32 ||
  9181. get_misalign_bytes(ctx, next_node) ||
  9182. get_misalign_bytes(ctx, next_node->src[0]) ||
  9183. get_misalign_bytes(ctx, next_node->src[1])) {
  9184. num_adds = i;
  9185. }
  9186. }
  9187. // Verify we can fuse these
  9188. ggml_op adds[MAX_FUSED_ADDS];
  9189. for (int32_t i = 0; i < num_adds; ++i) {
  9190. adds[i] = GGML_OP_ADD;
  9191. }
  9192. // decrease num_adds if they can't all be fused
  9193. while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) {
  9194. num_adds--;
  9195. }
  9196. // a single add is not "fused", so just return zero
  9197. if (num_adds == 1) {
  9198. return 0;
  9199. }
  9200. return num_adds;
  9201. }
  9202. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  9203. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  9204. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  9205. if (vk_instance.debug_utils_support) {
  9206. vk::DebugUtilsLabelEXT dul = {};
  9207. dul.pLabelName = "ggml_backend_vk_graph_compute";
  9208. dul.color = std::array<float,4>{1.0f, 1.0f, 1.0f, 1.0f};
  9209. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(ctx->device->compute_queue.queue, reinterpret_cast<VkDebugUtilsLabelEXT*>(&dul));
  9210. }
  9211. uint64_t total_mat_mul_bytes = 0;
  9212. for (int i = 0; i < cgraph->n_nodes; i++) {
  9213. if (!ctx->device->disable_fusion) {
  9214. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  9215. if (num_adds) {
  9216. ctx->num_additional_fused_ops = num_adds - 1;
  9217. } else if (ggml_vk_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  9218. ctx->num_additional_fused_ops = 1;
  9219. }
  9220. }
  9221. ggml_vk_build_graph(ctx, cgraph, i, nullptr, 0, true, false, false, false);
  9222. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  9223. total_mat_mul_bytes += ggml_nbytes(cgraph->nodes[i]->src[0]);
  9224. } else if (cgraph->nodes[i]->op == GGML_OP_CONV_2D) {
  9225. // Return CRSxNPQxsizeof(*) to account as many bytes as mul_mat has in im2col->mul_mat mode.
  9226. auto CRS_size =
  9227. cgraph->nodes[i]->src[0]->ne[0] * cgraph->nodes[i]->src[0]->ne[1] * cgraph->nodes[i]->src[0]->ne[2];
  9228. auto NPQ_size = cgraph->nodes[i]->ne[0] * cgraph->nodes[i]->ne[1] * cgraph->nodes[i]->ne[3];
  9229. total_mat_mul_bytes += NPQ_size * CRS_size * ggml_type_size(cgraph->nodes[i]->type);
  9230. }
  9231. i += ctx->num_additional_fused_ops;
  9232. ctx->num_additional_fused_ops = 0;
  9233. }
  9234. if (ctx->device->need_compiles) {
  9235. ggml_vk_load_shaders(ctx->device);
  9236. }
  9237. ggml_vk_preallocate_buffers(ctx);
  9238. ggml_pipeline_allocate_descriptor_sets(ctx);
  9239. int last_node = cgraph->n_nodes - 1;
  9240. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  9241. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  9242. last_node -= 1;
  9243. }
  9244. // Reserve tensor context space for all nodes
  9245. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  9246. bool first_node_in_batch = true; // true if next node will be first node in a batch
  9247. int submit_node_idx = 0; // index to first node in a batch
  9248. vk_context compute_ctx;
  9249. if (vk_perf_logger_enabled) {
  9250. // allocate/resize the query pool
  9251. if (ctx->device->num_queries < cgraph->n_nodes + 1) {
  9252. if (ctx->device->query_pool) {
  9253. ctx->device->device.destroyQueryPool(ctx->device->query_pool);
  9254. }
  9255. vk::QueryPoolCreateInfo query_create_info;
  9256. query_create_info.queryType = vk::QueryType::eTimestamp;
  9257. query_create_info.queryCount = cgraph->n_nodes + 100;
  9258. ctx->device->query_pool = ctx->device->device.createQueryPool(query_create_info);
  9259. ctx->device->num_queries = query_create_info.queryCount;
  9260. }
  9261. ctx->device->device.resetQueryPool(ctx->device->query_pool, 0, cgraph->n_nodes+1);
  9262. GGML_ASSERT(ctx->compute_ctx.expired());
  9263. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9264. ctx->compute_ctx = compute_ctx;
  9265. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  9266. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, 0);
  9267. }
  9268. // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution.
  9269. // Estimate the amount of matmul work by looking at the weight matrix size, and submit every 100MB
  9270. // (and scaled down based on model size, so smaller models submit earlier).
  9271. // Also submit at least every 100 nodes, in case there are workloads without as much matmul.
  9272. int nodes_per_submit = 100;
  9273. int submitted_nodes = 0;
  9274. int submit_count = 0;
  9275. uint64_t mul_mat_bytes = 0;
  9276. uint64_t mul_mat_bytes_per_submit = std::min(uint64_t(100*1000*1000), total_mat_mul_bytes / 40u);
  9277. for (int i = 0; i < cgraph->n_nodes; i++) {
  9278. if (first_node_in_batch) {
  9279. submit_node_idx = i;
  9280. }
  9281. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  9282. mul_mat_bytes += ggml_nbytes(cgraph->nodes[i]->src[0]);
  9283. }
  9284. if (!ctx->device->disable_fusion) {
  9285. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  9286. if (num_adds) {
  9287. ctx->num_additional_fused_ops = num_adds - 1;
  9288. } else if (ggml_vk_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  9289. ctx->num_additional_fused_ops = 1;
  9290. }
  9291. }
  9292. // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining)
  9293. bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5;
  9294. bool submit = (submitted_nodes >= nodes_per_submit) ||
  9295. (mul_mat_bytes >= mul_mat_bytes_per_submit) ||
  9296. (i + ctx->num_additional_fused_ops == last_node) ||
  9297. (almost_ready && !ctx->almost_ready_fence_pending);
  9298. 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);
  9299. if (vk_perf_logger_enabled) {
  9300. if (ctx->compute_ctx.expired()) {
  9301. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9302. ctx->compute_ctx = compute_ctx;
  9303. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  9304. } else {
  9305. compute_ctx = ctx->compute_ctx.lock();
  9306. }
  9307. // If there are fused ops, just write out timestamps for all nodes to keep the accounting simple
  9308. for (int j = 0; j < ctx->num_additional_fused_ops + 1; ++j) {
  9309. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, i+j+1);
  9310. }
  9311. }
  9312. if (enqueued) {
  9313. ++submitted_nodes;
  9314. #ifndef GGML_VULKAN_CHECK_RESULTS
  9315. if (first_node_in_batch) {
  9316. first_node_in_batch = false;
  9317. }
  9318. #endif
  9319. }
  9320. if (submit && enqueued) {
  9321. first_node_in_batch = true;
  9322. submitted_nodes = 0;
  9323. mul_mat_bytes = 0;
  9324. if (submit_count < 3) {
  9325. mul_mat_bytes_per_submit *= 2;
  9326. }
  9327. submit_count++;
  9328. }
  9329. i += ctx->num_additional_fused_ops;
  9330. ctx->num_additional_fused_ops = 0;
  9331. }
  9332. if (vk_perf_logger_enabled) {
  9333. // End the command buffer and submit/wait
  9334. GGML_ASSERT(!ctx->compute_ctx.expired());
  9335. compute_ctx = ctx->compute_ctx.lock();
  9336. ggml_vk_ctx_end(compute_ctx);
  9337. ggml_vk_submit(compute_ctx, ctx->device->fence);
  9338. VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences");
  9339. ctx->device->device.resetFences({ ctx->device->fence });
  9340. // Get the results and pass them to the logger
  9341. std::vector<uint64_t> timestamps(cgraph->n_nodes + 1);
  9342. 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");
  9343. for (int i = 0; i < cgraph->n_nodes; i++) {
  9344. if (!ggml_vk_is_empty(cgraph->nodes[i])) {
  9345. ctx->device->perf_logger->log_timing(cgraph->nodes[i], uint64_t((timestamps[i+1] - timestamps[i]) * ctx->device->properties.limits.timestampPeriod));
  9346. }
  9347. }
  9348. ctx->device->perf_logger->print_timings();
  9349. }
  9350. ggml_vk_graph_cleanup(ctx);
  9351. return GGML_STATUS_SUCCESS;
  9352. UNUSED(backend);
  9353. }
  9354. // TODO: enable async and synchronize
  9355. static ggml_backend_i ggml_backend_vk_interface = {
  9356. /* .get_name = */ ggml_backend_vk_name,
  9357. /* .free = */ ggml_backend_vk_free,
  9358. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  9359. /* .get_tensor_async = */ NULL, // ggml_backend_vk_get_tensor_async,
  9360. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  9361. /* .synchronize = */ NULL, // ggml_backend_vk_synchronize,
  9362. /* .graph_plan_create = */ NULL,
  9363. /* .graph_plan_free = */ NULL,
  9364. /* .graph_plan_update = */ NULL,
  9365. /* .graph_plan_compute = */ NULL,
  9366. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  9367. /* .event_record = */ NULL,
  9368. /* .event_wait = */ NULL,
  9369. };
  9370. static ggml_guid_t ggml_backend_vk_guid() {
  9371. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  9372. return &guid;
  9373. }
  9374. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  9375. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  9376. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  9377. ggml_vk_init(ctx, dev_num);
  9378. ggml_backend_t vk_backend = new ggml_backend {
  9379. /* .guid = */ ggml_backend_vk_guid(),
  9380. /* .iface = */ ggml_backend_vk_interface,
  9381. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  9382. /* .context = */ ctx,
  9383. };
  9384. return vk_backend;
  9385. }
  9386. bool ggml_backend_is_vk(ggml_backend_t backend) {
  9387. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  9388. }
  9389. int ggml_backend_vk_get_device_count() {
  9390. return ggml_vk_get_device_count();
  9391. }
  9392. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  9393. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  9394. int dev_idx = vk_instance.device_indices[device];
  9395. ggml_vk_get_device_description(dev_idx, description, description_size);
  9396. }
  9397. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  9398. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  9399. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  9400. vk::PhysicalDeviceMemoryProperties memprops = vkdev.getMemoryProperties();
  9401. for (const vk::MemoryHeap& heap : memprops.memoryHeaps) {
  9402. if (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal) {
  9403. *total = heap.size;
  9404. *free = heap.size;
  9405. break;
  9406. }
  9407. }
  9408. }
  9409. //////////////////////////
  9410. struct ggml_backend_vk_device_context {
  9411. size_t device;
  9412. std::string name;
  9413. std::string description;
  9414. };
  9415. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  9416. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  9417. return ctx->name.c_str();
  9418. }
  9419. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  9420. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  9421. return ctx->description.c_str();
  9422. }
  9423. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  9424. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  9425. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  9426. }
  9427. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  9428. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  9429. return ggml_backend_vk_buffer_type(ctx->device);
  9430. }
  9431. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  9432. UNUSED(dev);
  9433. return ggml_backend_vk_host_buffer_type();
  9434. }
  9435. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  9436. UNUSED(dev);
  9437. return GGML_BACKEND_DEVICE_TYPE_GPU;
  9438. }
  9439. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  9440. props->name = ggml_backend_vk_device_get_name(dev);
  9441. props->description = ggml_backend_vk_device_get_description(dev);
  9442. props->type = ggml_backend_vk_device_get_type(dev);
  9443. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  9444. props->caps = {
  9445. /* .async = */ false,
  9446. /* .host_buffer = */ true,
  9447. /* .buffer_from_host_ptr = */ false,
  9448. /* .events = */ false,
  9449. };
  9450. }
  9451. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  9452. UNUSED(params);
  9453. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  9454. return ggml_backend_vk_init(ctx->device);
  9455. }
  9456. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  9457. switch (op->op) {
  9458. case GGML_OP_UNARY:
  9459. switch (ggml_get_unary_op(op)) {
  9460. case GGML_UNARY_OP_GELU:
  9461. case GGML_UNARY_OP_GELU_ERF:
  9462. case GGML_UNARY_OP_GELU_QUICK:
  9463. case GGML_UNARY_OP_SILU:
  9464. case GGML_UNARY_OP_RELU:
  9465. case GGML_UNARY_OP_TANH:
  9466. case GGML_UNARY_OP_SIGMOID:
  9467. return ggml_is_contiguous(op->src[0]) &&
  9468. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  9469. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  9470. (op->src[0]->type == op->type);
  9471. default:
  9472. return false;
  9473. }
  9474. case GGML_OP_GLU:
  9475. switch (ggml_get_glu_op(op)) {
  9476. case GGML_GLU_OP_GEGLU:
  9477. case GGML_GLU_OP_REGLU:
  9478. case GGML_GLU_OP_SWIGLU:
  9479. case GGML_GLU_OP_SWIGLU_OAI:
  9480. case GGML_GLU_OP_GEGLU_ERF:
  9481. case GGML_GLU_OP_GEGLU_QUICK:
  9482. return ggml_is_contiguous(op->src[0]) &&
  9483. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  9484. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  9485. (op->src[0]->type == op->type);
  9486. default:
  9487. return false;
  9488. }
  9489. case GGML_OP_MUL_MAT:
  9490. case GGML_OP_MUL_MAT_ID:
  9491. {
  9492. ggml_type src0_type = op->src[0]->type;
  9493. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  9494. const vk_device& device = ggml_vk_get_device(ctx->device);
  9495. if (op->op == GGML_OP_MUL_MAT_ID) {
  9496. if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) {
  9497. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  9498. return false;
  9499. }
  9500. }
  9501. switch (src0_type) {
  9502. case GGML_TYPE_F32:
  9503. case GGML_TYPE_F16:
  9504. case GGML_TYPE_BF16:
  9505. case GGML_TYPE_Q4_0:
  9506. case GGML_TYPE_Q4_1:
  9507. case GGML_TYPE_Q5_0:
  9508. case GGML_TYPE_Q5_1:
  9509. case GGML_TYPE_Q8_0:
  9510. case GGML_TYPE_Q2_K:
  9511. case GGML_TYPE_Q3_K:
  9512. case GGML_TYPE_Q4_K:
  9513. case GGML_TYPE_Q5_K:
  9514. case GGML_TYPE_Q6_K:
  9515. case GGML_TYPE_IQ1_S:
  9516. case GGML_TYPE_IQ1_M:
  9517. case GGML_TYPE_IQ2_XXS:
  9518. case GGML_TYPE_IQ2_XS:
  9519. case GGML_TYPE_IQ2_S:
  9520. case GGML_TYPE_IQ3_XXS:
  9521. case GGML_TYPE_IQ3_S:
  9522. case GGML_TYPE_IQ4_XS:
  9523. case GGML_TYPE_IQ4_NL:
  9524. case GGML_TYPE_MXFP4:
  9525. break;
  9526. default:
  9527. return false;
  9528. }
  9529. struct ggml_tensor * a;
  9530. struct ggml_tensor * b;
  9531. if (op->op == GGML_OP_MUL_MAT) {
  9532. a = op->src[0];
  9533. b = op->src[1];
  9534. } else {
  9535. a = op->src[2];
  9536. b = op->src[1];
  9537. }
  9538. if (a->ne[3] != b->ne[3]) {
  9539. return false;
  9540. }
  9541. 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) ||
  9542. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  9543. return false;
  9544. }
  9545. if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) {
  9546. // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader.
  9547. // So don't support this combination for now.
  9548. return false;
  9549. }
  9550. return true;
  9551. }
  9552. case GGML_OP_FLASH_ATTN_EXT:
  9553. {
  9554. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  9555. auto device = ggml_vk_get_device(ctx->device);
  9556. bool coopmat2 = device->coopmat2;
  9557. FaHeadSizes head_sizes = fa_get_head_sizes(op->src[1]->ne[0], op->src[2]->ne[0]);
  9558. if (head_sizes == FA_HEAD_SIZE_UNSUPPORTED) {
  9559. return false;
  9560. }
  9561. if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) {
  9562. return false;
  9563. }
  9564. if (op->src[0]->type != GGML_TYPE_F32) {
  9565. return false;
  9566. }
  9567. if (op->type != GGML_TYPE_F32) {
  9568. return false;
  9569. }
  9570. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  9571. return false;
  9572. }
  9573. // It's straightforward to support different K/V dequant, but would
  9574. // significantly increase the number of pipelines
  9575. if (op->src[1]->type != op->src[2]->type) {
  9576. return false;
  9577. }
  9578. switch (op->src[1]->type) {
  9579. case GGML_TYPE_F16:
  9580. case GGML_TYPE_Q4_0:
  9581. case GGML_TYPE_Q8_0:
  9582. // supported in scalar and coopmat2 paths
  9583. break;
  9584. case GGML_TYPE_Q4_1:
  9585. case GGML_TYPE_Q5_0:
  9586. case GGML_TYPE_Q5_1:
  9587. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  9588. //case GGML_TYPE_Q2_K:
  9589. //case GGML_TYPE_Q3_K:
  9590. //case GGML_TYPE_Q4_K:
  9591. //case GGML_TYPE_Q5_K:
  9592. //case GGML_TYPE_Q6_K:
  9593. //case GGML_TYPE_IQ1_S:
  9594. //case GGML_TYPE_IQ1_M:
  9595. //case GGML_TYPE_IQ2_XXS:
  9596. //case GGML_TYPE_IQ2_XS:
  9597. //case GGML_TYPE_IQ2_S:
  9598. //case GGML_TYPE_IQ3_XXS:
  9599. //case GGML_TYPE_IQ3_S:
  9600. //case GGML_TYPE_IQ4_XS:
  9601. case GGML_TYPE_IQ4_NL:
  9602. // currently supported only in coopmat2 path
  9603. if (!coopmat2) {
  9604. return false;
  9605. }
  9606. break;
  9607. default:
  9608. return false;
  9609. }
  9610. if (!coopmat2 && !device->subgroup_shuffle) {
  9611. // scalar FA uses subgroupShuffle
  9612. return false;
  9613. }
  9614. return true;
  9615. }
  9616. case GGML_OP_GET_ROWS:
  9617. {
  9618. switch (op->src[0]->type) {
  9619. case GGML_TYPE_F32:
  9620. case GGML_TYPE_F16:
  9621. case GGML_TYPE_BF16:
  9622. case GGML_TYPE_Q4_0:
  9623. case GGML_TYPE_Q4_1:
  9624. case GGML_TYPE_Q5_0:
  9625. case GGML_TYPE_Q5_1:
  9626. case GGML_TYPE_Q8_0:
  9627. case GGML_TYPE_IQ1_S:
  9628. case GGML_TYPE_IQ1_M:
  9629. case GGML_TYPE_IQ2_XXS:
  9630. case GGML_TYPE_IQ2_XS:
  9631. case GGML_TYPE_IQ2_S:
  9632. case GGML_TYPE_IQ3_XXS:
  9633. case GGML_TYPE_IQ3_S:
  9634. case GGML_TYPE_IQ4_XS:
  9635. case GGML_TYPE_IQ4_NL:
  9636. case GGML_TYPE_MXFP4:
  9637. return true;
  9638. default:
  9639. return false;
  9640. }
  9641. }
  9642. case GGML_OP_SET_ROWS:
  9643. {
  9644. switch (op->type) {
  9645. case GGML_TYPE_F32:
  9646. case GGML_TYPE_F16:
  9647. case GGML_TYPE_BF16:
  9648. case GGML_TYPE_Q4_0:
  9649. case GGML_TYPE_Q4_1:
  9650. case GGML_TYPE_Q5_0:
  9651. case GGML_TYPE_Q5_1:
  9652. case GGML_TYPE_Q8_0:
  9653. case GGML_TYPE_IQ4_NL:
  9654. return true;
  9655. default:
  9656. return false;
  9657. }
  9658. }
  9659. case GGML_OP_CONT:
  9660. case GGML_OP_CPY:
  9661. case GGML_OP_DUP:
  9662. {
  9663. ggml_type src0_type = op->src[0]->type;
  9664. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  9665. if (src0_type == GGML_TYPE_F32) {
  9666. switch (src1_type) {
  9667. case GGML_TYPE_F32:
  9668. case GGML_TYPE_F16:
  9669. case GGML_TYPE_BF16:
  9670. case GGML_TYPE_Q4_0:
  9671. case GGML_TYPE_Q4_1:
  9672. case GGML_TYPE_Q5_0:
  9673. case GGML_TYPE_Q5_1:
  9674. case GGML_TYPE_Q8_0:
  9675. case GGML_TYPE_IQ4_NL:
  9676. return true;
  9677. default:
  9678. break;
  9679. }
  9680. }
  9681. if (src1_type == GGML_TYPE_F32) {
  9682. switch (src0_type) {
  9683. case GGML_TYPE_F16:
  9684. case GGML_TYPE_Q4_0:
  9685. case GGML_TYPE_Q4_1:
  9686. case GGML_TYPE_Q5_0:
  9687. case GGML_TYPE_Q5_1:
  9688. case GGML_TYPE_Q8_0:
  9689. case GGML_TYPE_IQ4_NL:
  9690. return true;
  9691. default:
  9692. break;
  9693. }
  9694. }
  9695. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  9696. return true;
  9697. }
  9698. // We can handle copying from a type to the same type if it's
  9699. // contiguous (memcpy). We use f16 or f32 shaders to do the copy,
  9700. // so the type/block size must be a multiple of 4.
  9701. if (src0_type == src1_type &&
  9702. ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op) &&
  9703. (ggml_type_size(src0_type) % 2) == 0) {
  9704. return true;
  9705. }
  9706. return false;
  9707. }
  9708. case GGML_OP_REPEAT:
  9709. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  9710. case GGML_OP_REPEAT_BACK:
  9711. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32;
  9712. case GGML_OP_ROPE:
  9713. case GGML_OP_ROPE_BACK:
  9714. case GGML_OP_NONE:
  9715. case GGML_OP_RESHAPE:
  9716. case GGML_OP_VIEW:
  9717. case GGML_OP_PERMUTE:
  9718. case GGML_OP_TRANSPOSE:
  9719. case GGML_OP_RMS_NORM:
  9720. return true;
  9721. case GGML_OP_NORM:
  9722. case GGML_OP_GROUP_NORM:
  9723. case GGML_OP_L2_NORM:
  9724. return ggml_is_contiguous(op->src[0]);
  9725. case GGML_OP_ADD:
  9726. case GGML_OP_SUB:
  9727. case GGML_OP_MUL:
  9728. case GGML_OP_DIV:
  9729. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  9730. (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
  9731. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  9732. case GGML_OP_ADD_ID:
  9733. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 &&
  9734. op->type == GGML_TYPE_F32;
  9735. case GGML_OP_SILU_BACK:
  9736. case GGML_OP_RMS_NORM_BACK:
  9737. case GGML_OP_SQR:
  9738. case GGML_OP_SIN:
  9739. case GGML_OP_COS:
  9740. case GGML_OP_CLAMP:
  9741. case GGML_OP_LEAKY_RELU:
  9742. case GGML_OP_OPT_STEP_ADAMW:
  9743. case GGML_OP_OPT_STEP_SGD:
  9744. return op->src[0]->type == GGML_TYPE_F32;
  9745. case GGML_OP_ARGSORT:
  9746. return op->ne[0] <= max_argsort_cols;
  9747. case GGML_OP_UPSCALE:
  9748. case GGML_OP_ACC:
  9749. case GGML_OP_CONCAT:
  9750. case GGML_OP_SCALE:
  9751. case GGML_OP_PAD:
  9752. case GGML_OP_ROLL:
  9753. case GGML_OP_DIAG_MASK_INF:
  9754. case GGML_OP_SOFT_MAX:
  9755. case GGML_OP_SOFT_MAX_BACK:
  9756. case GGML_OP_SUM:
  9757. case GGML_OP_SUM_ROWS:
  9758. case GGML_OP_ARGMAX:
  9759. case GGML_OP_COUNT_EQUAL:
  9760. case GGML_OP_IM2COL:
  9761. case GGML_OP_TIMESTEP_EMBEDDING:
  9762. case GGML_OP_CONV_2D_DW:
  9763. case GGML_OP_POOL_2D:
  9764. case GGML_OP_RWKV_WKV6:
  9765. case GGML_OP_RWKV_WKV7:
  9766. return true;
  9767. case GGML_OP_CONV_TRANSPOSE_1D:
  9768. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  9769. case GGML_OP_CONV_2D:
  9770. {
  9771. // Op is disabled for Apple because it segfaults at pipeline create time on MoltenVK
  9772. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  9773. const vk_device& device = ggml_vk_get_device(ctx->device);
  9774. bool is_Apple = ggml_vk_get_device(ctx->device)->vendor_id == VK_VENDOR_ID_APPLE;
  9775. // Channel-contiguous format is not supported yet.
  9776. return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  9777. op->src[1]->type == GGML_TYPE_F32 &&
  9778. op->type == GGML_TYPE_F32 &&
  9779. ggml_is_contiguous(op->src[0]) &&
  9780. ggml_is_contiguous(op->src[1]) &&
  9781. ggml_is_contiguous(op)) && !is_Apple;
  9782. }
  9783. default:
  9784. return false;
  9785. }
  9786. UNUSED(dev);
  9787. }
  9788. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  9789. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  9790. return false;
  9791. }
  9792. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  9793. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  9794. return buft_ctx->device->idx == ctx->device;
  9795. }
  9796. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  9797. const int min_batch_size = 32;
  9798. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  9799. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  9800. UNUSED(dev);
  9801. }
  9802. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  9803. /* .get_name = */ ggml_backend_vk_device_get_name,
  9804. /* .get_description = */ ggml_backend_vk_device_get_description,
  9805. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  9806. /* .get_type = */ ggml_backend_vk_device_get_type,
  9807. /* .get_props = */ ggml_backend_vk_device_get_props,
  9808. /* .init_backend = */ ggml_backend_vk_device_init,
  9809. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  9810. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  9811. /* .buffer_from_host_ptr = */ NULL,
  9812. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  9813. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  9814. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  9815. /* .event_new = */ NULL,
  9816. /* .event_free = */ NULL,
  9817. /* .event_synchronize = */ NULL,
  9818. };
  9819. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  9820. UNUSED(reg);
  9821. return GGML_VK_NAME;
  9822. }
  9823. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  9824. UNUSED(reg);
  9825. return ggml_backend_vk_get_device_count();
  9826. }
  9827. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  9828. static std::vector<ggml_backend_dev_t> devices;
  9829. static bool initialized = false;
  9830. {
  9831. static std::mutex mutex;
  9832. std::lock_guard<std::mutex> lock(mutex);
  9833. if (!initialized) {
  9834. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  9835. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  9836. char desc[256];
  9837. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  9838. ctx->device = i;
  9839. ctx->name = GGML_VK_NAME + std::to_string(i);
  9840. ctx->description = desc;
  9841. devices.push_back(new ggml_backend_device {
  9842. /* .iface = */ ggml_backend_vk_device_i,
  9843. /* .reg = */ reg,
  9844. /* .context = */ ctx,
  9845. });
  9846. }
  9847. initialized = true;
  9848. }
  9849. }
  9850. GGML_ASSERT(device < devices.size());
  9851. return devices[device];
  9852. }
  9853. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  9854. /* .get_name = */ ggml_backend_vk_reg_get_name,
  9855. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  9856. /* .get_device = */ ggml_backend_vk_reg_get_device,
  9857. /* .get_proc_address = */ NULL,
  9858. };
  9859. ggml_backend_reg_t ggml_backend_vk_reg() {
  9860. static ggml_backend_reg reg = {
  9861. /* .api_version = */ GGML_BACKEND_API_VERSION,
  9862. /* .iface = */ ggml_backend_vk_reg_i,
  9863. /* .context = */ nullptr,
  9864. };
  9865. try {
  9866. ggml_vk_instance_init();
  9867. return &reg;
  9868. } catch (const vk::SystemError& e) {
  9869. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what());
  9870. return nullptr;
  9871. }
  9872. }
  9873. // Extension availability
  9874. static bool ggml_vk_instance_validation_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  9875. #ifdef GGML_VULKAN_VALIDATE
  9876. bool portability_enumeration_ext = false;
  9877. // Check for portability enumeration extension for MoltenVK support
  9878. for (const auto& properties : instance_extensions) {
  9879. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  9880. return true;
  9881. }
  9882. }
  9883. if (!portability_enumeration_ext) {
  9884. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  9885. }
  9886. #endif
  9887. return false;
  9888. UNUSED(instance_extensions);
  9889. }
  9890. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  9891. #ifdef __APPLE__
  9892. bool portability_enumeration_ext = false;
  9893. // Check for portability enumeration extension for MoltenVK support
  9894. for (const auto& properties : instance_extensions) {
  9895. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  9896. return true;
  9897. }
  9898. }
  9899. if (!portability_enumeration_ext) {
  9900. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  9901. }
  9902. #endif
  9903. return false;
  9904. UNUSED(instance_extensions);
  9905. }
  9906. // Extension availability
  9907. static bool ggml_vk_instance_debug_utils_ext_available(
  9908. const std::vector<vk::ExtensionProperties> & instance_extensions) {
  9909. // Check for portability enumeration extension for MoltenVK support
  9910. for (const auto & properties : instance_extensions) {
  9911. if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) {
  9912. return true;
  9913. }
  9914. }
  9915. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl;
  9916. return false;
  9917. UNUSED(instance_extensions);
  9918. }
  9919. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) {
  9920. switch (props.vendorID) {
  9921. case VK_VENDOR_ID_INTEL:
  9922. // Only allowing Xe2 GPU at the moment since Xe2 GPU can gain significant performance boost,
  9923. // while some older hardware (ex. Arc A770) has performance regressions
  9924. return arch == vk_device_architecture::INTEL_XE2;
  9925. case VK_VENDOR_ID_AMD:
  9926. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  9927. // Workaround for AMD proprietary driver reporting support on all GPUs
  9928. return arch == vk_device_architecture::AMD_RDNA3;
  9929. }
  9930. return true;
  9931. default:
  9932. return true;
  9933. }
  9934. }
  9935. // checks
  9936. #ifdef GGML_VULKAN_CHECK_RESULTS
  9937. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  9938. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  9939. return;
  9940. }
  9941. for (int j = 0; j < level; j++) {
  9942. std::cerr << " ";
  9943. }
  9944. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  9945. done.push_back(tensor);
  9946. for (int i = 0; i < GGML_MAX_SRC; i++) {
  9947. if (tensor->src[i] != nullptr) {
  9948. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  9949. }
  9950. }
  9951. }
  9952. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  9953. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  9954. return;
  9955. }
  9956. i0 = std::max(i0, 5);
  9957. i1 = std::max(i1, 5);
  9958. i2 = std::max(i2, 0);
  9959. i3 = std::max(i3, 0);
  9960. fprintf(stderr, " ");
  9961. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9962. fprintf(stderr, "%7d ", idx1);
  9963. }
  9964. fprintf(stderr, "\n");
  9965. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9966. fprintf(stderr, "%7d: ", idx0);
  9967. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9968. 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]) {
  9969. float val;
  9970. if (tensor->type == GGML_TYPE_F32) {
  9971. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  9972. } else if (tensor->type == GGML_TYPE_F16) {
  9973. 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]));
  9974. } else if (tensor->type == GGML_TYPE_I32) {
  9975. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  9976. } else {
  9977. GGML_ABORT("fatal error");
  9978. }
  9979. fprintf(stderr, "% 7.2f ", val);
  9980. } else {
  9981. fprintf(stderr, " ");
  9982. }
  9983. }
  9984. fprintf(stderr, "\n");
  9985. }
  9986. }
  9987. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  9988. void * tensor_data = tensor->data;
  9989. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  9990. if (is_gpu) {
  9991. const size_t tensor_size = ggml_nbytes(tensor);
  9992. tensor_data = malloc(tensor_size);
  9993. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  9994. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  9995. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  9996. }
  9997. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  9998. 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;
  9999. if (tensor->src[0] != nullptr) {
  10000. 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;
  10001. }
  10002. if (tensor->src[1] != nullptr) {
  10003. 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;
  10004. }
  10005. std::cerr << std::endl << "Result:" << std::endl;
  10006. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  10007. std::cerr << std::endl;
  10008. std::vector<const ggml_tensor *> done;
  10009. ggml_vk_print_graph_origin(tensor, done);
  10010. if (is_gpu) {
  10011. free(tensor_data);
  10012. }
  10013. }
  10014. void * comp_result;
  10015. size_t comp_size;
  10016. size_t comp_nb[GGML_MAX_DIMS];
  10017. size_t check_counter = 0;
  10018. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  10019. ggml_tensor * tensor = cgraph->nodes[tensor_idx];
  10020. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  10021. return;
  10022. }
  10023. bool fused_rms_norm_mul = false;
  10024. int rms_norm_idx = -1;
  10025. if (ctx->num_additional_fused_ops == 1 &&
  10026. tensor->op == GGML_OP_RMS_NORM &&
  10027. cgraph->nodes[tensor_idx + 1]->op == GGML_OP_MUL) {
  10028. fused_rms_norm_mul = true;
  10029. tensor = cgraph->nodes[tensor_idx + 1];
  10030. }
  10031. check_counter++;
  10032. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  10033. return;
  10034. }
  10035. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  10036. ggml_tensor * src0 = tensor->src[0];
  10037. ggml_tensor * src1 = tensor->src[1];
  10038. struct ggml_init_params iparams = {
  10039. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  10040. /*.mem_buffer =*/ NULL,
  10041. /*.no_alloc =*/ false,
  10042. };
  10043. struct ggml_context * ggml_ctx = ggml_init(iparams);
  10044. std::array<struct ggml_tensor *, 6> src_clone = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  10045. std::array<size_t, 6> src_size = {0, 0, 0, 0, 0, 0};
  10046. std::array<void *, 6> src_buffer = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  10047. const char * srci_name[6] = {"src0", "src1", "src2", "src3", "src4", "src5"};
  10048. struct ggml_tensor * tensor_clone = nullptr;
  10049. for (int i = 0; i < 6; i++) {
  10050. ggml_tensor * srci = tensor->src[i];
  10051. if (fused_rms_norm_mul) {
  10052. rms_norm_idx = tensor->src[0]->op == GGML_OP_RMS_NORM ? 0 : 1;
  10053. ggml_tensor *rms_norm = tensor->src[rms_norm_idx];
  10054. switch (i) {
  10055. case 0: srci = rms_norm->src[0]; break;
  10056. case 1: srci = tensor->src[1 - rms_norm_idx]; break;
  10057. default: continue;
  10058. }
  10059. }
  10060. if (srci == nullptr) {
  10061. continue;
  10062. }
  10063. ggml_tensor * srci_clone = ggml_dup_tensor(ggml_ctx, srci);
  10064. size_t srci_size = ggml_nbytes(srci);
  10065. src_clone[i] = srci_clone;
  10066. src_size[i] = ggml_nbytes(srci);
  10067. src_buffer[i] = malloc(srci_size);
  10068. srci_clone->data = src_buffer[i];
  10069. if (ggml_backend_buffer_is_host(srci->buffer)) {
  10070. memcpy(srci_clone->data, srci->data, srci_size);
  10071. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  10072. } else if (ggml_backend_buffer_is_vk(srci->buffer)) {
  10073. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)srci->buffer->context;
  10074. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  10075. uint64_t offset = vk_tensor_offset(srci) + srci->view_offs;
  10076. if (!ggml_is_contiguous(srci) && ggml_vk_dim01_contiguous(srci)) {
  10077. for (int i3 = 0; i3 < srci->ne[3]; i3++) {
  10078. for (int i2 = 0; i2 < srci->ne[2]; i2++) {
  10079. const int idx = i3*srci->ne[2] + i2;
  10080. 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]);
  10081. }
  10082. }
  10083. srci_clone->nb[0] = srci->nb[0];
  10084. srci_clone->nb[1] = srci->nb[1];
  10085. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  10086. srci_clone->nb[i] = srci_clone->nb[i - 1]*srci_clone->ne[i - 1];
  10087. }
  10088. } else {
  10089. if (offset + srci_size >= buffer_gpu->size) {
  10090. srci_size = buffer_gpu->size - offset;
  10091. }
  10092. ggml_vk_buffer_read(buffer_gpu, offset, srci_clone->data, srci_size);
  10093. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  10094. }
  10095. } else {
  10096. GGML_ABORT("fatal error");
  10097. }
  10098. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  10099. ggml_vk_print_tensor(srci, srci_name[i]);
  10100. }
  10101. }
  10102. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  10103. const float * params = (const float *)tensor->op_params;
  10104. 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]);
  10105. if (src_clone[4]) {
  10106. ggml_flash_attn_ext_add_sinks(tensor_clone, src_clone[4]);
  10107. }
  10108. } else if (tensor->op == GGML_OP_MUL_MAT) {
  10109. tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
  10110. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  10111. tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  10112. } else if (tensor->op == GGML_OP_SUB) {
  10113. tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
  10114. } else if (tensor->op == GGML_OP_MUL) {
  10115. if (fused_rms_norm_mul) {
  10116. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->src[rms_norm_idx]->op_params);
  10117. tensor_clone = ggml_mul(ggml_ctx, tensor_clone, src_clone[1 - rms_norm_idx]);
  10118. } else {
  10119. tensor_clone = ggml_mul(ggml_ctx, src_clone[0], src_clone[1]);
  10120. }
  10121. } else if (tensor->op == GGML_OP_DIV) {
  10122. tensor_clone = ggml_div(ggml_ctx, src_clone[0], src_clone[1]);
  10123. } else if (tensor->op == GGML_OP_CONCAT) {
  10124. tensor_clone = ggml_concat(ggml_ctx, src_clone[0], src_clone[1], *(int *)tensor->op_params);
  10125. } else if (tensor->op == GGML_OP_UPSCALE) {
  10126. tensor_clone = ggml_upscale_ext(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3], (ggml_scale_mode) tensor->op_params[0]);
  10127. } else if (tensor->op == GGML_OP_SCALE) {
  10128. const float * params = (const float *)tensor->op_params;
  10129. tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]);
  10130. } else if (tensor->op == GGML_OP_SQR) {
  10131. tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]);
  10132. } else if (tensor->op == GGML_OP_SIN) {
  10133. tensor_clone = ggml_sin(ggml_ctx, src_clone[0]);
  10134. } else if (tensor->op == GGML_OP_COS) {
  10135. tensor_clone = ggml_cos(ggml_ctx, src_clone[0]);
  10136. } else if (tensor->op == GGML_OP_CLAMP) {
  10137. const float * params = (const float *)tensor->op_params;
  10138. tensor_clone = ggml_clamp(ggml_ctx, src_clone[0], params[0], params[1]);
  10139. } else if (tensor->op == GGML_OP_PAD) {
  10140. tensor_clone = ggml_pad(ggml_ctx, src_clone[0], tensor->ne[0] - src_clone[0]->ne[0], tensor->ne[1] - src_clone[0]->ne[1], tensor->ne[2] - src_clone[0]->ne[2], tensor->ne[3] - src_clone[0]->ne[3]);
  10141. } else if (tensor->op == GGML_OP_REPEAT) {
  10142. tensor_clone = ggml_repeat(ggml_ctx, src_clone[0], tensor);
  10143. } else if (tensor->op == GGML_OP_REPEAT_BACK) {
  10144. tensor_clone = ggml_repeat_back(ggml_ctx, src_clone[0], tensor);
  10145. } else if (tensor->op == GGML_OP_ADD) {
  10146. tensor_clone = ggml_add(ggml_ctx, src_clone[0], src_clone[1]);
  10147. } else if (tensor->op == GGML_OP_ACC) {
  10148. 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]);
  10149. } else if (tensor->op == GGML_OP_NORM) {
  10150. tensor_clone = ggml_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  10151. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  10152. const float * float_params = (const float *)tensor->op_params;
  10153. tensor_clone = ggml_group_norm(ggml_ctx, src_clone[0], tensor->op_params[0], float_params[1]);
  10154. } else if (tensor->op == GGML_OP_RMS_NORM) {
  10155. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  10156. } else if (tensor->op == GGML_OP_RMS_NORM_BACK) {
  10157. const float eps = ((float *) tensor->op_params)[0];
  10158. tensor_clone = ggml_rms_norm_back(ggml_ctx, src_clone[0], src_clone[1], eps);
  10159. } else if (tensor->op == GGML_OP_SILU_BACK) {
  10160. tensor_clone = ggml_silu_back(ggml_ctx, src_clone[0], src_clone[1]);
  10161. } else if (tensor->op == GGML_OP_L2_NORM) {
  10162. const float eps = ((float *) tensor->op_params)[0];
  10163. tensor_clone = ggml_l2_norm(ggml_ctx, src_clone[0], eps);
  10164. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  10165. if (src1 != nullptr) {
  10166. const float * params = (const float *)tensor->op_params;
  10167. tensor_clone = ggml_soft_max_ext(ggml_ctx, src_clone[0], src_clone[1], params[0], params[1]);
  10168. } else {
  10169. tensor_clone = ggml_soft_max(ggml_ctx, src_clone[0]);
  10170. }
  10171. } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) {
  10172. 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]);
  10173. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  10174. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]);
  10175. } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) {
  10176. const int n_dims = ((int32_t *) tensor->op_params)[1];
  10177. const int mode = ((int32_t *) tensor->op_params)[2];
  10178. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  10179. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  10180. const float freq_base = ((float *) tensor->op_params)[5];
  10181. const float freq_scale = ((float *) tensor->op_params)[6];
  10182. const float ext_factor = ((float *) tensor->op_params)[7];
  10183. const float attn_factor = ((float *) tensor->op_params)[8];
  10184. const float beta_fast = ((float *) tensor->op_params)[9];
  10185. const float beta_slow = ((float *) tensor->op_params)[10];
  10186. if (mode & GGML_ROPE_TYPE_MROPE) {
  10187. int32_t *sections = ((int32_t *) tensor->op_params) + 11;
  10188. if (tensor->op == GGML_OP_ROPE) {
  10189. 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);
  10190. } else {
  10191. 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);
  10192. }
  10193. } else {
  10194. if (tensor->op == GGML_OP_ROPE) {
  10195. 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);
  10196. } else {
  10197. 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);
  10198. }
  10199. }
  10200. } else if (tensor->op == GGML_OP_UNARY) {
  10201. switch (ggml_get_unary_op(tensor)) {
  10202. case GGML_UNARY_OP_SILU:
  10203. tensor_clone = ggml_silu(ggml_ctx, src_clone[0]);
  10204. break;
  10205. case GGML_UNARY_OP_GELU:
  10206. tensor_clone = ggml_gelu(ggml_ctx, src_clone[0]);
  10207. break;
  10208. case GGML_UNARY_OP_GELU_ERF:
  10209. tensor_clone = ggml_gelu_erf(ggml_ctx, src_clone[0]);
  10210. break;
  10211. case GGML_UNARY_OP_GELU_QUICK:
  10212. tensor_clone = ggml_gelu_quick(ggml_ctx, src_clone[0]);
  10213. break;
  10214. case GGML_UNARY_OP_RELU:
  10215. tensor_clone = ggml_relu(ggml_ctx, src_clone[0]);
  10216. break;
  10217. case GGML_UNARY_OP_TANH:
  10218. tensor_clone = ggml_tanh(ggml_ctx, src_clone[0]);
  10219. break;
  10220. case GGML_UNARY_OP_SIGMOID:
  10221. tensor_clone = ggml_sigmoid(ggml_ctx, src_clone[0]);
  10222. break;
  10223. default:
  10224. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  10225. GGML_ABORT("fatal error");
  10226. }
  10227. } else if (tensor->op == GGML_OP_GLU) {
  10228. if (src_clone[1] == nullptr) {
  10229. tensor_clone = ggml_glu(ggml_ctx, src_clone[0], (ggml_glu_op) tensor->op_params[0], tensor->op_params[1]);
  10230. } else {
  10231. tensor_clone = ggml_glu_split(ggml_ctx, src_clone[0], src_clone[1], (ggml_glu_op) tensor->op_params[0]);
  10232. }
  10233. ggml_set_op_params_i32(tensor_clone, 2, ggml_get_op_params_i32(tensor, 2));
  10234. ggml_set_op_params_i32(tensor_clone, 3, ggml_get_op_params_i32(tensor, 3));
  10235. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  10236. if (src1 == nullptr) {
  10237. tensor_clone = ggml_dup(ggml_ctx, src_clone[0]);
  10238. tensor_clone->type = tensor->type;
  10239. } else {
  10240. tensor_clone = ggml_cpy(ggml_ctx, src_clone[0], src_clone[1]);
  10241. }
  10242. } else if (tensor->op == GGML_OP_CONT) {
  10243. tensor_clone = ggml_cont_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  10244. } else if (tensor->op == GGML_OP_RESHAPE) {
  10245. tensor_clone = ggml_reshape_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  10246. } else if (tensor->op == GGML_OP_VIEW) {
  10247. 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]);
  10248. } else if (tensor->op == GGML_OP_PERMUTE) {
  10249. int32_t * params = (int32_t *)tensor->op_params;
  10250. tensor_clone = ggml_permute(ggml_ctx, src_clone[0], params[0], params[1], params[2], params[3]);
  10251. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  10252. tensor_clone = ggml_transpose(ggml_ctx, src_clone[0]);
  10253. } else if (tensor->op == GGML_OP_GET_ROWS) {
  10254. tensor_clone = ggml_get_rows(ggml_ctx, src_clone[0], src_clone[1]);
  10255. } else if (tensor->op == GGML_OP_ARGSORT) {
  10256. tensor_clone = ggml_argsort(ggml_ctx, src_clone[0], (ggml_sort_order) *(int *)tensor->op_params);
  10257. } else if (tensor->op == GGML_OP_SUM) {
  10258. tensor_clone = ggml_sum(ggml_ctx, src_clone[0]);
  10259. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  10260. tensor_clone = ggml_sum_rows(ggml_ctx, src_clone[0]);
  10261. } else if (tensor->op == GGML_OP_ARGMAX) {
  10262. tensor_clone = ggml_argmax(ggml_ctx, src_clone[0]);
  10263. } else if (tensor->op == GGML_OP_COUNT_EQUAL) {
  10264. tensor_clone = ggml_count_equal(ggml_ctx, src_clone[0], src_clone[1]);
  10265. } else if (tensor->op == GGML_OP_IM2COL) {
  10266. const int32_t s0 = tensor->op_params[0];
  10267. const int32_t s1 = tensor->op_params[1];
  10268. const int32_t p0 = tensor->op_params[2];
  10269. const int32_t p1 = tensor->op_params[3];
  10270. const int32_t d0 = tensor->op_params[4];
  10271. const int32_t d1 = tensor->op_params[5];
  10272. const bool is_2D = tensor->op_params[6] == 1;
  10273. tensor_clone = ggml_im2col(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  10274. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  10275. const int32_t dim = tensor->op_params[0];
  10276. const int32_t max_period = tensor->op_params[1];
  10277. tensor_clone = ggml_timestep_embedding(ggml_ctx, src_clone[0], dim, max_period);
  10278. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_1D){
  10279. const int32_t s0 = tensor->op_params[0];
  10280. const int32_t p0 = tensor->op_params[1];
  10281. const int32_t d0 = tensor->op_params[2];
  10282. tensor_clone = ggml_conv_transpose_1d(ggml_ctx, src_clone[0], src_clone[1], s0, p0, d0);
  10283. } else if (tensor->op == GGML_OP_POOL_2D) {
  10284. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  10285. const int32_t k0 = tensor->op_params[1];
  10286. const int32_t k1 = tensor->op_params[2];
  10287. const int32_t s0 = tensor->op_params[3];
  10288. const int32_t s1 = tensor->op_params[4];
  10289. const int32_t p0 = tensor->op_params[5];
  10290. const int32_t p1 = tensor->op_params[6];
  10291. tensor_clone = ggml_pool_2d(ggml_ctx, src_clone[0], op, k0, k1, s0, s1, p0, p1);
  10292. } else if (tensor->op == GGML_OP_CONV_2D) {
  10293. const int32_t s0 = tensor->op_params[0];
  10294. const int32_t s1 = tensor->op_params[1];
  10295. const int32_t p0 = tensor->op_params[2];
  10296. const int32_t p1 = tensor->op_params[3];
  10297. const int32_t d0 = tensor->op_params[4];
  10298. const int32_t d1 = tensor->op_params[5];
  10299. tensor_clone = ggml_conv_2d(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  10300. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  10301. const float * op_params = (const float *)tensor->op_params;
  10302. tensor_clone = ggml_leaky_relu(ggml_ctx, src_clone[0], op_params[0], false);
  10303. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  10304. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, src_clone[0], src_clone[1],
  10305. src_clone[2], src_clone[3], src_clone[4], src_clone[5]);
  10306. } else if (tensor->op == GGML_OP_RWKV_WKV7) {
  10307. tensor_clone = ggml_rwkv_wkv7(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3],
  10308. src_clone[4], src_clone[5], src_clone[6]);
  10309. } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
  10310. src_clone[0]->flags = src0->flags;
  10311. tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
  10312. src_clone[2], src_clone[3], src_clone[4]);
  10313. } else if (tensor->op == GGML_OP_OPT_STEP_SGD) {
  10314. src_clone[0]->flags = src0->flags;
  10315. tensor_clone = ggml_opt_step_sgd(ggml_ctx, src_clone[0], src_clone[1],
  10316. src_clone[2]);
  10317. } else if (tensor->op == GGML_OP_ADD_ID) {
  10318. tensor_clone = ggml_add_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  10319. }
  10320. else {
  10321. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  10322. GGML_ABORT("fatal error");
  10323. }
  10324. ggml_cgraph * cgraph_cpu = ggml_new_graph(ggml_ctx);
  10325. ggml_build_forward_expand(cgraph_cpu, tensor_clone);
  10326. ggml_graph_compute_with_ctx(ggml_ctx, cgraph_cpu, 8);
  10327. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  10328. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  10329. }
  10330. comp_size = ggml_nbytes(tensor_clone);
  10331. comp_result = malloc(comp_size);
  10332. memcpy(comp_result, tensor_clone->data, comp_size);
  10333. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  10334. for (int i = 0; i < 6; i++) {
  10335. if (src_buffer[i] != nullptr) {
  10336. free(src_buffer[i]);
  10337. }
  10338. }
  10339. ggml_free(ggml_ctx);
  10340. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  10341. }
  10342. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  10343. ggml_tensor * tensor = cgraph->nodes[tensor_idx];
  10344. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  10345. return;
  10346. }
  10347. bool fused_rms_norm_mul = false;
  10348. if (ctx->num_additional_fused_ops == 1 &&
  10349. tensor->op == GGML_OP_RMS_NORM &&
  10350. cgraph->nodes[tensor_idx + 1]->op == GGML_OP_MUL) {
  10351. fused_rms_norm_mul = true;
  10352. tensor = cgraph->nodes[tensor_idx + 1];
  10353. }
  10354. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  10355. return;
  10356. }
  10357. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  10358. ggml_tensor * src0 = tensor->src[0];
  10359. ggml_tensor * src1 = tensor->src[1];
  10360. ggml_tensor * src2 = tensor->src[2];
  10361. ggml_tensor * src3 = tensor->src[3];
  10362. void * tensor_data = tensor->data;
  10363. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  10364. size_t tensor_size = ggml_nbytes(tensor);
  10365. tensor_data = malloc(tensor_size);
  10366. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10367. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  10368. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  10369. if (offset + tensor_size >= buffer_gpu->size) {
  10370. tensor_size = buffer_gpu->size - offset;
  10371. }
  10372. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  10373. }
  10374. float first_error_result = -1.0f;
  10375. float first_error_correct = -1.0f;
  10376. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  10377. double avg_err = 0.0;
  10378. size_t counter = 0;
  10379. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  10380. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  10381. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  10382. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  10383. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  10384. float correct = 0.0f;
  10385. float result = 0.0f;
  10386. if (buffer_size_fit) {
  10387. if (tensor->type == GGML_TYPE_F32) {
  10388. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  10389. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  10390. } else if (tensor->type == GGML_TYPE_F16) {
  10391. 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]));
  10392. 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]));
  10393. } else if (tensor->type == GGML_TYPE_BF16) {
  10394. 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]));
  10395. 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]));
  10396. } else if (tensor->type == GGML_TYPE_I32) {
  10397. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  10398. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  10399. } else if (tensor->type == GGML_TYPE_I64) {
  10400. correct = *(int64_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  10401. result = *(int64_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  10402. } else {
  10403. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  10404. }
  10405. } else {
  10406. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  10407. GGML_ABORT("fatal error");
  10408. }
  10409. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  10410. 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;
  10411. 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;
  10412. if (src0 != nullptr) {
  10413. 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;
  10414. }
  10415. if (src1 != nullptr) {
  10416. 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;
  10417. }
  10418. if (src2 != nullptr) {
  10419. 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;
  10420. }
  10421. if (src3 != nullptr) {
  10422. 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;
  10423. }
  10424. 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;
  10425. std::cerr << std::endl << "Result:" << std::endl;
  10426. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  10427. std::cerr << std::endl << "Correct:" << std::endl;
  10428. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  10429. std::cerr << std::endl;
  10430. std::vector<const ggml_tensor *> done;
  10431. ggml_vk_print_graph_origin(tensor, done);
  10432. GGML_ABORT("fatal error");
  10433. }
  10434. const double denom = std::fabs(correct) > 1.0f ? (std::fabs(correct) > 1e-8 ? std::fabs(correct) : 1e-8) : 1.0f;
  10435. if (first_error[0] == -1 && std::fabs(correct - result) / denom > 0.5) {
  10436. first_error[0] = i0;
  10437. first_error[1] = i1;
  10438. first_error[2] = i2;
  10439. first_error[3] = i3;
  10440. first_error_result = result;
  10441. first_error_correct = correct;
  10442. }
  10443. // Special case, value is infinite, avoid NaN result in avg_err
  10444. // NaN also appears in results, if both are nan error is 0
  10445. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  10446. avg_err += std::fabs(correct - result) / denom;
  10447. }
  10448. counter++;
  10449. }
  10450. }
  10451. }
  10452. }
  10453. avg_err /= counter;
  10454. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  10455. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  10456. 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;
  10457. if (src0 != nullptr) {
  10458. 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;
  10459. }
  10460. if (src1 != nullptr) {
  10461. 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;
  10462. }
  10463. if (src2 != nullptr) {
  10464. 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;
  10465. }
  10466. if (src3 != nullptr) {
  10467. 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;
  10468. }
  10469. 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;
  10470. std::cerr << std::endl << "Result:" << std::endl;
  10471. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  10472. std::cerr << std::endl << "Correct:" << std::endl;
  10473. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  10474. std::cerr << std::endl;
  10475. std::vector<const ggml_tensor *> done;
  10476. ggml_vk_print_graph_origin(tensor, done);
  10477. }
  10478. if (avg_err > 0.5 || std::isnan(avg_err)) {
  10479. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  10480. 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;
  10481. if (src0 != nullptr) {
  10482. 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;
  10483. }
  10484. if (src1 != nullptr) {
  10485. 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;
  10486. }
  10487. if (src2 != nullptr) {
  10488. 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;
  10489. }
  10490. if (src3 != nullptr) {
  10491. 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;
  10492. }
  10493. 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;
  10494. std::cerr << std::endl << "Result:" << std::endl;
  10495. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  10496. std::cerr << std::endl << "Correct:" << std::endl;
  10497. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  10498. std::cerr << std::endl;
  10499. std::vector<const ggml_tensor *> done;
  10500. ggml_vk_print_graph_origin(tensor, done);
  10501. GGML_ABORT("fatal error");
  10502. } else {
  10503. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  10504. }
  10505. free(comp_result);
  10506. comp_result = nullptr;
  10507. comp_size = 0;
  10508. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  10509. free(tensor_data);
  10510. }
  10511. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  10512. }
  10513. #endif
  10514. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)