ggml-vulkan.cpp 741 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962
  1. #include "ggml-vulkan.h"
  2. #include <vulkan/vulkan_core.h>
  3. #if defined(GGML_VULKAN_RUN_TESTS) || defined(GGML_VULKAN_CHECK_RESULTS)
  4. #include <chrono>
  5. #include "ggml-cpu.h"
  6. #endif
  7. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  8. #define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
  9. // We use VULKAN_HPP_DEFAULT_DISPATCHER, but not VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
  10. // to avoid conflicts with applications or other libraries who might use it.
  11. #if VK_HEADER_VERSION >= 301
  12. namespace vk::detail { class DispatchLoaderDynamic; }
  13. using vk::detail::DispatchLoaderDynamic;
  14. #else
  15. namespace vk { class DispatchLoaderDynamic; }
  16. using vk::DispatchLoaderDynamic;
  17. #endif
  18. DispatchLoaderDynamic & ggml_vk_default_dispatcher();
  19. #define VULKAN_HPP_DEFAULT_DISPATCHER ggml_vk_default_dispatcher()
  20. #include <vulkan/vulkan.hpp>
  21. #include <algorithm>
  22. #include <cmath>
  23. #include <iomanip>
  24. #include <iostream>
  25. #include <tuple>
  26. #include <vector>
  27. #include <sstream>
  28. #include <utility>
  29. #include <memory>
  30. #include <limits>
  31. #include <map>
  32. #include <set>
  33. #include <unordered_map>
  34. #include <memory>
  35. #include <mutex>
  36. #include <future>
  37. #include <thread>
  38. #if defined(_MSC_VER)
  39. # define NOMINMAX 1
  40. # include <windows.h>
  41. # define YIELD() YieldProcessor()
  42. #elif defined(__clang__) || defined(__GNUC__)
  43. # if defined(__x86_64__) ||defined(__i386__)
  44. # include <immintrin.h>
  45. # define YIELD() _mm_pause()
  46. # elif defined(__arm__) || defined(__aarch64__)
  47. # if defined(__clang__)
  48. # include <arm_acle.h>
  49. # define YIELD() __yield()
  50. # else
  51. # define YIELD() asm volatile("yield")
  52. # endif
  53. # endif
  54. #endif
  55. #if !defined(YIELD)
  56. #define YIELD()
  57. #endif
  58. #include "ggml-impl.h"
  59. #include "ggml-backend-impl.h"
  60. #include "ggml-vulkan-shaders.hpp"
  61. // remove this once it's more widely available in the SDK
  62. #if !defined(VK_KHR_shader_bfloat16)
  63. #define VK_KHR_shader_bfloat16 1
  64. #define VK_KHR_SHADER_BFLOAT16_SPEC_VERSION 1
  65. #define VK_KHR_SHADER_BFLOAT16_EXTENSION_NAME "VK_KHR_shader_bfloat16"
  66. #define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR ((VkStructureType)1000141000)
  67. #define VK_COMPONENT_TYPE_BFLOAT16_KHR ((VkComponentTypeKHR)1000141000)
  68. typedef struct VkPhysicalDeviceShaderBfloat16FeaturesKHR {
  69. VkStructureType sType;
  70. void* pNext;
  71. VkBool32 shaderBFloat16Type;
  72. VkBool32 shaderBFloat16DotProduct;
  73. VkBool32 shaderBFloat16CooperativeMatrix;
  74. } VkPhysicalDeviceShaderBfloat16FeaturesKHR;
  75. #endif
  76. #define ROUNDUP_POW2(M, N) (((M) + (N) - 1) & ~((N) - 1))
  77. #define CEIL_DIV(M, N) (((M) + (N)-1) / (N))
  78. static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; }
  79. #define VK_VENDOR_ID_AMD 0x1002
  80. #define VK_VENDOR_ID_APPLE 0x106b
  81. #define VK_VENDOR_ID_INTEL 0x8086
  82. #define VK_VENDOR_ID_NVIDIA 0x10de
  83. #define VK_DEVICE_DESCRIPTOR_POOL_SIZE 256
  84. #define GGML_VK_MAX_NODES 8192
  85. #define VK_CHECK(err, msg) \
  86. do { \
  87. vk::Result err_ = (err); \
  88. if (err_ != vk::Result::eSuccess) { \
  89. fprintf(stderr, "ggml_vulkan: %s error %s at %s:%d\n", \
  90. #err, to_string(err_).c_str(), __FILE__, __LINE__); \
  91. exit(1); \
  92. } \
  93. } while (0)
  94. #ifdef GGML_VULKAN_DEBUG
  95. #define VK_LOG_DEBUG(msg) std::cerr << msg << std::endl
  96. #else
  97. #define VK_LOG_DEBUG(msg) ((void) 0)
  98. #endif // GGML_VULKAN_DEBUG
  99. struct ggml_backend_vk_context;
  100. #define MAX_PARAMETER_COUNT 12
  101. // Max number of adds that can be fused without exceeding MAX_PARAMETER_COUNT.
  102. #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3)
  103. struct vk_pipeline_struct {
  104. std::string name;
  105. vk::ShaderModule shader_module;
  106. vk::PipelineLayout layout;
  107. vk::Pipeline pipeline;
  108. uint32_t push_constant_size;
  109. uint32_t parameter_count;
  110. std::array<uint32_t, 3> wg_denoms;
  111. uint32_t align;
  112. // true if fields have been set by ggml_vk_create_pipeline
  113. bool initialized {};
  114. // set to true to request the pipeline is compiled
  115. std::atomic<bool> needed {};
  116. // set to true when the shader has been compiled
  117. std::atomic<bool> compiled {};
  118. // number of registers used, extracted from pipeline executable properties
  119. uint32_t register_count {};
  120. };
  121. typedef std::shared_ptr<vk_pipeline_struct> vk_pipeline;
  122. typedef std::weak_ptr<vk_pipeline_struct> vk_pipeline_ref;
  123. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
  124. struct vk_matmul_pipeline_struct {
  125. vk_pipeline l, m, s;
  126. vk_pipeline a_l, a_m, a_s;
  127. // Returns true when all unaligned pipelines are null.
  128. // We only check for unaligned variants since one of the unaligned pipelines must exist
  129. // while aligned pipelines are optional
  130. bool is_empty() const {
  131. return l == nullptr && m == nullptr && s == nullptr;
  132. }
  133. };
  134. typedef std::shared_ptr<vk_matmul_pipeline_struct> vk_matmul_pipeline;
  135. struct vk_matmul_pipeline2 {
  136. vk_matmul_pipeline2() {
  137. f16acc = std::make_shared<vk_matmul_pipeline_struct>();
  138. f32acc = std::make_shared<vk_matmul_pipeline_struct>();
  139. }
  140. vk_matmul_pipeline f32acc;
  141. vk_matmul_pipeline f16acc;
  142. };
  143. struct vk_device_struct;
  144. typedef std::shared_ptr<vk_device_struct> vk_device;
  145. typedef std::weak_ptr<vk_device_struct> vk_device_ref;
  146. struct vk_buffer_struct;
  147. typedef std::shared_ptr<vk_buffer_struct> vk_buffer;
  148. typedef std::weak_ptr<vk_buffer_struct> vk_buffer_ref;
  149. struct ggml_backend_vk_buffer_type_context {
  150. std::string name;
  151. vk_device device;
  152. };
  153. struct vk_queue;
  154. // Stores command pool/buffers. There's an instance of this
  155. // for each (context,queue) pair and for each (device,queue) pair.
  156. struct vk_command_pool {
  157. void init(vk_device& device, vk_queue *q_);
  158. void destroy(vk::Device& device);
  159. vk::CommandPool pool;
  160. uint32_t cmd_buffer_idx;
  161. std::vector<vk::CommandBuffer> cmd_buffers;
  162. vk_queue *q;
  163. };
  164. // Prevent simultaneous submissions to the same queue.
  165. // This could be per vk_queue if we stopped having two vk_queue structures
  166. // sharing the same vk::Queue.
  167. static std::mutex queue_mutex;
  168. struct vk_queue {
  169. uint32_t queue_family_index;
  170. vk::Queue queue;
  171. vk_command_pool cmd_pool;
  172. vk::PipelineStageFlags stage_flags;
  173. bool transfer_only;
  174. // copy everything except the cmd_pool
  175. void copyFrom(vk_queue &other) {
  176. queue_family_index = other.queue_family_index;
  177. queue = other.queue;
  178. stage_flags = other.stage_flags;
  179. transfer_only = other.transfer_only;
  180. }
  181. };
  182. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft);
  183. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size);
  184. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft);
  185. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft);
  186. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor);
  187. static ggml_backend_buffer_type_i ggml_backend_vk_buffer_type_interface = {
  188. /* .get_name = */ ggml_backend_vk_buffer_type_name,
  189. /* .alloc_buffer = */ ggml_backend_vk_buffer_type_alloc_buffer,
  190. /* .get_alignment = */ ggml_backend_vk_buffer_type_get_alignment,
  191. /* .get_max_size = */ ggml_backend_vk_buffer_type_get_max_size,
  192. /* .get_alloc_size = */ ggml_backend_vk_buffer_type_get_alloc_size,
  193. /* .is_host = */ NULL,
  194. };
  195. #ifdef GGML_VULKAN_MEMORY_DEBUG
  196. class vk_memory_logger;
  197. #endif
  198. class vk_perf_logger;
  199. static void ggml_vk_destroy_buffer(vk_buffer& buf);
  200. static void ggml_vk_synchronize(ggml_backend_vk_context * ctx);
  201. static constexpr uint32_t mul_mat_vec_max_cols = 8;
  202. static constexpr uint32_t p021_max_gqa_ratio = 8;
  203. enum vk_device_architecture {
  204. OTHER,
  205. AMD_GCN,
  206. AMD_RDNA1,
  207. AMD_RDNA2,
  208. AMD_RDNA3,
  209. INTEL_XE2,
  210. NVIDIA_PRE_TURING,
  211. };
  212. static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) {
  213. vk::PhysicalDeviceProperties props = device.getProperties();
  214. if (props.vendorID == VK_VENDOR_ID_AMD) {
  215. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  216. bool amd_shader_core_properties = false;
  217. bool integer_dot_product = false;
  218. bool subgroup_size_control = false;
  219. for (const auto& properties : ext_props) {
  220. if (strcmp("VK_AMD_shader_core_properties", properties.extensionName) == 0) {
  221. amd_shader_core_properties = true;
  222. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0) {
  223. integer_dot_product = true;
  224. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  225. subgroup_size_control = true;
  226. }
  227. }
  228. if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) {
  229. return vk_device_architecture::OTHER;
  230. }
  231. vk::PhysicalDeviceProperties2 props2;
  232. vk::PhysicalDeviceShaderCorePropertiesAMD shader_core_props_amd;
  233. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR integer_dot_props;
  234. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  235. props2.pNext = &shader_core_props_amd;
  236. shader_core_props_amd.pNext = &integer_dot_props;
  237. integer_dot_props.pNext = &subgroup_size_control_props;
  238. device.getProperties2(&props2);
  239. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 64) {
  240. return vk_device_architecture::AMD_GCN;
  241. }
  242. if (subgroup_size_control_props.maxSubgroupSize == 64 && subgroup_size_control_props.minSubgroupSize == 32) {
  243. // RDNA
  244. if (shader_core_props_amd.wavefrontsPerSimd == 20) {
  245. return vk_device_architecture::AMD_RDNA1;
  246. }
  247. if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
  248. return vk_device_architecture::AMD_RDNA3;
  249. }
  250. return vk_device_architecture::AMD_RDNA2;
  251. }
  252. } else if (props.vendorID == VK_VENDOR_ID_INTEL) {
  253. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  254. bool subgroup_size_control = false;
  255. for (const auto& properties : ext_props) {
  256. if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  257. subgroup_size_control = true;
  258. }
  259. }
  260. if (!subgroup_size_control) {
  261. return vk_device_architecture::OTHER;
  262. }
  263. vk::PhysicalDeviceProperties2 props2;
  264. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  265. props2.pNext = &subgroup_size_control_props;
  266. device.getProperties2(&props2);
  267. if (subgroup_size_control_props.minSubgroupSize == 16) {
  268. // Xe2 architecture uses SIMD16 while previous Xe and Gen architecture uses SIMD8.
  269. // Minimum subgroup size matches the SIMD width so we distinguish architecture by checking this value.
  270. // https://www.intel.com/content/www/us/en/content-details/824434/2024-intel-tech-tour-xe2-and-lunar-lake-s-gpu.html
  271. // https://www.intel.com/content/www/us/en/docs/oneapi/optimization-guide-gpu/2025-0/intel-xe-gpu-architecture.html
  272. return vk_device_architecture::INTEL_XE2;
  273. }
  274. } else if (props.vendorID == VK_VENDOR_ID_NVIDIA) {
  275. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  276. bool cooperative_matrix = false;
  277. // Detect "pre-turing" based on lack of coopmat support.
  278. for (const auto& properties : ext_props) {
  279. if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0) {
  280. cooperative_matrix = true;
  281. break;
  282. }
  283. }
  284. if (!cooperative_matrix) {
  285. return vk_device_architecture::NVIDIA_PRE_TURING;
  286. }
  287. }
  288. return vk_device_architecture::OTHER;
  289. }
  290. enum vk_conv_shapes {
  291. CONV_SHAPE_128x128,
  292. CONV_SHAPE_64x32,
  293. CONV_SHAPE_32x256,
  294. CONV_SHAPE_COUNT,
  295. };
  296. uint32_t conv_shapes_wg_denoms[][3] = {
  297. { 128, 128, 1 },
  298. { 64, 32, 1 },
  299. { 32, 256, 1 },
  300. };
  301. enum dmmv_wg_sizes {
  302. DMMV_WG_SIZE_SUBGROUP,
  303. DMMV_WG_SIZE_LARGE,
  304. DMMV_WG_SIZE_COUNT,
  305. };
  306. enum FaCodePath {
  307. FA_SCALAR,
  308. FA_COOPMAT1,
  309. FA_COOPMAT2,
  310. };
  311. struct vk_fa_pipeline_state {
  312. vk_fa_pipeline_state(uint32_t HSK, uint32_t HSV, bool small_rows, FaCodePath path, bool aligned, bool f32acc)
  313. : HSK(HSK), HSV(HSV), small_rows(small_rows), path(path), aligned(aligned), f32acc(f32acc) {}
  314. uint32_t HSK, HSV;
  315. bool small_rows;
  316. FaCodePath path;
  317. bool aligned;
  318. bool f32acc;
  319. bool operator<(const vk_fa_pipeline_state &b) const {
  320. return std::tie(HSK, HSV, small_rows, path, aligned, f32acc) <
  321. std::tie(b.HSK, b.HSV, b.small_rows, b.path, b.aligned, b.f32acc);
  322. }
  323. };
  324. struct vk_conv2d_pipeline_state {
  325. vk_conv2d_pipeline_state(uint32_t s0, uint32_t s1, uint32_t p0, uint32_t p1, uint32_t d0, uint32_t d1, uint32_t KW, uint32_t KH)
  326. : s0(s0), s1(s1), p0(p0), p1(p1), d0(d0), d1(d1), KW(KW), KH(KH) {}
  327. uint32_t s0, s1, p0, p1, d0, d1, KW, KH;
  328. bool operator<(const vk_conv2d_pipeline_state &b) const {
  329. return std::tie(s0, s1, p0, p1, d0, d1, KW, KH) <
  330. std::tie(b.s0, b.s1, b.p0, b.p1, b.d0, b.d1, b.KW, b.KH);
  331. }
  332. };
  333. enum shader_reduction_mode {
  334. SHADER_REDUCTION_MODE_SHMEM,
  335. SHADER_REDUCTION_MODE_HYBRID,
  336. SHADER_REDUCTION_MODE_SUBGROUP,
  337. SHADER_REDUCTION_MODE_COUNT,
  338. };
  339. // argsort pipelines for up to 1<<10 invocations per workgroup
  340. static constexpr uint32_t num_argsort_pipelines = 11;
  341. static constexpr uint32_t num_topk_moe_pipelines = 10;
  342. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax_norm{ GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  343. GGML_OP_VIEW, GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  344. GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV,
  345. GGML_OP_RESHAPE };
  346. static constexpr std::initializer_list<ggml_op> topk_moe_early_softmax { GGML_OP_SOFT_MAX, GGML_OP_RESHAPE, GGML_OP_ARGSORT,
  347. GGML_OP_VIEW, GGML_OP_GET_ROWS };
  348. static constexpr std::initializer_list<ggml_op> topk_moe_late_softmax { GGML_OP_ARGSORT, GGML_OP_VIEW,
  349. GGML_OP_GET_ROWS, GGML_OP_RESHAPE,
  350. GGML_OP_SOFT_MAX, GGML_OP_RESHAPE };
  351. //node #978 ( SOFT_MAX): ffn_moe_probs-15 ( 0K) [Vulka ] use=2: ffn_moe_logits-15 ( 0K) [Vulka ]
  352. //node #979 ( RESHAPE): ffn_moe_probs-15 (re ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  353. //node #980 ( ARGSORT): ffn_moe_argsort-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 ( 0K) [Vulka ]
  354. //node #981 ( VIEW): ffn_moe_topk-15 ( 0K) [Vulka ] use=4: ffn_moe_argsort-15 ( 0K) [Vulka ]
  355. //node #982 ( GET_ROWS): ffn_moe_weights-15 ( 0K) [Vulka ] use=1: ffn_moe_probs-15 (re ( 0K) [Vulka ] ffn_moe_topk-15 ( 0K) [Vulka ]
  356. //node #983 ( RESHAPE): ffn_moe_weights-15 ( ( 0K) [Vulka ] use=2: ffn_moe_weights-15 ( 0K) [Vulka ]
  357. //node #984 ( SUM_ROWS): ffn_moe_weights_sum- ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ]
  358. //node #985 ( CLAMP): ffn_moe_weights_sum_ ( 0K) [Vulka ] use=1: ffn_moe_weights_sum- ( 0K) [Vulka ]
  359. //node #986 ( DIV): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights-15 ( ( 0K) [Vulka ] ffn_moe_weights_sum_ ( 0K) [Vulka ]
  360. //node #987 ( RESHAPE): ffn_moe_weights_norm ( 0K) [Vulka ] use=1: ffn_moe_weights_norm ( 0K) [Vulka ]
  361. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_norm_edges {
  362. { 1, 0, 0 }, // reshape->src[0] == softmax
  363. { 2, 0, 0 }, // argsort->src[0] == softmax
  364. { 3, 0, 2 }, // view->src[0] == argsort
  365. { 4, 0, 1 }, // get_rows->src[0] == reshape
  366. { 4, 1, 3 }, // get_rows->src[1] == view
  367. { 5, 0, 4 }, // reshape->src[0] == get_rows
  368. { 6, 0, 5 }, // sum_rows->src[0] == reshape
  369. { 7, 0, 6 }, // clamp->src[0] == sum_rows
  370. { 8, 0, 5 }, // div->src[0] == reshape
  371. { 8, 1, 7 }, // div->src[1] == clamp
  372. { 9, 0, 8 }, // reshape->src[0] == div
  373. };
  374. // same as early_softmax_norm but ending after the get_rows
  375. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_early_softmax_edges {
  376. { 1, 0, 0 }, // reshape->src[0] == softmax
  377. { 2, 0, 0 }, // argsort->src[0] == softmax
  378. { 3, 0, 2 }, // view->src[0] == argsort
  379. { 4, 0, 1 }, // get_rows->src[0] == reshape
  380. { 4, 1, 3 }, // get_rows->src[1] == view
  381. };
  382. //node #652 ( ARGSORT): ffn_moe_argsort-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 ( 0K) [Vulka ]
  383. //node #653 ( VIEW): ffn_moe_topk-11 ( 0K) [Vulka ] use=7: ffn_moe_argsort-11 ( 0K) [Vulka ]
  384. //node #654 ( GET_ROWS): ffn_moe_weights-11 ( 0K) [Vulka ] use=1: ffn_moe_probs-11 (re ( 0K) [Vulka ] ffn_moe_topk-11 ( 0K) [Vulka ]
  385. //node #655 ( RESHAPE): ffn_moe_weights-11 ( ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( 0K) [Vulka ]
  386. //node #656 ( SOFT_MAX): node_656 ( 0K) [Vulka ] use=1: ffn_moe_weights-11 ( ( 0K) [Vulka ]
  387. //node #657 ( RESHAPE): ffn_moe_weights_soft ( 0K) [Vulka ] use=1: node_656 ( 0K) [Vulka ]
  388. static constexpr std::initializer_list<std::array<int, 3>> topk_moe_late_softmax_edges {
  389. { 1, 0, 0 }, // view->src[0] == argsort
  390. { 2, 1, 1 }, // get_rows->src[1] == view
  391. { 3, 0, 2 }, // reshape->src[0] == get_rows
  392. { 4, 0, 3 }, // soft_max->src[0] == reshape
  393. { 5, 0, 4 }, // reshape->src[0] == soft_max
  394. };
  395. enum topk_moe_mode {
  396. TOPK_MOE_EARLY_SOFTMAX,
  397. TOPK_MOE_EARLY_SOFTMAX_NORM,
  398. TOPK_MOE_LATE_SOFTMAX,
  399. TOPK_MOE_COUNT,
  400. };
  401. static topk_moe_mode ggml_vk_num_additional_ops_to_topk_moe_mode(uint32_t num) {
  402. topk_moe_mode mode = num == topk_moe_early_softmax_norm.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX_NORM :
  403. num == topk_moe_early_softmax.size() - 1 ? TOPK_MOE_EARLY_SOFTMAX :
  404. TOPK_MOE_LATE_SOFTMAX;
  405. return mode;
  406. }
  407. static constexpr std::initializer_list<std::array<int, 3>> rope_view_set_rows_edges {
  408. { 1, 0, 0 }, // view->src[0] == rope
  409. { 2, 0, 1 }, // set_rows->src[0] == view
  410. };
  411. static constexpr std::initializer_list<std::array<int, 3>> rms_norm_mul_rope_view_set_rows_edges {
  412. { 1, 0, 0 }, // mul->src[0] == rms
  413. { 2, 0, 1 }, // rope->src[0] == mul
  414. { 3, 0, 2 }, // view->src[0] == rope
  415. { 4, 0, 3 }, // set_rows->src[0] == view
  416. };
  417. struct vk_device_struct {
  418. std::recursive_mutex mutex;
  419. vk::PhysicalDevice physical_device;
  420. vk::PhysicalDeviceProperties properties;
  421. std::string name;
  422. uint64_t max_memory_allocation_size;
  423. uint64_t max_buffer_size;
  424. uint64_t suballocation_block_size;
  425. bool fp16;
  426. bool bf16;
  427. bool pipeline_robustness;
  428. vk::Device device;
  429. uint32_t vendor_id;
  430. vk::DriverId driver_id;
  431. vk_device_architecture architecture;
  432. vk_queue compute_queue;
  433. vk_queue transfer_queue;
  434. bool single_queue;
  435. uint32_t subgroup_size;
  436. uint32_t shader_core_count;
  437. bool uma;
  438. bool prefer_host_memory;
  439. bool float_controls_rte_fp16;
  440. bool subgroup_arithmetic;
  441. bool subgroup_shuffle;
  442. bool subgroup_ballot;
  443. bool subgroup_clustered;
  444. bool subgroup_vote;
  445. bool multi_add;
  446. bool shader_int64;
  447. bool buffer_device_address;
  448. bool vulkan_memory_model;
  449. bool add_rms_fusion;
  450. uint32_t partials_binding_alignment;
  451. bool integer_dot_product;
  452. // 0: default, 1: force mmvq, -1: disable mmvq
  453. int32_t mmvq_mode;
  454. bool subgroup_size_control;
  455. uint32_t subgroup_min_size;
  456. uint32_t subgroup_max_size;
  457. bool subgroup_require_full_support;
  458. // floor(log2(maxComputeWorkGroupInvocations))
  459. uint32_t max_workgroup_size_log2 {};
  460. bool coopmat_support;
  461. bool coopmat_acc_f32_support {};
  462. bool coopmat_acc_f16_support {};
  463. bool coopmat_bf16_support {};
  464. bool coopmat_support_16x16x16_f16acc {};
  465. bool coopmat_support_16x16x16_f32acc {};
  466. bool coopmat1_fa_support {};
  467. uint32_t coopmat_m;
  468. uint32_t coopmat_n;
  469. uint32_t coopmat_k;
  470. bool coopmat_int_support;
  471. uint32_t coopmat_int_m;
  472. uint32_t coopmat_int_n;
  473. uint32_t coopmat_int_k;
  474. bool coopmat2;
  475. bool pipeline_executable_properties_support {};
  476. size_t idx;
  477. bool mul_mat_l[GGML_TYPE_COUNT];
  478. bool mul_mat_m[GGML_TYPE_COUNT];
  479. bool mul_mat_s[GGML_TYPE_COUNT];
  480. bool mul_mat_id_l[GGML_TYPE_COUNT];
  481. bool mul_mat_id_m[GGML_TYPE_COUNT];
  482. bool mul_mat_id_s[GGML_TYPE_COUNT];
  483. vk::DescriptorSetLayout dsl;
  484. vk_matmul_pipeline pipeline_matmul_f32 {};
  485. vk_matmul_pipeline pipeline_matmul_f32_f16 {};
  486. vk_matmul_pipeline pipeline_matmul_bf16 {};
  487. vk_matmul_pipeline2 pipeline_matmul_f16;
  488. vk_matmul_pipeline2 pipeline_matmul_f16_f32;
  489. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat[GGML_TYPE_COUNT];
  490. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_f16[GGML_TYPE_COUNT];
  491. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_COUNT];
  492. vk_matmul_pipeline pipeline_matmul_id_f32 {};
  493. vk_matmul_pipeline pipeline_matmul_id_bf16 {};
  494. vk_matmul_pipeline2 pipeline_matmul_id_f16;
  495. vk_matmul_pipeline2 pipeline_matmul_id_f16_f32;
  496. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id[GGML_TYPE_COUNT];
  497. vk_matmul_pipeline2 pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_COUNT];
  498. vk_pipeline pipeline_matmul_split_k_reduce;
  499. vk_pipeline pipeline_quantize_q8_1_x4;
  500. vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
  501. vk_pipeline pipeline_dequant_mul_mat_vec_f32_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  502. vk_pipeline pipeline_dequant_mul_mat_vec_f16_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  503. vk_pipeline pipeline_dequant_mul_mat_vec_id_f32[GGML_TYPE_COUNT];
  504. vk_pipeline pipeline_dequant_mul_mat_vec_q8_1_f32[DMMV_WG_SIZE_COUNT][GGML_TYPE_COUNT][mul_mat_vec_max_cols];
  505. vk_pipeline pipeline_mul_mat_vec_p021_f16_f32[p021_max_gqa_ratio];
  506. vk_pipeline pipeline_mul_mat_vec_nc_f16_f32;
  507. vk_pipeline pipeline_get_rows[GGML_TYPE_COUNT];
  508. vk_pipeline pipeline_get_rows_f32[GGML_TYPE_COUNT];
  509. vk_pipeline pipeline_acc_f32;
  510. // [src0 0=fp32,1=fp16][src1 0=fp32,1=fp16][dst 0=fp32,1=fp16]
  511. vk_pipeline pipeline_add[2][2][2];
  512. vk_pipeline pipeline_add_norepeat[2][2][2];
  513. vk_pipeline pipeline_sub[2][2][2];
  514. vk_pipeline pipeline_sub_norepeat[2][2][2];
  515. vk_pipeline pipeline_mul[2][2][2];
  516. vk_pipeline pipeline_mul_norepeat[2][2][2];
  517. vk_pipeline pipeline_div[2][2][2];
  518. vk_pipeline pipeline_div_norepeat[2][2][2];
  519. vk_pipeline pipeline_add_rms[2][2][2];
  520. vk_pipeline pipeline_add_rms_norepeat[2][2][2];
  521. // indexed by num_additional_fused_ops == num_adds - 1
  522. vk_pipeline pipeline_multi_add[MAX_FUSED_ADDS];
  523. vk_pipeline pipeline_multi_add_rms[MAX_FUSED_ADDS];
  524. vk_pipeline pipeline_add_id_f32;
  525. vk_pipeline pipeline_concat_f32, pipeline_concat_f16, pipeline_concat_i32;
  526. vk_pipeline pipeline_upscale_nearest_f32, pipeline_upscale_bilinear_f32, pipeline_upscale_bicubic_f32;
  527. vk_pipeline pipeline_scale_f32;
  528. vk_pipeline pipeline_sqr_f32;
  529. vk_pipeline pipeline_sqrt_f32;
  530. vk_pipeline pipeline_sin_f32;
  531. vk_pipeline pipeline_cos_f32;
  532. vk_pipeline pipeline_log[2];
  533. vk_pipeline pipeline_clamp_f32;
  534. vk_pipeline pipeline_pad_f32;
  535. vk_pipeline pipeline_roll_f32;
  536. vk_pipeline pipeline_repeat_f32, pipeline_repeat_back_f32;
  537. vk_pipeline pipeline_cpy_f32_f32, pipeline_cpy_f32_f16, pipeline_cpy_f16_f16, pipeline_cpy_f16_f32, pipeline_cpy_f32_bf16, pipeline_cpy_f32_i32, pipeline_cpy_i32_f32;
  538. vk_pipeline pipeline_contig_cpy_f32_f32, pipeline_contig_cpy_f32_f16, pipeline_contig_cpy_f16_f16, pipeline_contig_cpy_f16_f32, pipeline_contig_cpy_f32_bf16, pipeline_contig_cpy_f32_i32, pipeline_contig_cpy_i32_f32;
  539. vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
  540. vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
  541. vk_pipeline pipeline_cpy_transpose_16, pipeline_cpy_transpose_32;
  542. vk_pipeline pipeline_set_rows_i32[GGML_TYPE_COUNT];
  543. vk_pipeline pipeline_set_rows_i64[GGML_TYPE_COUNT];
  544. vk_pipeline pipeline_norm_f32;
  545. vk_pipeline pipeline_group_norm_f32;
  546. vk_pipeline pipeline_rms_norm_f32;
  547. vk_pipeline pipeline_rms_norm_mul_f32;
  548. vk_pipeline pipeline_rms_norm_partials_f32;
  549. vk_pipeline pipeline_rms_norm_mul_partials_f32;
  550. vk_pipeline pipeline_rms_norm_mul_rope_f32_f32;
  551. vk_pipeline pipeline_rms_norm_mul_rope_f32_f16;
  552. vk_pipeline pipeline_rms_norm_back_f32;
  553. vk_pipeline pipeline_l2_norm_f32;
  554. // [src/dst 0=fp32,1=fp16]
  555. vk_pipeline pipeline_exp[2];
  556. vk_pipeline pipeline_gelu[2];
  557. vk_pipeline pipeline_gelu_erf[2];
  558. vk_pipeline pipeline_gelu_quick[2];
  559. vk_pipeline pipeline_silu[2];
  560. vk_pipeline pipeline_relu[2];
  561. vk_pipeline pipeline_neg[2];
  562. vk_pipeline pipeline_tanh[2];
  563. vk_pipeline pipeline_sigmoid[2];
  564. vk_pipeline pipeline_hardsigmoid[2];
  565. vk_pipeline pipeline_hardswish[2];
  566. vk_pipeline pipeline_abs[2];
  567. vk_pipeline pipeline_softplus[2];
  568. vk_pipeline pipeline_step[2];
  569. vk_pipeline pipeline_round[2];
  570. vk_pipeline pipeline_ceil[2];
  571. vk_pipeline pipeline_floor[2];
  572. vk_pipeline pipeline_trunc[2];
  573. vk_pipeline pipeline_add1_f16_f16;
  574. vk_pipeline pipeline_add1_f16_f32;
  575. vk_pipeline pipeline_add1_f32_f32;
  576. vk_pipeline pipeline_arange_f32;
  577. vk_pipeline pipeline_fill_f32;
  578. vk_pipeline pipeline_geglu[2];
  579. vk_pipeline pipeline_reglu[2];
  580. vk_pipeline pipeline_swiglu[2];
  581. vk_pipeline pipeline_swiglu_oai[2];
  582. vk_pipeline pipeline_geglu_erf[2];
  583. vk_pipeline pipeline_geglu_quick[2];
  584. vk_pipeline pipeline_leaky_relu_f32;
  585. vk_pipeline pipeline_silu_back_f32;
  586. vk_pipeline pipeline_diag_mask_inf_f32;
  587. vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16;
  588. vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512;
  589. vk_pipeline pipeline_soft_max_back_f32;
  590. vk_pipeline pipeline_rope_norm_f32, pipeline_rope_norm_f16, pipeline_rope_norm_f32_f16;
  591. vk_pipeline pipeline_rope_neox_f32, pipeline_rope_neox_f16, pipeline_rope_neox_f32_f16;
  592. vk_pipeline pipeline_rope_multi_f32, pipeline_rope_multi_f16;
  593. vk_pipeline pipeline_rope_vision_f32, pipeline_rope_vision_f16;
  594. vk_pipeline pipeline_argsort_f32[num_argsort_pipelines];
  595. vk_pipeline pipeline_argsort_large_f32[num_argsort_pipelines];
  596. vk_pipeline pipeline_sum_rows_f32;
  597. vk_pipeline pipeline_argmax_f32;
  598. vk_pipeline pipeline_count_equal_i32;
  599. vk_pipeline pipeline_im2col_f32, pipeline_im2col_f32_f16;
  600. vk_pipeline pipeline_im2col_3d_f32, pipeline_im2col_3d_f32_f16;
  601. vk_pipeline pipeline_timestep_embedding_f32;
  602. vk_pipeline pipeline_conv_transpose_1d_f32;
  603. vk_pipeline pipeline_pool2d_f32;
  604. vk_pipeline pipeline_rwkv_wkv6_f32;
  605. vk_pipeline pipeline_rwkv_wkv7_f32;
  606. vk_pipeline pipeline_ssm_scan_f32_d128;
  607. vk_pipeline pipeline_ssm_scan_f32_d256;
  608. vk_pipeline pipeline_ssm_conv_f32;
  609. vk_pipeline pipeline_opt_step_adamw_f32;
  610. vk_pipeline pipeline_opt_step_sgd_f32;
  611. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f32[CONV_SHAPE_COUNT];
  612. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv2d_f16_f32[CONV_SHAPE_COUNT];
  613. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f32[CONV_SHAPE_COUNT];
  614. std::map<vk_conv2d_pipeline_state, vk_pipeline> pipeline_conv_transpose_2d_f16_f32[CONV_SHAPE_COUNT];
  615. vk_pipeline pipeline_conv2d_dw_whcn_f32, pipeline_conv2d_dw_whcn_f16_f32;
  616. vk_pipeline pipeline_conv2d_dw_cwhn_f32, pipeline_conv2d_dw_cwhn_f16_f32;
  617. std::map<vk_fa_pipeline_state, vk_pipeline> pipeline_flash_attn_f32_f16[GGML_TYPE_COUNT];
  618. vk_pipeline pipeline_flash_attn_split_k_reduce;
  619. vk_pipeline pipeline_topk_moe[num_topk_moe_pipelines][TOPK_MOE_COUNT];
  620. std::vector<vk_pipeline_ref> all_pipelines;
  621. std::vector<std::tuple<void*, size_t, vk_buffer>> pinned_memory;
  622. vk::Fence fence;
  623. vk_buffer sync_staging;
  624. ggml_backend_buffer_type buffer_type;
  625. bool disable_fusion;
  626. bool disable_host_visible_vidmem;
  627. bool allow_sysmem_fallback;
  628. bool disable_graph_optimize;
  629. #ifdef GGML_VULKAN_MEMORY_DEBUG
  630. std::unique_ptr<vk_memory_logger> memory_logger;
  631. #endif
  632. // for GGML_VK_PERF_LOGGER
  633. std::unique_ptr<vk_perf_logger> perf_logger;
  634. vk::QueryPool query_pool;
  635. int32_t num_queries;
  636. ~vk_device_struct() {
  637. VK_LOG_DEBUG("destroy device " << name);
  638. device.destroyFence(fence);
  639. ggml_vk_destroy_buffer(sync_staging);
  640. compute_queue.cmd_pool.destroy(device);
  641. transfer_queue.cmd_pool.destroy(device);
  642. for (auto& pipeline : all_pipelines) {
  643. if (pipeline.expired()) {
  644. continue;
  645. }
  646. vk_pipeline pl = pipeline.lock();
  647. ggml_vk_destroy_pipeline(device, pl);
  648. }
  649. all_pipelines.clear();
  650. device.destroyDescriptorSetLayout(dsl);
  651. device.destroy();
  652. }
  653. };
  654. void vk_command_pool::init(vk_device& device, vk_queue *q_) {
  655. cmd_buffer_idx = 0;
  656. q = q_;
  657. vk::CommandPoolCreateInfo command_pool_create_info(vk::CommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_TRANSIENT_BIT), q->queue_family_index);
  658. pool = device->device.createCommandPool(command_pool_create_info);
  659. }
  660. void vk_command_pool::destroy(vk::Device& device) {
  661. device.destroyCommandPool(pool);
  662. pool = nullptr;
  663. cmd_buffers.clear();
  664. }
  665. struct vk_buffer_struct {
  666. vk::Buffer buffer = VK_NULL_HANDLE;
  667. vk::DeviceMemory device_memory = VK_NULL_HANDLE;
  668. vk::MemoryPropertyFlags memory_property_flags;
  669. void * ptr;
  670. size_t size = 0;
  671. vk::DeviceAddress bda_addr {};
  672. vk_device device;
  673. ~vk_buffer_struct() {
  674. if (size == 0) {
  675. return;
  676. }
  677. VK_LOG_DEBUG("~vk_buffer_struct(" << buffer << ", " << size << ")");
  678. device->device.freeMemory(device_memory);
  679. device->device.destroyBuffer(buffer);
  680. }
  681. };
  682. struct vk_subbuffer {
  683. vk_buffer buffer;
  684. uint64_t offset;
  685. uint64_t size;
  686. operator vk::DescriptorBufferInfo() const {
  687. return { buffer->buffer, offset, size };
  688. }
  689. };
  690. struct vk_semaphore {
  691. vk::Semaphore s;
  692. uint64_t value;
  693. };
  694. struct vk_submission {
  695. vk::CommandBuffer buffer;
  696. std::vector<vk_semaphore> wait_semaphores;
  697. std::vector<vk_semaphore> signal_semaphores;
  698. };
  699. typedef std::vector<vk_submission> vk_sequence;
  700. struct vk_mat_mat_push_constants {
  701. uint32_t M; uint32_t N; uint32_t K;
  702. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  703. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  704. uint32_t k_split;
  705. uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3;
  706. uint32_t padded_N;
  707. };
  708. #define MAT_VEC_FUSION_FLAGS_BIAS0 0x1
  709. #define MAT_VEC_FUSION_FLAGS_BIAS1 0x2
  710. #define MAT_VEC_FUSION_FLAGS_SCALE0 0x4
  711. #define MAT_VEC_FUSION_FLAGS_SCALE1 0x8
  712. struct vk_mat_vec_push_constants {
  713. uint32_t ncols;
  714. uint32_t stride_a;
  715. uint32_t stride_b;
  716. uint32_t stride_d;
  717. uint32_t batch_stride_a;
  718. uint32_t batch_stride_b;
  719. uint32_t batch_stride_d;
  720. uint32_t fusion_flags;
  721. uint32_t ne02;
  722. uint32_t ne12;
  723. uint32_t broadcast2;
  724. uint32_t broadcast3;
  725. };
  726. struct vk_mat_vec_p021_push_constants {
  727. uint32_t ncols_x;
  728. uint32_t nrows_x;
  729. uint32_t nchannels_x;
  730. uint32_t nchannels_y;
  731. uint32_t b_offset;
  732. uint32_t d_offset;
  733. uint32_t fusion_flags;
  734. };
  735. struct vk_mat_vec_nc_push_constants {
  736. uint32_t ncols_x;
  737. uint32_t nrows_x;
  738. uint32_t row_stride_x;
  739. uint32_t channel_stride_x;
  740. uint32_t channel_stride_y;
  741. uint32_t channel_x_divisor;
  742. uint32_t ne12;
  743. uint32_t b_offset;
  744. uint32_t d_offset;
  745. uint32_t nb03;
  746. uint32_t nb13;
  747. uint32_t nb23;
  748. uint32_t fusion_flags;
  749. };
  750. struct vk_mat_mat_id_push_constants {
  751. uint32_t M; uint32_t N; uint32_t K;
  752. uint32_t stride_a; uint32_t stride_b; uint32_t stride_d;
  753. uint32_t batch_stride_a; uint32_t batch_stride_b; uint32_t batch_stride_d;
  754. uint32_t nei0; uint32_t nei1; uint32_t nbi1; uint32_t ne11;
  755. uint32_t padded_N;
  756. };
  757. struct vk_mat_vec_id_push_constants {
  758. uint32_t ncols;
  759. uint32_t stride_a;
  760. uint32_t stride_b;
  761. uint32_t stride_d;
  762. uint32_t batch_stride_a;
  763. uint32_t batch_stride_b;
  764. uint32_t batch_stride_d;
  765. uint32_t fusion_flags;
  766. uint32_t nei0;
  767. uint32_t ne11;
  768. };
  769. struct vk_flash_attn_push_constants {
  770. uint32_t N;
  771. uint32_t KV;
  772. uint32_t ne1;
  773. uint32_t ne2;
  774. uint32_t ne3;
  775. uint32_t neq2;
  776. uint32_t neq3;
  777. uint32_t nek2;
  778. uint32_t nek3;
  779. uint32_t nev2;
  780. uint32_t nev3;
  781. uint32_t nem1;
  782. uint32_t nem2;
  783. uint32_t nem3;
  784. uint32_t nb01;
  785. uint32_t nb02;
  786. uint32_t nb03;
  787. uint32_t nb11;
  788. uint32_t nb12;
  789. uint32_t nb13;
  790. uint32_t nb21;
  791. uint32_t nb22;
  792. uint32_t nb23;
  793. float scale;
  794. float max_bias;
  795. float logit_softcap;
  796. uint32_t mask_n_head_log2;
  797. float m0;
  798. float m1;
  799. uint32_t gqa_ratio;
  800. uint32_t split_kv;
  801. uint32_t k_num;
  802. };
  803. static_assert(sizeof(vk_flash_attn_push_constants) <= 128, "sizeof(vk_flash_attn_push_constants) must be <= 128");
  804. struct vk_op_push_constants {
  805. uint32_t KX;
  806. uint32_t KY;
  807. float param1;
  808. float param2;
  809. };
  810. struct vk_op_glu_push_constants {
  811. uint32_t N;
  812. uint32_t ne00;
  813. uint32_t ne20;
  814. uint32_t mode; // 0: default, 1: swapped, 2: split
  815. float alpha; // for swiglu_oai
  816. float limit;
  817. };
  818. struct vk_op_unary_push_constants {
  819. uint32_t ne;
  820. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  821. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  822. uint32_t misalign_offsets;
  823. float param1; float param2;
  824. uint32_t ne0_012mp; uint32_t ne0_012L;
  825. uint32_t ne0_01mp; uint32_t ne0_01L;
  826. uint32_t ne0_0mp; uint32_t ne0_0L;
  827. uint32_t ne1_012mp; uint32_t ne1_012L;
  828. uint32_t ne1_01mp; uint32_t ne1_01L;
  829. uint32_t ne1_0mp; uint32_t ne1_0L;
  830. };
  831. static_assert(sizeof(vk_op_unary_push_constants) <= 128, "sizeof(vk_op_unary_push_constants) must be <= 128");
  832. static vk_op_unary_push_constants vk_op_unary_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst, int64_t ne = 0) {
  833. GGML_ASSERT(ne != 0 || (ggml_nelements(src0) == ggml_nelements(dst)));
  834. ne = ne != 0 ? ne : ggml_nelements(dst);
  835. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  836. vk_op_unary_push_constants p{};
  837. p.ne = (uint32_t)ne;
  838. size_t src0_tsize = ggml_type_size(src0->type);
  839. p.ne00 = (uint32_t)src0->ne[0];
  840. p.ne01 = (uint32_t)src0->ne[1];
  841. p.ne02 = (uint32_t)src0->ne[2];
  842. p.ne03 = (uint32_t)src0->ne[3];
  843. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  844. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  845. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  846. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  847. size_t dst_tsize = ggml_type_size(dst->type);
  848. p.ne10 = (uint32_t)dst->ne[0];
  849. p.ne11 = (uint32_t)dst->ne[1];
  850. p.ne12 = (uint32_t)dst->ne[2];
  851. p.ne13 = (uint32_t)dst->ne[3];
  852. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  853. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  854. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  855. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  856. return p; // offsets are initialized later in ggml_vk_op
  857. }
  858. struct vk_op_pad_push_constants {
  859. uint32_t ne;
  860. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  861. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  862. uint32_t misalign_offsets;
  863. uint32_t lp0; uint32_t rp0;
  864. uint32_t lp1; uint32_t rp1;
  865. uint32_t lp2; uint32_t rp2;
  866. uint32_t lp3; uint32_t rp3;
  867. };
  868. static vk_op_pad_push_constants vk_op_pad_push_constants_init(const ggml_tensor * src0, const ggml_tensor * dst) {
  869. int64_t ne = ggml_nelements(dst);
  870. GGML_ASSERT(ne <= (int64_t)std::numeric_limits<uint32_t>::max());
  871. vk_op_pad_push_constants p{};
  872. p.ne = (uint32_t)ne;
  873. size_t src0_tsize = ggml_type_size(src0->type);
  874. p.ne00 = (uint32_t)src0->ne[0];
  875. p.ne01 = (uint32_t)src0->ne[1];
  876. p.ne02 = (uint32_t)src0->ne[2];
  877. p.ne03 = (uint32_t)src0->ne[3];
  878. p.nb00 = (uint32_t)(src0->nb[0] / src0_tsize);
  879. p.nb01 = (uint32_t)(src0->nb[1] / src0_tsize);
  880. p.nb02 = (uint32_t)(src0->nb[2] / src0_tsize);
  881. p.nb03 = (uint32_t)(src0->nb[3] / src0_tsize);
  882. size_t dst_tsize = ggml_type_size(dst->type);
  883. p.ne10 = (uint32_t)dst->ne[0];
  884. p.ne11 = (uint32_t)dst->ne[1];
  885. p.ne12 = (uint32_t)dst->ne[2];
  886. p.ne13 = (uint32_t)dst->ne[3];
  887. p.nb10 = (uint32_t)(dst->nb[0] / dst_tsize);
  888. p.nb11 = (uint32_t)(dst->nb[1] / dst_tsize);
  889. p.nb12 = (uint32_t)(dst->nb[2] / dst_tsize);
  890. p.nb13 = (uint32_t)(dst->nb[3] / dst_tsize);
  891. p.lp0 = dst->op_params[0];
  892. p.rp0 = dst->op_params[1];
  893. p.lp1 = dst->op_params[2];
  894. p.rp1 = dst->op_params[3];
  895. p.lp2 = dst->op_params[4];
  896. p.rp2 = dst->op_params[5];
  897. p.lp3 = dst->op_params[6];
  898. p.rp3 = dst->op_params[7];
  899. return p; // fastdiv values and offsets are initialized later in ggml_vk_op
  900. }
  901. // See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1.
  902. // Precompute mp (m' in the paper) and L such that division
  903. // can be computed using a multiply (high 32b of 64b result)
  904. // and a shift:
  905. //
  906. // n/d = (mulhi(n, mp) + n) >> L;
  907. static void init_fastdiv_values(uint32_t d, uint32_t &mp, uint32_t &L)
  908. {
  909. // compute L = ceil(log2(d));
  910. L = 0;
  911. while (L < 32 && (uint32_t{1} << L) < d) {
  912. L++;
  913. }
  914. mp = (uint32_t)((uint64_t{1} << 32) * ((uint64_t{1} << L) - d) / d + 1);
  915. }
  916. template <typename T> void init_pushconst_fastdiv(T &p) {
  917. GGML_UNUSED(p);
  918. static_assert(!std::is_const<T>::value, "unexpected type");
  919. }
  920. template <> void init_pushconst_fastdiv(vk_op_unary_push_constants &p) {
  921. // Compute magic values to divide by these six numbers.
  922. init_fastdiv_values(p.ne02*p.ne01*p.ne00, p.ne0_012mp, p.ne0_012L);
  923. init_fastdiv_values(p.ne01*p.ne00, p.ne0_01mp, p.ne0_01L);
  924. init_fastdiv_values(p.ne00, p.ne0_0mp, p.ne0_0L);
  925. init_fastdiv_values(p.ne12*p.ne11*p.ne10, p.ne1_012mp, p.ne1_012L);
  926. init_fastdiv_values(p.ne11*p.ne10, p.ne1_01mp, p.ne1_01L);
  927. init_fastdiv_values(p.ne10, p.ne1_0mp, p.ne1_0L);
  928. }
  929. struct vk_op_binary_push_constants {
  930. uint32_t ne;
  931. uint32_t ne00; uint32_t ne01; uint32_t ne02; uint32_t ne03; uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  932. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13; uint32_t nb10; uint32_t nb11; uint32_t nb12; uint32_t nb13;
  933. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23; uint32_t nb20; uint32_t nb21; uint32_t nb22; uint32_t nb23;
  934. uint32_t misalign_offsets;
  935. float param1; float param2; int32_t param3;
  936. };
  937. struct vk_op_multi_add_push_constants {
  938. // shape for dst
  939. uint32_t ne20; uint32_t ne21; uint32_t ne22; uint32_t ne23;
  940. // strides for srcs+dst
  941. uint32_t nb[MAX_PARAMETER_COUNT][4];
  942. uint32_t rms_partials;
  943. };
  944. // update multi_add.comp if this changes
  945. static_assert(MAX_PARAMETER_COUNT == 12);
  946. static_assert(sizeof(vk_op_multi_add_push_constants) <= 256);
  947. struct vk_op_topk_moe_push_constants {
  948. uint32_t n_rows;
  949. uint32_t n_expert_used;
  950. float clamp_min;
  951. float clamp_max;
  952. };
  953. struct vk_op_add_id_push_constants {
  954. uint32_t ne0;
  955. uint32_t ne1;
  956. uint32_t s01;
  957. uint32_t s02;
  958. uint32_t s11;
  959. uint32_t s21;
  960. };
  961. struct vk_op_diag_mask_push_constants {
  962. uint32_t ncols;
  963. uint32_t rows_per_channel;
  964. int32_t n_past;
  965. };
  966. struct vk_op_rope_push_constants {
  967. uint32_t rope_mode;
  968. uint32_t ncols;
  969. uint32_t n_dims;
  970. float freq_scale;
  971. uint32_t p_delta_rows;
  972. float freq_base;
  973. float ext_factor;
  974. float attn_factor;
  975. float corr_dims[2];
  976. float theta_scale;
  977. uint32_t has_ff;
  978. uint32_t ne02;
  979. uint32_t s1;
  980. uint32_t s2;
  981. int32_t sections[4];
  982. uint32_t is_imrope;
  983. uint32_t is_back;
  984. uint32_t set_rows_stride;
  985. };
  986. // For fused rms_norm+mul+rope(+view+set_rows)
  987. struct vk_op_rms_norm_mul_rope_push_constants {
  988. vk_op_binary_push_constants bin;
  989. vk_op_rope_push_constants rope;
  990. };
  991. struct vk_op_soft_max_push_constants {
  992. uint32_t KX;
  993. uint32_t KY;
  994. uint32_t ne00;
  995. uint32_t ne01;
  996. uint32_t ne02;
  997. uint32_t ne12;
  998. uint32_t ne13;
  999. uint32_t nb11;
  1000. uint32_t nb12;
  1001. uint32_t nb13;
  1002. float scale;
  1003. float max_bias;
  1004. float m0;
  1005. float m1;
  1006. uint32_t n_head_log2;
  1007. uint32_t nrows_x;
  1008. uint32_t has_sinks;
  1009. };
  1010. struct vk_op_argsort_push_constants {
  1011. uint32_t ncols;
  1012. uint32_t ncols_padded;
  1013. uint32_t ncols_padded_log2;
  1014. uint32_t nrows;
  1015. uint32_t order;
  1016. uint32_t outer_start;
  1017. uint32_t outer_end;
  1018. uint32_t inner_start;
  1019. uint32_t inner_end;
  1020. };
  1021. struct vk_op_im2col_push_constants {
  1022. uint64_t dst_addr;
  1023. uint32_t batch_offset; uint32_t offset_delta;
  1024. uint32_t IC;
  1025. uint32_t IW; uint32_t IH;
  1026. uint32_t OW; uint32_t OH;
  1027. uint32_t KW; uint32_t KH;
  1028. uint32_t pelements;
  1029. uint32_t CHW;
  1030. int32_t s0; int32_t s1;
  1031. int32_t p0; int32_t p1;
  1032. int32_t d0; int32_t d1;
  1033. };
  1034. struct vk_op_im2col_3d_push_constants {
  1035. uint64_t dst_addr;
  1036. uint32_t nb10;
  1037. uint32_t nb11;
  1038. uint32_t nb12;
  1039. uint32_t nb13;
  1040. uint32_t s0;
  1041. uint32_t s1;
  1042. uint32_t s2;
  1043. uint32_t p0;
  1044. uint32_t p1;
  1045. uint32_t p2;
  1046. uint32_t d0;
  1047. uint32_t d1;
  1048. uint32_t d2;
  1049. uint32_t IW;
  1050. uint32_t IH;
  1051. uint32_t ID;
  1052. uint32_t IC;
  1053. uint32_t KW;
  1054. uint32_t OH;
  1055. uint32_t KD_KH_KW;
  1056. uint32_t KH_KW;
  1057. uint32_t IC_KD_KH_KW;
  1058. uint32_t N_OD_OH;
  1059. uint32_t OD_OH;
  1060. uint32_t OD_OH_OW_IC_KD_KH_KW;
  1061. uint32_t OH_OW_IC_KD_KH_KW;
  1062. uint32_t OW_IC_KD_KH_KW;
  1063. uint32_t misalign_offsets;
  1064. };
  1065. struct vk_op_timestep_embedding_push_constants {
  1066. uint32_t nb1;
  1067. uint32_t dim;
  1068. uint32_t max_period;
  1069. };
  1070. struct vk_op_conv_transpose_1d_push_constants {
  1071. uint32_t Cout;
  1072. uint32_t Cin;
  1073. uint32_t K;
  1074. uint32_t L;
  1075. uint32_t KL;
  1076. uint32_t nb01;
  1077. uint32_t nb02;
  1078. uint32_t nb11;
  1079. uint32_t nb1;
  1080. int32_t s0;
  1081. };
  1082. struct vk_op_pool2d_push_constants {
  1083. uint32_t IW; uint32_t IH;
  1084. uint32_t OW; uint32_t OH;
  1085. uint32_t OC;
  1086. uint32_t pelements;
  1087. uint32_t op;
  1088. int32_t k0; int32_t k1;
  1089. int32_t s0; int32_t s1;
  1090. int32_t p0; int32_t p1;
  1091. };
  1092. struct vk_op_rwkv_wkv6_push_constants {
  1093. uint32_t B;
  1094. uint32_t T;
  1095. uint32_t C;
  1096. uint32_t H;
  1097. };
  1098. struct vk_op_rwkv_wkv7_push_constants {
  1099. uint32_t B;
  1100. uint32_t T;
  1101. uint32_t C;
  1102. uint32_t H;
  1103. };
  1104. struct vk_op_ssm_scan_push_constants {
  1105. uint32_t nb02, nb03, nb12, nb13;
  1106. uint32_t nb21, nb22, nb31;
  1107. uint32_t nb42, nb43, nb52, nb53;
  1108. uint32_t s_off;
  1109. uint32_t n_head, d_head, n_group, n_tok;
  1110. };
  1111. struct vk_op_ssm_conv_push_constants {
  1112. uint32_t nb01, nb02;
  1113. uint32_t nb11;
  1114. uint32_t dst_nb0, dst_nb1, dst_nb2;
  1115. uint32_t nc, ncs, nr, n_t, n_s;
  1116. };
  1117. struct vk_op_conv2d_push_constants {
  1118. uint32_t Cout;
  1119. uint32_t Cin;
  1120. uint32_t N;
  1121. uint32_t KW;
  1122. uint32_t KH;
  1123. uint32_t W;
  1124. uint32_t H;
  1125. uint32_t OW;
  1126. uint32_t OH;
  1127. uint32_t s0;
  1128. uint32_t s1;
  1129. uint32_t p0;
  1130. uint32_t p1;
  1131. uint32_t d0;
  1132. uint32_t d1;
  1133. uint32_t nb01;
  1134. uint32_t nb02;
  1135. uint32_t nb03;
  1136. uint32_t nb11;
  1137. uint32_t nb12;
  1138. uint32_t nb13;
  1139. uint32_t nb1;
  1140. uint32_t nb2;
  1141. uint32_t nb3;
  1142. // init_fastdiv_values constants for dividing by OW, OW*OH
  1143. uint32_t OWmp; uint32_t OWL;
  1144. uint32_t OWOHmp; uint32_t OWOHL;
  1145. };
  1146. template <> void init_pushconst_fastdiv(vk_op_conv2d_push_constants &p) {
  1147. // Compute magic values to divide by OW, OW*OH
  1148. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1149. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1150. }
  1151. struct vk_op_conv_transpose_2d_push_constants {
  1152. uint32_t Cout;
  1153. uint32_t Cin;
  1154. uint32_t N;
  1155. uint32_t KW;
  1156. uint32_t KH;
  1157. uint32_t W;
  1158. uint32_t H;
  1159. uint32_t OW;
  1160. uint32_t OH;
  1161. uint32_t s0;
  1162. uint32_t s1;
  1163. uint32_t p0;
  1164. uint32_t p1;
  1165. uint32_t d0;
  1166. uint32_t d1;
  1167. uint32_t nb01;
  1168. uint32_t nb02;
  1169. uint32_t nb03;
  1170. uint32_t nb11;
  1171. uint32_t nb12;
  1172. uint32_t nb13;
  1173. uint32_t nb1;
  1174. uint32_t nb2;
  1175. uint32_t nb3;
  1176. // init_fastdiv_values constants for dividing by OW, OW*OH
  1177. uint32_t OWmp; uint32_t OWL;
  1178. uint32_t OWOHmp; uint32_t OWOHL;
  1179. };
  1180. template <> void init_pushconst_fastdiv(vk_op_conv_transpose_2d_push_constants &p) {
  1181. // Compute magic values to divide by OW, OW*OH
  1182. init_fastdiv_values(p.OW, p.OWmp, p.OWL);
  1183. init_fastdiv_values(p.OW*p.OH, p.OWOHmp, p.OWOHL);
  1184. }
  1185. struct vk_op_conv2d_dw_push_constants {
  1186. uint32_t ne;
  1187. uint32_t batches;
  1188. uint32_t channels;
  1189. uint32_t dst_w;
  1190. uint32_t dst_h;
  1191. uint32_t src_w;
  1192. uint32_t src_h;
  1193. uint32_t knl_w;
  1194. uint32_t knl_h;
  1195. int32_t stride_x;
  1196. int32_t stride_y;
  1197. int32_t pad_x;
  1198. int32_t pad_y;
  1199. int32_t dilation_x;
  1200. int32_t dilation_y;
  1201. };
  1202. struct vk_op_upscale_push_constants {
  1203. uint32_t ne; uint32_t a_offset; uint32_t d_offset;
  1204. uint32_t ne00; uint32_t ne01;
  1205. uint32_t nb00; uint32_t nb01; uint32_t nb02; uint32_t nb03;
  1206. uint32_t ne10; uint32_t ne11; uint32_t ne12; uint32_t ne13;
  1207. float sf0; float sf1; float sf2; float sf3;
  1208. float pixel_offset;
  1209. };
  1210. struct vk_op_sum_rows_push_constants
  1211. {
  1212. uint32_t n_cols;
  1213. uint32_t ne01, ne02;
  1214. uint32_t nb01, nb02, nb03;
  1215. uint32_t nb11, nb12, nb13;
  1216. float weight;
  1217. uint32_t misalign_offsets;
  1218. uint32_t ne0_12mp, ne0_12L;
  1219. uint32_t ne0_1mp, ne0_1L;
  1220. };
  1221. static vk_op_sum_rows_push_constants vk_op_sum_rows_push_constants_init(const ggml_tensor * src, const ggml_tensor * dst, int64_t n_cols) {
  1222. uint32_t type_size = (uint32_t)ggml_type_size(src->type);
  1223. vk_op_sum_rows_push_constants p = {};
  1224. p.n_cols = (uint32_t)n_cols;
  1225. p.ne01 = (uint32_t)src->ne[1];
  1226. p.ne02 = (uint32_t)src->ne[2];
  1227. p.nb01 = (uint32_t)src->nb[1] / type_size;
  1228. p.nb02 = (uint32_t)src->nb[2] / type_size;
  1229. p.nb03 = (uint32_t)src->nb[3] / type_size;
  1230. p.nb11 = (uint32_t)dst->nb[1] / type_size;
  1231. p.nb12 = (uint32_t)dst->nb[2] / type_size;
  1232. p.nb13 = (uint32_t)dst->nb[3] / type_size;
  1233. p.weight = 1.0f;
  1234. return p;
  1235. }
  1236. template <> void init_pushconst_fastdiv(vk_op_sum_rows_push_constants &p) {
  1237. init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L);
  1238. init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L);
  1239. }
  1240. // Allow pre-recording command buffers
  1241. struct vk_staging_memcpy {
  1242. vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
  1243. void * dst;
  1244. const void * src;
  1245. size_t n;
  1246. };
  1247. struct vk_staging_memset {
  1248. vk_staging_memset(void * _dst, uint32_t _val, size_t _n) : dst(_dst), val(_val), n(_n) {}
  1249. void * dst;
  1250. uint32_t val;
  1251. size_t n;
  1252. };
  1253. struct vk_context_struct {
  1254. vk_submission * s;
  1255. std::vector<vk_sequence> seqs;
  1256. int exit_tensor_idx;
  1257. std::vector<vk_staging_memcpy> in_memcpys;
  1258. std::vector<vk_staging_memcpy> out_memcpys;
  1259. std::vector<vk_staging_memset> memsets;
  1260. vk_command_pool * p {};
  1261. };
  1262. typedef std::shared_ptr<vk_context_struct> vk_context;
  1263. typedef std::weak_ptr<vk_context_struct> vk_context_ref;
  1264. struct ggml_vk_garbage_collector {
  1265. std::vector<vk_semaphore> tl_semaphores;
  1266. std::vector<vk_semaphore> semaphores;
  1267. std::vector<vk::Event> events;
  1268. std::vector<vk_context> contexts;
  1269. };
  1270. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx);
  1271. static void ggml_vk_load_shaders(vk_device& device);
  1272. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx);
  1273. #if defined(GGML_VULKAN_MEMORY_DEBUG) || defined(GGML_VULKAN_DEBUG)
  1274. #define VK_LOG_MEMORY(msg) std::cerr << "ggml_vulkan memory: " << msg << std::endl
  1275. static std::string format_size(size_t size) {
  1276. const size_t kib = 1024;
  1277. const size_t mib = kib * 1024;
  1278. const size_t gib = mib * 1024;
  1279. std::ostringstream oss;
  1280. oss << std::fixed << std::setprecision(2);
  1281. if (size >= gib) {
  1282. oss << static_cast<double>(size) / gib << " GiB";
  1283. } else if (size >= mib) {
  1284. oss << static_cast<double>(size) / mib << " MiB";
  1285. } else if (size >= kib) {
  1286. oss << static_cast<double>(size) / kib << " KiB";
  1287. } else {
  1288. oss << size << " B";
  1289. }
  1290. return oss.str();
  1291. }
  1292. class vk_memory_logger {
  1293. public:
  1294. vk_memory_logger(): total_device(0), total_host(0) {}
  1295. void log_allocation(vk_buffer_ref buf_ref, size_t size);
  1296. void log_deallocation(vk_buffer_ref buf_ref);
  1297. private:
  1298. std::map<vk::Buffer, size_t> allocations; // Track allocations
  1299. size_t total_device;
  1300. size_t total_host;
  1301. };
  1302. #else
  1303. #define VK_LOG_MEMORY(msg) ((void) 0)
  1304. #endif // GGML_VULKAN_MEMORY_DEBUG
  1305. class vk_perf_logger {
  1306. public:
  1307. void print_timings() {
  1308. if (timings.empty()) {
  1309. return;
  1310. }
  1311. uint64_t total_all_op_times = 0;
  1312. std::cerr << "----------------\nVulkan Timings:" << std::endl;
  1313. for (const auto & t : timings) {
  1314. uint64_t total_op_times = 0;
  1315. for (const auto & time : t.second) {
  1316. total_op_times += time;
  1317. }
  1318. std::cerr << t.first << ": " << t.second.size() << " x " << (total_op_times / t.second.size() / 1000.0)
  1319. << " us";
  1320. // If we have as many flops entries as timing entries for the op, then compute and log the flops/S.
  1321. auto it = flops.find(t.first);
  1322. if (it != flops.end() && (it->second).size() == t.second.size()) {
  1323. uint64_t total_op_flops = 0;
  1324. for (const auto & elem : it->second) {
  1325. total_op_flops += elem;
  1326. }
  1327. std::cerr << " ("
  1328. << (double(total_op_flops) / (1000.0 * 1000.0 * 1000.0)) /
  1329. (double(total_op_times) / (1000.0 * 1000.0 * 1000.0))
  1330. << " GFLOPS/s)";
  1331. }
  1332. total_all_op_times += total_op_times;
  1333. std::cerr << std::endl;
  1334. }
  1335. if (timings.size() > 0) {
  1336. std::cerr << "Total time: " << total_all_op_times / 1000.0 << " us." << std::endl;
  1337. }
  1338. timings.clear();
  1339. flops.clear();
  1340. }
  1341. void log_timing(const ggml_tensor * node, uint64_t time) {
  1342. if (node->op == GGML_OP_UNARY) {
  1343. timings[ggml_unary_op_name(ggml_get_unary_op(node))].push_back(time);
  1344. return;
  1345. }
  1346. if (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) {
  1347. const uint64_t m = node->src[0]->ne[1];
  1348. const uint64_t n = node->ne[1];
  1349. const uint64_t k = node->src[1]->ne[0];
  1350. const uint64_t batch = node->src[1]->ne[2] * node->src[1]->ne[3];
  1351. std::string name = ggml_op_name(node->op);
  1352. if ((node->op == GGML_OP_MUL_MAT && n <= mul_mat_vec_max_cols) ||
  1353. (node->op == GGML_OP_MUL_MAT_ID && node->src[2]->ne[1] == 1)) {
  1354. name += "_VEC";
  1355. }
  1356. name += " ";
  1357. name += ggml_type_name(node->src[0]->type);
  1358. name += " m=" + std::to_string(m) + " n=" + std::to_string(n) + " k=" + std::to_string(k);
  1359. if (batch > 1) {
  1360. name += " batch=" + std::to_string(batch);
  1361. }
  1362. timings[name].push_back(time);
  1363. flops[name].push_back(m * n * (k + (k - 1)) * batch);
  1364. return;
  1365. }
  1366. if (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_TRANSPOSE_2D) {
  1367. std::string name = ggml_op_name(node->op);
  1368. ggml_tensor * knl = node->src[0];
  1369. uint64_t OW = node->ne[0];
  1370. uint64_t OH = node->ne[1];
  1371. uint64_t N = node->ne[3];
  1372. uint64_t Cout = node->ne[2];
  1373. uint64_t KW = knl->ne[0];
  1374. uint64_t KH = knl->ne[1];
  1375. uint64_t Cin = node->src[1]->ne[2];
  1376. // KxCRS @ CRSxNPQ = KxNPQ -> M=K, K=CRS, N=NPQ
  1377. uint64_t size_M = Cout;
  1378. uint64_t size_K = Cin * KW * KH;
  1379. uint64_t size_N = N * OW * OH;
  1380. uint64_t n_flops = size_M * size_N * (size_K + (size_K - 1));
  1381. name += " M=Cout=" + std::to_string(size_M) + ", K=Cin*KW*KH=" + std::to_string(size_K) +
  1382. ", N=N*OW*OH=" + std::to_string(size_N);
  1383. flops[name].push_back(n_flops);
  1384. timings[name].push_back(time);
  1385. return;
  1386. }
  1387. if (node->op == GGML_OP_RMS_NORM) {
  1388. std::string name = ggml_op_name(node->op);
  1389. name += "(" + std::to_string(node->ne[0]) + "," + std::to_string(node->ne[1]) + "," + std::to_string(node->ne[2]) + "," + std::to_string(node->ne[3]) + ")";
  1390. timings[name].push_back(time);
  1391. return;
  1392. }
  1393. timings[ggml_op_name(node->op)].push_back(time);
  1394. }
  1395. private:
  1396. std::map<std::string, std::vector<uint64_t>> timings;
  1397. std::map<std::string, std::vector<uint64_t>> flops;
  1398. };
  1399. struct ggml_backend_vk_context {
  1400. std::string name;
  1401. vk_device device;
  1402. size_t semaphore_idx, event_idx;
  1403. ggml_vk_garbage_collector gc;
  1404. size_t prealloc_size_x, prealloc_size_y, prealloc_size_split_k, prealloc_size_add_rms_partials, prealloc_size_add_rms_partials_offset;
  1405. vk_buffer prealloc_x, prealloc_y, prealloc_split_k, prealloc_add_rms_partials, sync_staging;
  1406. vk::Fence fence, almost_ready_fence;
  1407. bool submit_pending {};
  1408. bool almost_ready_fence_pending {};
  1409. // Set before op_add and unset after op_rms_norm to indicate that the add should
  1410. // write partial sums to accumulate the square of the vector components
  1411. bool do_add_rms_partials_offset_calculation;
  1412. bool do_add_rms_partials;
  1413. uint64_t last_total_mul_mat_bytes {};
  1414. // Cache most recent tensor that was converted into prealloc_y, and what pipeline it used to convert.
  1415. vk_pipeline_struct * prealloc_y_last_pipeline_used {};
  1416. const ggml_tensor * prealloc_y_last_tensor_used {};
  1417. // Track which nodes have been used since the last sync, and whether they were written to
  1418. std::vector<const ggml_tensor *> unsynced_nodes_written;
  1419. std::vector<const ggml_tensor *> unsynced_nodes_read;
  1420. // Track which prealloc buffers have pending reads that need to be synchronized.
  1421. // These are checked before writing to the buffer (and call ggml_vk_sync_buffers if set),
  1422. // and set to true after the buffer contents are consumed.
  1423. bool prealloc_x_need_sync, prealloc_y_need_sync, prealloc_split_k_need_sync;
  1424. vk_context_ref compute_ctx;
  1425. vk_context_ref transfer_ctx;
  1426. std::vector<vk_context_ref> tensor_ctxs;
  1427. std::vector<vk::DescriptorPool> descriptor_pools;
  1428. std::vector<vk::DescriptorSet> descriptor_sets;
  1429. uint32_t descriptor_set_idx {};
  1430. uint32_t pipeline_descriptor_set_requirements {};
  1431. vk_command_pool compute_cmd_pool;
  1432. vk_command_pool transfer_cmd_pool;
  1433. // number of additional consecutive nodes that are being fused with the
  1434. // node currently being processed
  1435. int num_additional_fused_ops {};
  1436. // Bitmask of which fused ops need to write an intermediate value to memory.
  1437. // Bit 'i' means nodes[start_of_fusion + i] writes to memory.
  1438. // If there's no fusion, bit 0 is still set.
  1439. int fused_ops_write_mask {};
  1440. };
  1441. static void * const vk_ptr_base = (void *)(uintptr_t) 0x1000; // NOLINT
  1442. static uint64_t vk_tensor_offset(const ggml_tensor * tensor) {
  1443. if (tensor->view_src) {
  1444. return (uint8_t *) tensor->view_src->data - (uint8_t *) vk_ptr_base;
  1445. }
  1446. return (uint8_t *) tensor->data - (uint8_t *) vk_ptr_base;
  1447. }
  1448. static uint32_t get_misalign_bytes(const ggml_backend_vk_context * ctx, const ggml_tensor * t)
  1449. {
  1450. return ((vk_tensor_offset(t) + t->view_offs) & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1));;
  1451. }
  1452. template <typename T> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, T &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  1453. GGML_UNUSED(p);
  1454. GGML_UNUSED(src0);
  1455. GGML_UNUSED(src1);
  1456. GGML_UNUSED(src2);
  1457. GGML_UNUSED(src3);
  1458. GGML_UNUSED(dst);
  1459. static_assert(!std::is_const<T>::value, "unexpected type");
  1460. GGML_ASSERT(!src0 || get_misalign_bytes(ctx, src0) == 0);
  1461. GGML_ASSERT(!src1 || get_misalign_bytes(ctx, src1) == 0);
  1462. GGML_ASSERT(!src2 || get_misalign_bytes(ctx, src2) == 0);
  1463. GGML_ASSERT(!src3 || get_misalign_bytes(ctx, src3) == 0);
  1464. GGML_ASSERT(!dst || get_misalign_bytes(ctx, dst) == 0);
  1465. }
  1466. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_mat_vec_p021_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  1467. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1468. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1469. p.b_offset = b_offset;
  1470. p.d_offset = d_offset;
  1471. GGML_UNUSED(src0);
  1472. GGML_UNUSED(src2);
  1473. GGML_UNUSED(src3);
  1474. }
  1475. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_mat_vec_nc_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  1476. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  1477. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  1478. p.b_offset = b_offset;
  1479. p.d_offset = d_offset;
  1480. GGML_UNUSED(src0);
  1481. GGML_UNUSED(src2);
  1482. GGML_UNUSED(src3);
  1483. }
  1484. struct ggml_backend_vk_buffer_context {
  1485. vk_device_ref device;
  1486. vk_buffer dev_buffer;
  1487. std::string name;
  1488. ggml_backend_vk_buffer_context(vk_device_ref device, vk_buffer&& dev_buffer, std::string& name) :
  1489. device(device),
  1490. dev_buffer(dev_buffer),
  1491. name(name) {
  1492. }
  1493. ~ggml_backend_vk_buffer_context() {
  1494. ggml_vk_destroy_buffer(dev_buffer);
  1495. }
  1496. };
  1497. #ifdef GGML_VULKAN_MEMORY_DEBUG
  1498. static std::mutex log_mutex;
  1499. void vk_memory_logger::log_allocation(vk_buffer_ref buf_ref, size_t size) {
  1500. std::lock_guard<std::mutex> guard(log_mutex);
  1501. vk_buffer buf = buf_ref.lock();
  1502. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1503. const std::string type = device ? "device" : "host";
  1504. allocations[buf->buffer] = size;
  1505. total_device += device ? size : 0;
  1506. total_host += device ? 0 : size;
  1507. 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));
  1508. }
  1509. void vk_memory_logger::log_deallocation(vk_buffer_ref buf_ref) {
  1510. if (buf_ref.expired() || buf_ref.lock()->size == 0) {
  1511. return;
  1512. }
  1513. std::lock_guard<std::mutex> guard(log_mutex);
  1514. vk_buffer buf = buf_ref.lock();
  1515. const bool device = bool(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eDeviceLocal);
  1516. std::string type = device ? "device" : "host";
  1517. auto it = allocations.find(buf->buffer);
  1518. total_device -= device ? it->second : 0;
  1519. total_host -= device ? 0 : it->second;
  1520. if (it != allocations.end()) {
  1521. 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));
  1522. allocations.erase(it);
  1523. } else {
  1524. VK_LOG_MEMORY("ERROR " << buf->device->name << ": Attempted to deallocate unknown " << type << " memory at " << buf->buffer);
  1525. }
  1526. }
  1527. #endif // GGML_VULKAN_MEMORY_DEBUG
  1528. struct vk_instance_t {
  1529. vk::Instance instance;
  1530. bool debug_utils_support = false; // VK_EXT_debug_utils enabled
  1531. PFN_vkSetDebugUtilsObjectNameEXT pfn_vkSetDebugUtilsObjectNameEXT = {};
  1532. PFN_vkQueueBeginDebugUtilsLabelEXT pfn_vkQueueBeginDebugUtilsLabelEXT = {};
  1533. PFN_vkQueueEndDebugUtilsLabelEXT pfn_vkQueueEndDebugUtilsLabelEXT = {};
  1534. PFN_vkCmdBeginDebugUtilsLabelEXT pfn_vkCmdBeginDebugUtilsLabelEXT = {};
  1535. PFN_vkCmdEndDebugUtilsLabelEXT pfn_vkCmdEndDebugUtilsLabelEXT = {};
  1536. PFN_vkCmdInsertDebugUtilsLabelEXT pfn_vkCmdInsertDebugUtilsLabelEXT = {};
  1537. std::vector<size_t> device_indices;
  1538. std::vector<bool> device_supports_membudget;
  1539. vk_device devices[GGML_VK_MAX_DEVICES];
  1540. };
  1541. static bool vk_instance_initialized = false;
  1542. static vk_instance_t vk_instance;
  1543. static bool vk_perf_logger_enabled = false;
  1544. #ifdef GGML_VULKAN_CHECK_RESULTS
  1545. static size_t vk_skip_checks;
  1546. static size_t vk_output_tensor;
  1547. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name);
  1548. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1549. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx);
  1550. #endif
  1551. 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);
  1552. static void ggml_backend_vk_free(ggml_backend_t backend);
  1553. static VkDeviceSize ggml_vk_get_max_buffer_range(const ggml_backend_vk_context * ctx, const vk_buffer &buf, const VkDeviceSize offset) {
  1554. const VkDeviceSize range = std::min(VkDeviceSize{buf->size - offset},
  1555. VkDeviceSize{ctx->device->properties.limits.maxStorageBufferRange});
  1556. return range;
  1557. }
  1558. // Wait for ctx->fence to be signaled.
  1559. static void ggml_vk_wait_for_fence(ggml_backend_vk_context * ctx) {
  1560. // Use waitForFences while most of the graph executes. Hopefully the CPU can sleep
  1561. // during this wait.
  1562. if (ctx->almost_ready_fence_pending) {
  1563. VK_CHECK(ctx->device->device.waitForFences({ ctx->almost_ready_fence }, true, UINT64_MAX), "almost_ready_fence");
  1564. ctx->device->device.resetFences({ ctx->almost_ready_fence });
  1565. ctx->almost_ready_fence_pending = false;
  1566. }
  1567. // Spin (w/pause) waiting for the graph to finish executing.
  1568. vk::Result result;
  1569. while ((result = ctx->device->device.getFenceStatus(ctx->fence)) != vk::Result::eSuccess) {
  1570. if (result != vk::Result::eNotReady) {
  1571. fprintf(stderr, "ggml_vulkan: error %s at %s:%d\n", to_string(result).c_str(), __FILE__, __LINE__);
  1572. exit(1);
  1573. }
  1574. for (uint32_t i = 0; i < 100; ++i) {
  1575. YIELD();
  1576. YIELD();
  1577. YIELD();
  1578. YIELD();
  1579. YIELD();
  1580. YIELD();
  1581. YIELD();
  1582. YIELD();
  1583. YIELD();
  1584. YIELD();
  1585. }
  1586. }
  1587. ctx->device->device.resetFences({ ctx->fence });
  1588. }
  1589. // variables to track number of compiles in progress
  1590. static uint32_t compile_count = 0;
  1591. static std::mutex compile_count_mutex;
  1592. static std::condition_variable compile_count_cond;
  1593. 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,
  1594. uint32_t parameter_count, std::array<uint32_t, 3> wg_denoms, std::vector<uint32_t> specialization_constants,
  1595. bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) {
  1596. VK_LOG_DEBUG("ggml_vk_create_pipeline(" << device->name << ", " << pipeline->name << ", " << entrypoint << ", " << parameter_count <<
  1597. ", (" << wg_denoms[0] << "," << wg_denoms[1] << "," << wg_denoms[2] << "), specialization_constants, " <<
  1598. disable_robustness << ", " << require_full_subgroups << ", " << required_subgroup_size << ")");
  1599. GGML_ASSERT(parameter_count > 0);
  1600. GGML_ASSERT(parameter_count <= MAX_PARAMETER_COUNT);
  1601. GGML_ASSERT(wg_denoms[0] > 0 && wg_denoms[1] > 0 && wg_denoms[2] > 0); // NOLINT
  1602. vk::ShaderModuleCreateInfo shader_module_create_info({}, spv_size, reinterpret_cast<const uint32_t *>(spv_data));
  1603. pipeline->shader_module = device->device.createShaderModule(shader_module_create_info);
  1604. vk::PushConstantRange pcr(
  1605. vk::ShaderStageFlagBits::eCompute,
  1606. 0,
  1607. pipeline->push_constant_size
  1608. );
  1609. vk::PipelineLayoutCreateInfo pipeline_layout_create_info(vk::PipelineLayoutCreateFlags(), device->dsl, pcr);
  1610. pipeline->layout = device->device.createPipelineLayout(pipeline_layout_create_info);
  1611. std::vector<vk::SpecializationMapEntry> specialization_entries(specialization_constants.size());
  1612. for (size_t i = 0; i < specialization_constants.size(); i++) {
  1613. specialization_entries[i].constantID = i;
  1614. specialization_entries[i].offset = i * sizeof(uint32_t);
  1615. specialization_entries[i].size = sizeof(uint32_t);
  1616. }
  1617. vk::SpecializationInfo specialization_info(
  1618. specialization_entries.size(),
  1619. specialization_entries.data(),
  1620. specialization_constants.size() * sizeof(uint32_t),
  1621. specialization_constants.data()
  1622. );
  1623. vk::PipelineShaderStageCreateFlags pipeline_shader_stage_create_flags{};
  1624. if (device->subgroup_require_full_support && require_full_subgroups) {
  1625. pipeline_shader_stage_create_flags |= vk::PipelineShaderStageCreateFlagBits::eRequireFullSubgroupsEXT;
  1626. }
  1627. vk::PipelineShaderStageCreateInfo pipeline_shader_create_info(
  1628. pipeline_shader_stage_create_flags,
  1629. vk::ShaderStageFlagBits::eCompute,
  1630. pipeline->shader_module,
  1631. entrypoint.c_str(),
  1632. &specialization_info);
  1633. vk::PipelineShaderStageRequiredSubgroupSizeCreateInfoEXT pipeline_shader_stage_required_subgroup_size_create_info;
  1634. pipeline_shader_stage_required_subgroup_size_create_info.requiredSubgroupSize = required_subgroup_size;
  1635. if (device->subgroup_size_control && required_subgroup_size > 0) {
  1636. GGML_ASSERT(device->subgroup_min_size <= required_subgroup_size && required_subgroup_size <= device->subgroup_max_size);
  1637. pipeline_shader_create_info.setPNext(&pipeline_shader_stage_required_subgroup_size_create_info);
  1638. }
  1639. vk::ComputePipelineCreateInfo compute_pipeline_create_info(
  1640. device->pipeline_executable_properties_support ?
  1641. vk::PipelineCreateFlagBits::eCaptureStatisticsKHR :
  1642. vk::PipelineCreateFlags{},
  1643. pipeline_shader_create_info,
  1644. pipeline->layout);
  1645. vk::PipelineRobustnessCreateInfoEXT rci;
  1646. if (device->pipeline_robustness && disable_robustness) {
  1647. rci.storageBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1648. rci.uniformBuffers = vk::PipelineRobustnessBufferBehaviorEXT::eDisabled;
  1649. compute_pipeline_create_info.setPNext(&rci);
  1650. }
  1651. try {
  1652. pipeline->pipeline = device->device.createComputePipeline(VK_NULL_HANDLE, compute_pipeline_create_info).value;
  1653. } catch (const vk::SystemError& e) {
  1654. std::cerr << "ggml_vulkan: Compute pipeline creation failed for " << pipeline->name << std::endl;
  1655. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  1656. throw e;
  1657. }
  1658. pipeline->compiled = true;
  1659. if (vk_instance.debug_utils_support) {
  1660. vk::DebugUtilsObjectNameInfoEXT duoni;
  1661. duoni.objectType = vk::ObjectType::ePipeline;
  1662. duoni.pObjectName = pipeline->name.c_str();
  1663. duoni.objectHandle = /*reinterpret_cast*/(uint64_t)(static_cast<VkPipeline>(pipeline->pipeline));
  1664. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT(device->device, &static_cast<VkDebugUtilsObjectNameInfoEXT &>(duoni));
  1665. }
  1666. if (device->pipeline_executable_properties_support) {
  1667. vk::PipelineExecutableInfoKHR executableInfo;
  1668. executableInfo.pipeline = pipeline->pipeline;
  1669. auto statistics = device->device.getPipelineExecutableStatisticsKHR(executableInfo);
  1670. for (auto & s : statistics) {
  1671. // "Register Count" is reported by NVIDIA drivers.
  1672. if (strcmp(s.name, "Register Count") == 0) {
  1673. VK_LOG_DEBUG(pipeline->name << " " << s.name << ": " << s.value.u64 << " registers");
  1674. pipeline->register_count = (uint32_t)s.value.u64;
  1675. }
  1676. }
  1677. }
  1678. device->all_pipelines.push_back(pipeline);
  1679. {
  1680. std::lock_guard<std::mutex> guard(compile_count_mutex);
  1681. assert(compile_count > 0);
  1682. compile_count--;
  1683. }
  1684. compile_count_cond.notify_all();
  1685. }
  1686. static void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline) {
  1687. VK_LOG_DEBUG("ggml_pipeline_destroy_pipeline(" << pipeline->name << ")");
  1688. device.destroyPipelineLayout(pipeline->layout);
  1689. device.destroyShaderModule(pipeline->shader_module);
  1690. device.destroyPipeline(pipeline->pipeline);
  1691. }
  1692. static void ggml_pipeline_request_descriptor_sets(ggml_backend_vk_context *ctx, vk_pipeline& pipeline, uint32_t n) {
  1693. VK_LOG_DEBUG("ggml_pipeline_request_descriptor_sets(" << pipeline->name << ", " << n << ")");
  1694. ctx->pipeline_descriptor_set_requirements += n;
  1695. if (!pipeline->compiled) {
  1696. pipeline->needed = true;
  1697. ggml_vk_load_shaders(ctx->device);
  1698. }
  1699. ggml_pipeline_allocate_descriptor_sets(ctx);
  1700. }
  1701. static void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) {
  1702. if (ctx->descriptor_sets.size() >= ctx->pipeline_descriptor_set_requirements) {
  1703. // Enough descriptors are available
  1704. return;
  1705. }
  1706. vk_device& device = ctx->device;
  1707. // Grow by 50% to avoid frequent allocations
  1708. uint32_t needed = std::max(3 * ctx->descriptor_sets.size() / 2, size_t{ctx->pipeline_descriptor_set_requirements});
  1709. uint32_t to_alloc = needed - ctx->descriptor_sets.size();
  1710. uint32_t pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE - ctx->descriptor_sets.size() % VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1711. uint32_t pool_idx = ctx->descriptor_sets.size() / VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1712. while (to_alloc > 0) {
  1713. const uint32_t alloc_count = std::min(pool_remaining, to_alloc);
  1714. to_alloc -= alloc_count;
  1715. pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE;
  1716. if (pool_idx >= ctx->descriptor_pools.size()) {
  1717. vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE);
  1718. vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size);
  1719. ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info));
  1720. }
  1721. std::vector<vk::DescriptorSetLayout> layouts(alloc_count);
  1722. for (uint32_t i = 0; i < alloc_count; i++) {
  1723. layouts[i] = device->dsl;
  1724. }
  1725. vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data());
  1726. std::vector<vk::DescriptorSet> sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info);
  1727. ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end());
  1728. pool_idx++;
  1729. }
  1730. }
  1731. static vk::CommandBuffer ggml_vk_create_cmd_buffer(vk_device& device, vk_command_pool& p) {
  1732. VK_LOG_DEBUG("ggml_vk_create_cmd_buffer()");
  1733. if (p.cmd_buffers.size() > p.cmd_buffer_idx) {
  1734. // Reuse command buffer
  1735. return p.cmd_buffers[p.cmd_buffer_idx++];
  1736. }
  1737. vk::CommandBufferAllocateInfo command_buffer_alloc_info(
  1738. p.pool,
  1739. vk::CommandBufferLevel::ePrimary,
  1740. 1);
  1741. const std::vector<vk::CommandBuffer> cmd_buffers = device->device.allocateCommandBuffers(command_buffer_alloc_info);
  1742. auto buf = cmd_buffers.front();
  1743. p.cmd_buffers.push_back(buf);
  1744. p.cmd_buffer_idx++;
  1745. return buf;
  1746. }
  1747. static void ggml_vk_submit(vk_context& ctx, vk::Fence fence) {
  1748. if (ctx->seqs.empty()) {
  1749. if (fence) {
  1750. std::lock_guard<std::mutex> guard(queue_mutex);
  1751. ctx->p->q->queue.submit({}, fence);
  1752. }
  1753. return;
  1754. }
  1755. VK_LOG_DEBUG("ggml_vk_submit(" << ctx << ", " << fence << ")");
  1756. std::vector<std::vector<uint64_t>> tl_wait_vals;
  1757. std::vector<std::vector<uint64_t>> tl_signal_vals;
  1758. std::vector<std::vector<vk::Semaphore>> tl_wait_semaphores;
  1759. std::vector<std::vector<vk::Semaphore>> tl_signal_semaphores;
  1760. std::vector<vk::TimelineSemaphoreSubmitInfo> tl_submit_infos;
  1761. std::vector<vk::SubmitInfo> submit_infos;
  1762. int idx = -1;
  1763. std::vector<std::vector<vk::PipelineStageFlags>> stage_flags;
  1764. size_t reserve = 0;
  1765. for (const auto& sequence : ctx->seqs) {
  1766. reserve += sequence.size();
  1767. }
  1768. // Pre-reserve vectors to prevent reallocation, which invalidates pointers
  1769. tl_wait_semaphores.reserve(reserve);
  1770. tl_wait_vals.reserve(reserve);
  1771. tl_signal_semaphores.reserve(reserve);
  1772. tl_signal_vals.reserve(reserve);
  1773. tl_submit_infos.reserve(reserve);
  1774. submit_infos.reserve(reserve);
  1775. stage_flags.reserve(reserve);
  1776. for (const auto& sequence : ctx->seqs) {
  1777. for (const auto& submission : sequence) {
  1778. stage_flags.push_back({});
  1779. idx++;
  1780. tl_wait_vals.push_back({});
  1781. tl_wait_semaphores.push_back({});
  1782. tl_signal_vals.push_back({});
  1783. tl_signal_semaphores.push_back({});
  1784. for (size_t i = 0; i < submission.wait_semaphores.size(); i++) {
  1785. stage_flags[idx].push_back(ctx->p->q->stage_flags);
  1786. tl_wait_vals[idx].push_back(submission.wait_semaphores[i].value);
  1787. tl_wait_semaphores[idx].push_back(submission.wait_semaphores[i].s);
  1788. }
  1789. for (size_t i = 0; i < submission.signal_semaphores.size(); i++) {
  1790. tl_signal_vals[idx].push_back(submission.signal_semaphores[i].value);
  1791. tl_signal_semaphores[idx].push_back(submission.signal_semaphores[i].s);
  1792. }
  1793. tl_submit_infos.push_back({
  1794. (uint32_t) submission.wait_semaphores.size(),
  1795. tl_wait_vals[idx].data(),
  1796. (uint32_t) submission.signal_semaphores.size(),
  1797. tl_signal_vals[idx].data(),
  1798. });
  1799. tl_submit_infos[idx].sType = vk::StructureType::eTimelineSemaphoreSubmitInfo;
  1800. tl_submit_infos[idx].pNext = nullptr;
  1801. vk::SubmitInfo si{
  1802. (uint32_t) submission.wait_semaphores.size(),
  1803. tl_wait_semaphores[idx].data(),
  1804. stage_flags[idx].data(),
  1805. 1,
  1806. &submission.buffer,
  1807. (uint32_t) submission.signal_semaphores.size(),
  1808. tl_signal_semaphores[idx].data(),
  1809. };
  1810. si.setPNext(&tl_submit_infos[idx]);
  1811. submit_infos.push_back(si);
  1812. }
  1813. }
  1814. std::lock_guard<std::mutex> guard(queue_mutex);
  1815. ctx->p->q->queue.submit(submit_infos, fence);
  1816. ctx->seqs.clear();
  1817. }
  1818. 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) {
  1819. VK_LOG_DEBUG("ggml_vk_find_queue_family_index()");
  1820. const uint32_t qfsize = queue_family_props.size();
  1821. // Try with avoid preferences first
  1822. for (uint32_t i = 0; i < qfsize; i++) {
  1823. 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)) {
  1824. return i;
  1825. }
  1826. }
  1827. // Fall back to only required
  1828. for (size_t i = 0; i < qfsize; i++) {
  1829. if (queue_family_props[i].queueCount >= min_num_queues && (compute_index < 0 || i != (uint32_t) compute_index) && queue_family_props[i].queueFlags & required) {
  1830. return i;
  1831. }
  1832. }
  1833. // Fall back to reusing compute queue
  1834. for (size_t i = 0; i < qfsize; i++) {
  1835. if (queue_family_props[i].queueCount >= min_num_queues && queue_family_props[i].queueFlags & required) {
  1836. return i;
  1837. }
  1838. }
  1839. // Fall back to ignoring min_num_queries
  1840. for (size_t i = 0; i < qfsize; i++) {
  1841. if (queue_family_props[i].queueFlags & required) {
  1842. return i;
  1843. }
  1844. }
  1845. // 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.
  1846. // 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.
  1847. if (compute_index >= 0) {
  1848. return compute_index;
  1849. }
  1850. std::cerr << "ggml_vulkan: No suitable queue family index found." << std::endl;
  1851. for(auto &q_family : queue_family_props) {
  1852. std::cerr << "Queue number: " + std::to_string(q_family.queueCount) << " flags: " + to_string(q_family.queueFlags) << std::endl;
  1853. }
  1854. abort();
  1855. }
  1856. 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) {
  1857. VK_LOG_DEBUG("ggml_vk_create_queue()");
  1858. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  1859. q.queue_family_index = queue_family_index;
  1860. q.transfer_only = transfer_only;
  1861. q.cmd_pool.init(device, &q);
  1862. q.queue = device->device.getQueue(queue_family_index, queue_index);
  1863. q.stage_flags = stage_flags;
  1864. }
  1865. static vk_context ggml_vk_create_context(ggml_backend_vk_context * ctx, vk_command_pool& p) {
  1866. vk_context result = std::make_shared<vk_context_struct>();
  1867. VK_LOG_DEBUG("ggml_vk_create_context(" << result << ")");
  1868. ctx->gc.contexts.emplace_back(result);
  1869. result->p = &p;
  1870. return result;
  1871. }
  1872. static vk_context ggml_vk_create_temporary_context(vk_command_pool& p) {
  1873. vk_context result = std::make_shared<vk_context_struct>();
  1874. VK_LOG_DEBUG("ggml_vk_create_temporary_context(" << result << ")");
  1875. result->p = &p;
  1876. return result;
  1877. }
  1878. static vk_semaphore * ggml_vk_create_binary_semaphore(ggml_backend_vk_context * ctx) {
  1879. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1880. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eBinary, 0 };
  1881. vk::SemaphoreCreateInfo ci{};
  1882. ci.setPNext(&tci);
  1883. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1884. ctx->gc.semaphores.push_back({ semaphore, 0 });
  1885. return &ctx->gc.semaphores[ctx->gc.semaphores.size() - 1];
  1886. }
  1887. static vk_semaphore * ggml_vk_create_timeline_semaphore(ggml_backend_vk_context * ctx) {
  1888. VK_LOG_DEBUG("ggml_vk_create_timeline_semaphore()");
  1889. if (ctx->semaphore_idx >= ctx->gc.tl_semaphores.size()) {
  1890. vk::SemaphoreTypeCreateInfo tci{ vk::SemaphoreType::eTimeline, 0 };
  1891. vk::SemaphoreCreateInfo ci{};
  1892. ci.setPNext(&tci);
  1893. vk::Semaphore semaphore = ctx->device->device.createSemaphore(ci);
  1894. ctx->gc.tl_semaphores.push_back({ semaphore, 0 });
  1895. }
  1896. return &ctx->gc.tl_semaphores[ctx->semaphore_idx++];
  1897. }
  1898. static vk::Event ggml_vk_create_event(ggml_backend_vk_context * ctx) {
  1899. if (ctx->event_idx >= ctx->gc.events.size()) {
  1900. ctx->gc.events.push_back(ctx->device->device.createEvent({}));
  1901. }
  1902. return ctx->gc.events[ctx->event_idx++];
  1903. }
  1904. static void ggml_vk_command_pool_cleanup(vk_device& device, vk_command_pool& p) {
  1905. VK_LOG_DEBUG("ggml_vk_command_pool_cleanup()");
  1906. // Requires command buffers to be done
  1907. device->device.resetCommandPool(p.pool);
  1908. p.cmd_buffer_idx = 0;
  1909. }
  1910. static void ggml_vk_queue_command_pools_cleanup(vk_device& device) {
  1911. VK_LOG_DEBUG("ggml_vk_queue_command_pools_cleanup()");
  1912. // Arbitrary frequency to cleanup/reuse command buffers
  1913. static constexpr uint32_t cleanup_frequency = 10;
  1914. if (device->compute_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1915. ggml_vk_command_pool_cleanup(device, device->compute_queue.cmd_pool);
  1916. }
  1917. if (device->transfer_queue.cmd_pool.cmd_buffer_idx >= cleanup_frequency) {
  1918. ggml_vk_command_pool_cleanup(device, device->transfer_queue.cmd_pool);
  1919. }
  1920. }
  1921. static std::vector<uint32_t> ggml_vk_find_memory_properties(const vk::PhysicalDeviceMemoryProperties* mem_props, vk::MemoryRequirements* mem_req, vk::MemoryPropertyFlags flags) {
  1922. std::vector<uint32_t> indices;
  1923. for (uint32_t i = 0; i < mem_props->memoryTypeCount; ++i) {
  1924. vk::MemoryType memory_type = mem_props->memoryTypes[i];
  1925. if ((mem_req->memoryTypeBits & ((uint64_t)1 << i)) &&
  1926. (flags & memory_type.propertyFlags) == flags &&
  1927. mem_props->memoryHeaps[memory_type.heapIndex].size >= mem_req->size) {
  1928. indices.push_back(i);
  1929. }
  1930. }
  1931. return indices;
  1932. }
  1933. static vk_buffer ggml_vk_create_buffer(vk_device& device, size_t size, const std::initializer_list<vk::MemoryPropertyFlags> & req_flags_list) {
  1934. VK_LOG_DEBUG("ggml_vk_create_buffer(" << device->name << ", " << size << ", " << to_string(req_flags_list.begin()[0]) << ", " << to_string(req_flags_list.begin()[req_flags_list.size()-1]) << ")");
  1935. if (size > device->max_buffer_size) {
  1936. throw vk::OutOfDeviceMemoryError("Requested buffer size exceeds device buffer size limit");
  1937. }
  1938. vk_buffer buf = std::make_shared<vk_buffer_struct>();
  1939. if (size == 0) {
  1940. buf->size = 0;
  1941. return buf;
  1942. }
  1943. vk::BufferUsageFlags usage_flags = vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst;
  1944. vk::MemoryAllocateFlags mem_flags {};
  1945. if (device->buffer_device_address) {
  1946. usage_flags |= vk::BufferUsageFlagBits::eShaderDeviceAddress;
  1947. mem_flags |= vk::MemoryAllocateFlagBits::eDeviceAddress;
  1948. }
  1949. vk::BufferCreateInfo buffer_create_info{
  1950. vk::BufferCreateFlags(),
  1951. size,
  1952. usage_flags,
  1953. vk::SharingMode::eExclusive,
  1954. 0,
  1955. nullptr,
  1956. };
  1957. buf->buffer = device->device.createBuffer(buffer_create_info);
  1958. vk::MemoryRequirements mem_req = device->device.getBufferMemoryRequirements(buf->buffer);
  1959. vk::PhysicalDeviceMemoryProperties mem_props = device->physical_device.getMemoryProperties();
  1960. const vk::MemoryAllocateFlagsInfo mem_flags_info { mem_flags };
  1961. for (auto it = req_flags_list.begin(); it != req_flags_list.end(); it++) {
  1962. const auto & req_flags = *it;
  1963. const std::vector<uint32_t> memory_type_indices = ggml_vk_find_memory_properties(&mem_props, &mem_req, req_flags);
  1964. if (memory_type_indices.empty()) {
  1965. continue;
  1966. }
  1967. buf->memory_property_flags = req_flags;
  1968. bool done = false;
  1969. for (auto mtype_it = memory_type_indices.begin(); mtype_it != memory_type_indices.end(); mtype_it++) {
  1970. try {
  1971. buf->device_memory = device->device.allocateMemory({ mem_req.size, *mtype_it, &mem_flags_info });
  1972. done = true;
  1973. break;
  1974. } catch (const vk::SystemError& e) {
  1975. // loop and retry
  1976. // during last attempt throw the exception
  1977. if (it + 1 == req_flags_list.end() && mtype_it + 1 == memory_type_indices.end()) {
  1978. device->device.destroyBuffer(buf->buffer);
  1979. throw e;
  1980. }
  1981. }
  1982. }
  1983. if (done) {
  1984. break;
  1985. }
  1986. }
  1987. if (!buf->device_memory) {
  1988. device->device.destroyBuffer(buf->buffer);
  1989. throw vk::OutOfDeviceMemoryError("No suitable memory type found");
  1990. }
  1991. buf->ptr = nullptr;
  1992. if (buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  1993. buf->ptr = device->device.mapMemory(buf->device_memory, 0, VK_WHOLE_SIZE);
  1994. }
  1995. device->device.bindBufferMemory(buf->buffer, buf->device_memory, 0);
  1996. buf->device = device;
  1997. buf->size = size;
  1998. if (device->buffer_device_address) {
  1999. const vk::BufferDeviceAddressInfo addressInfo(buf->buffer);
  2000. buf->bda_addr = device->device.getBufferAddress(addressInfo);
  2001. }
  2002. #ifdef GGML_VULKAN_MEMORY_DEBUG
  2003. device->memory_logger->log_allocation(buf, size);
  2004. #endif
  2005. return buf;
  2006. }
  2007. 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)) {
  2008. try {
  2009. return ggml_vk_create_buffer(device, size, {req_flags, fallback_flags});
  2010. } catch (const vk::SystemError& e) {
  2011. std::cerr << "ggml_vulkan: Memory allocation of size " << size << " failed." << std::endl;
  2012. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  2013. throw e;
  2014. }
  2015. }
  2016. static vk_buffer ggml_vk_create_buffer_device(vk_device& device, size_t size) {
  2017. vk_buffer buf;
  2018. try {
  2019. if (device->prefer_host_memory) {
  2020. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2021. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2022. } else if (device->uma) {
  2023. // Fall back to host memory type
  2024. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2025. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2026. } else if (device->disable_host_visible_vidmem) {
  2027. if (device->allow_sysmem_fallback) {
  2028. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal,
  2029. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2030. } else {
  2031. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  2032. }
  2033. } else {
  2034. // use rebar if available, otherwise fallback to device only visible memory
  2035. if (device->allow_sysmem_fallback) {
  2036. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2037. vk::MemoryPropertyFlagBits::eDeviceLocal,
  2038. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  2039. } else {
  2040. buf = ggml_vk_create_buffer(device, size, {vk::MemoryPropertyFlagBits::eDeviceLocal | vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
  2041. vk::MemoryPropertyFlagBits::eDeviceLocal});
  2042. }
  2043. }
  2044. } catch (const vk::SystemError& e) {
  2045. std::cerr << "ggml_vulkan: Device memory allocation of size " << size << " failed." << std::endl;
  2046. std::cerr << "ggml_vulkan: " << e.what() << std::endl;
  2047. throw e;
  2048. }
  2049. return buf;
  2050. }
  2051. static void ggml_vk_destroy_buffer(vk_buffer& buf) {
  2052. if (buf == nullptr) {
  2053. return;
  2054. }
  2055. #ifdef GGML_VULKAN_MEMORY_DEBUG
  2056. if (buf->device != nullptr) {
  2057. buf->device->memory_logger->log_deallocation(buf);
  2058. }
  2059. #endif
  2060. buf.reset();
  2061. }
  2062. static vk_subbuffer ggml_vk_subbuffer(const ggml_backend_vk_context* ctx, const vk_buffer& buf, size_t offset = 0) {
  2063. return { buf, offset, ggml_vk_get_max_buffer_range(ctx, buf, offset) };
  2064. }
  2065. static void ggml_vk_sync_buffers(ggml_backend_vk_context* ctx, vk_context& subctx) {
  2066. VK_LOG_DEBUG("ggml_vk_sync_buffers()");
  2067. const bool transfer_queue = subctx->p->q->transfer_only;
  2068. if (ctx) {
  2069. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  2070. }
  2071. subctx->s->buffer.pipelineBarrier(
  2072. subctx->p->q->stage_flags,
  2073. subctx->p->q->stage_flags,
  2074. {},
  2075. { {
  2076. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) },
  2077. { !transfer_queue ? (vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eShaderWrite | vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) : (vk::AccessFlagBits::eTransferRead | vk::AccessFlagBits::eTransferWrite) }
  2078. } },
  2079. {},
  2080. {}
  2081. );
  2082. }
  2083. static void ggml_vk_wait_events(vk_context& ctx, std::vector<vk::Event>&& events) {
  2084. VK_LOG_DEBUG("ggml_vk_wait_events()");
  2085. if (events.empty()) {
  2086. return;
  2087. }
  2088. ctx->s->buffer.waitEvents(
  2089. events,
  2090. ctx->p->q->stage_flags,
  2091. ctx->p->q->stage_flags,
  2092. {},
  2093. {},
  2094. {}
  2095. );
  2096. }
  2097. // number of rows/cols for flash attention shader
  2098. static constexpr uint32_t flash_attention_num_small_rows = 32;
  2099. static constexpr uint32_t scalar_flash_attention_num_small_rows = 1;
  2100. static uint32_t get_fa_scalar_num_large_rows(uint32_t hsv) {
  2101. if (hsv >= 192) {
  2102. return 2;
  2103. } else {
  2104. return 8;
  2105. }
  2106. }
  2107. // The FA coopmat1 shader assumes 16x16x16 matrix multiply support.
  2108. // 128 threads split into four subgroups, each subgroup does 1/4
  2109. // of the Bc dimension.
  2110. static constexpr uint32_t coopmat1_flash_attention_num_large_rows = 16;
  2111. static constexpr uint32_t scalar_flash_attention_Bc = 64;
  2112. static constexpr uint32_t scalar_flash_attention_workgroup_size = 128;
  2113. static uint32_t get_fa_num_small_rows(FaCodePath path) {
  2114. if (path == FA_COOPMAT2) {
  2115. return flash_attention_num_small_rows;
  2116. } else {
  2117. return scalar_flash_attention_num_small_rows;
  2118. }
  2119. }
  2120. 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) {
  2121. GGML_UNUSED(clamp);
  2122. GGML_UNUSED(hsv);
  2123. if (path == FA_SCALAR) {
  2124. if (small_rows) {
  2125. return {scalar_flash_attention_num_small_rows, 64};
  2126. } else {
  2127. if ((hsv | hsk) & 8) {
  2128. // HSV/HSK not being a multiple of 16 makes D_split smaller, which makes cols_per_iter
  2129. // larger, and Bc needs to be >= cols_per_thread. 64 is large enough, 32 is not.
  2130. return {get_fa_scalar_num_large_rows(hsv), 64};
  2131. } else {
  2132. return {get_fa_scalar_num_large_rows(hsv), 32};
  2133. }
  2134. }
  2135. }
  2136. if (path == FA_COOPMAT1) {
  2137. if (small_rows) {
  2138. return {scalar_flash_attention_num_small_rows, scalar_flash_attention_Bc};
  2139. } else {
  2140. return {coopmat1_flash_attention_num_large_rows, scalar_flash_attention_Bc};
  2141. }
  2142. }
  2143. // small rows, large cols
  2144. if (small_rows) {
  2145. return {get_fa_num_small_rows(FA_COOPMAT2), 32};
  2146. }
  2147. // small cols to reduce register count
  2148. if (ggml_is_quantized(type) || hsk >= 256 || hsv >= 256) {
  2149. if (hsk >= 512 || hsv >= 512) {
  2150. return {32, 32};
  2151. } else {
  2152. return {64, 32};
  2153. }
  2154. }
  2155. return {64, 64};
  2156. }
  2157. static uint32_t fa_align(FaCodePath path, uint32_t hsk, uint32_t hsv, ggml_type type, bool small_rows) {
  2158. return fa_rows_cols(path, hsk, hsv, 0, type, small_rows)[1];
  2159. }
  2160. 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) {
  2161. uint32_t lut_size = 0;
  2162. switch (src0_type) {
  2163. case GGML_TYPE_IQ1_S:
  2164. case GGML_TYPE_IQ1_M:
  2165. lut_size = 2*2048;
  2166. break;
  2167. case GGML_TYPE_IQ2_XXS:
  2168. lut_size = 8*256;
  2169. break;
  2170. case GGML_TYPE_IQ2_XS:
  2171. lut_size = 8*512;
  2172. break;
  2173. case GGML_TYPE_IQ2_S:
  2174. lut_size = 8*1024;
  2175. break;
  2176. case GGML_TYPE_IQ3_XXS:
  2177. lut_size = 4*256;
  2178. break;
  2179. case GGML_TYPE_IQ3_S:
  2180. lut_size = 4*512;
  2181. break;
  2182. case GGML_TYPE_IQ4_NL:
  2183. case GGML_TYPE_IQ4_XS:
  2184. case GGML_TYPE_MXFP4:
  2185. lut_size = 4*16;
  2186. break;
  2187. default:
  2188. break;
  2189. }
  2190. // Needs to be kept up to date on shader changes
  2191. const uint32_t bank_conflict_offset = device->coopmat_support ? 8 : 1;
  2192. const uint32_t type_size = device->fp16 ? sizeof(ggml_fp16_t) : sizeof(float);
  2193. const uint32_t warps = warptile[0] / warptile[10];
  2194. const uint32_t load_bufs = (warptile[1] + warptile[2]) * (warptile[3] + bank_conflict_offset) * type_size;
  2195. const uint32_t mmid_row_ids = mul_mat_id ? (warptile[2] * 2 * sizeof(uint16_t)) : 0;
  2196. const uint32_t coopmat_stage = device->coopmat_support ? warptile[7] * warptile[8] / warps * sizeof(float) : 0;
  2197. const uint32_t ballots_sh = mul_mat_id ? (warps * 4 * sizeof(uint32_t)) : 0;
  2198. const uint32_t total_size = load_bufs + mmid_row_ids + coopmat_stage + lut_size + ballots_sh;
  2199. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  2200. VK_LOG_DEBUG("ggml_vk_matmul_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), "
  2201. "mul_mat_id=" << mul_mat_id << ", src0_type=" << ggml_type_name(src0_type) << ", supported=" << supported);
  2202. return supported;
  2203. }
  2204. struct GpuPipelineConfig {
  2205. // GPU architecture identifier.
  2206. // Example: vk_device_architecture::AMD_GCN
  2207. vk_device_architecture arch;
  2208. // Mapping of pipeline names to their specific subgroup sizes.
  2209. // Example: {"soft_max_f32", 64}
  2210. std::unordered_map<std::string, uint32_t> pipelines;
  2211. // Default subgroup size for this GPU.
  2212. // Defaults to 0 if not explicitly provided.
  2213. uint32_t default_subgroup_size = 0;
  2214. };
  2215. // Pipeline configuration for RDNA1 GPUs.
  2216. static const std::unordered_map<std::string, uint32_t> rdna1_pipelines = {
  2217. {"soft_max", 64}, {"im2col", 64},
  2218. {"argmax", 64}, {"mul_mat_vec", 64},
  2219. {"mul_mat_vec_f16", 32}, {"mul_mat_vec_f32_f16", 32}
  2220. };
  2221. // Pipeline configuration for RDNA2 GPUs.
  2222. static const std::unordered_map<std::string, uint32_t> rdna2_pipelines = {
  2223. {"soft_max", 64}, {"im2col", 64},
  2224. };
  2225. static constexpr uint32_t RDNA_DEFAULT_SUBGROUP_SIZE = 32;
  2226. // Define configurations for different GPUs.
  2227. static std::vector<GpuPipelineConfig> gpu_pipeline_configs = {
  2228. {
  2229. vk_device_architecture::AMD_RDNA1,
  2230. {
  2231. rdna1_pipelines,
  2232. },
  2233. RDNA_DEFAULT_SUBGROUP_SIZE
  2234. },
  2235. {
  2236. vk_device_architecture::AMD_RDNA2,
  2237. {
  2238. rdna2_pipelines,
  2239. },
  2240. RDNA_DEFAULT_SUBGROUP_SIZE
  2241. },
  2242. };
  2243. static uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch) {
  2244. for (const auto &config : gpu_pipeline_configs) {
  2245. if (config.arch == arch) {
  2246. auto pipIt = config.pipelines.find(pipeline_name);
  2247. if (pipIt != config.pipelines.end()) {
  2248. return pipIt->second;
  2249. }
  2250. std::vector<std::pair<std::string, uint32_t>> sorted_pipelines(config.pipelines.begin(), config.pipelines.end());
  2251. std::sort(sorted_pipelines.begin(), sorted_pipelines.end(),
  2252. [](const auto &a, const auto &b) { return a.first.size() > b.first.size(); });
  2253. for (const auto &entry : sorted_pipelines) {
  2254. if (pipeline_name.find(entry.first) != std::string::npos) {
  2255. return entry.second;
  2256. }
  2257. }
  2258. return config.default_subgroup_size;
  2259. }
  2260. }
  2261. return 0; // If no matching configuration is found
  2262. }
  2263. static void ggml_vk_load_shaders(vk_device& device) {
  2264. VK_LOG_DEBUG("ggml_vk_load_shaders(" << device->name << ")");
  2265. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  2266. // some shaders have a minimum subgroup size
  2267. const uint32_t subgroup_size_8 = std::max(device->subgroup_size, 8u);
  2268. const uint32_t subgroup_size_16 = std::max(device->subgroup_size, 16u);
  2269. const uint32_t subgroup_size_32 = std::max(device->subgroup_size, 32u);
  2270. const uint32_t mul_mat_subgroup_size = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  2271. const uint32_t mul_mat_subgroup_size_8 = std::max(mul_mat_subgroup_size, 8u);
  2272. const uint32_t mul_mat_subgroup_size_16 = std::max(mul_mat_subgroup_size, 16u);
  2273. const uint32_t mul_mat_subgroup_size_32 = std::max(mul_mat_subgroup_size, 32u);
  2274. const bool subgroup_min_size_16 = (!device->subgroup_size_control && device->subgroup_size >= 16) ||
  2275. (device->subgroup_size_control && device->subgroup_max_size >= 16);
  2276. // mulmat
  2277. std::vector<uint32_t> l_warptile, m_warptile, s_warptile,
  2278. l_warptile_id, m_warptile_id, s_warptile_id,
  2279. l_warptile_mmq, m_warptile_mmq, s_warptile_mmq,
  2280. l_warptile_mmq_int, m_warptile_mmq_int, s_warptile_mmq_int,
  2281. l_warptile_mmq_int_k, m_warptile_mmq_int_k, s_warptile_mmq_int_k,
  2282. l_warptile_mmq_k, m_warptile_mmq_k, s_warptile_mmq_k,
  2283. l_warptile_mmqid, m_warptile_mmqid, s_warptile_mmqid,
  2284. l_warptile_mmqid_int, m_warptile_mmqid_int, s_warptile_mmqid_int,
  2285. l_warptile_mmqid_int_k, m_warptile_mmqid_int_k, s_warptile_mmqid_int_k;
  2286. std::array<uint32_t, 3> l_wg_denoms, m_wg_denoms, s_wg_denoms,
  2287. l_mmq_wg_denoms, m_mmq_wg_denoms, s_mmq_wg_denoms,
  2288. l_mmq_wg_denoms_k, m_mmq_wg_denoms_k, s_mmq_wg_denoms_k,
  2289. l_mmqid_wg_denoms, m_mmqid_wg_denoms, s_mmqid_wg_denoms;
  2290. uint32_t l_align, m_align, s_align;
  2291. if (device->coopmat2) {
  2292. // spec constants and tile sizes for non-quant matmul/matmul_id
  2293. l_warptile = { 256, 128, 256, 64, 1 };
  2294. m_warptile = { 256, 128, 128, 64, 0 };
  2295. s_warptile = { 128, 64, 64, 64, 0 };
  2296. l_wg_denoms = {128, 256, 1 };
  2297. m_wg_denoms = {128, 128, 1 };
  2298. s_wg_denoms = { 64, 64, 1 };
  2299. // spec constants and tile sizes for quant matmul (non-Qi_K)
  2300. l_warptile_mmq = { 256, 128, 256, 64, 1 };
  2301. m_warptile_mmq = { 256, 128, 128, 64, 1 };
  2302. s_warptile_mmq = { 256, 32, 64, 128, 0 };
  2303. l_mmq_wg_denoms = { 128, 256, 1 };
  2304. m_mmq_wg_denoms = { 128, 128, 1 };
  2305. s_mmq_wg_denoms = { 32, 64, 1 };
  2306. // spec constants and tile sizes for quant matmul (Qi_K)
  2307. l_warptile_mmq_k = { 256, 128, 256, 64, 1 };
  2308. m_warptile_mmq_k = { 256, 128, 128, 64, 1 };
  2309. s_warptile_mmq_k = { 256, 32, 64, 128, 0 };
  2310. l_mmq_wg_denoms_k = { 128, 256, 1 };
  2311. m_mmq_wg_denoms_k = { 128, 128, 1 };
  2312. s_mmq_wg_denoms_k = { 32, 64, 1 };
  2313. // spec constants and tile sizes for quant matmul_id
  2314. l_warptile_mmqid = { 256, 128, 128, 16, 1, device->subgroup_size };
  2315. m_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2316. s_warptile_mmqid = { 256, 128, 64, 16, 0, device->subgroup_size };
  2317. l_mmqid_wg_denoms = { 128, 128, 1 };
  2318. m_mmqid_wg_denoms = { 128, 64, 1 };
  2319. s_mmqid_wg_denoms = { 128, 64, 1 };
  2320. l_align = 128;
  2321. m_align = 64;
  2322. s_align = 32;
  2323. } else {
  2324. // Matrix cores require different warp group sizes
  2325. const uint32_t tm_l = device->coopmat_support ? device->coopmat_m : 4;
  2326. const uint32_t tm_m = device->coopmat_support ? device->coopmat_m : 4;
  2327. const uint32_t tm_s = device->coopmat_support ? device->coopmat_m : 2;
  2328. const uint32_t tn_l = device->coopmat_support ? device->coopmat_n : 4;
  2329. const uint32_t tn_m = device->coopmat_support ? device->coopmat_n : 2;
  2330. const uint32_t tn_s = device->coopmat_support ? device->coopmat_n : 2;
  2331. const uint32_t tk_l = device->coopmat_support ? device->coopmat_k : 1;
  2332. const uint32_t tk_m = device->coopmat_support ? device->coopmat_k : 1;
  2333. const uint32_t tk_s = device->coopmat_support ? device->coopmat_k : 1;
  2334. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2335. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2336. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2337. l_warptile_mmq = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, subgroup_size_8 };
  2338. m_warptile_mmq = { 128, 64, 64, 32, subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, subgroup_size_8 };
  2339. s_warptile_mmq = { subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, subgroup_size_8 };
  2340. // Integer MMQ has a smaller shared memory profile, but heavier register use
  2341. l_warptile_mmq_int = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2342. m_warptile_mmq_int = { 128, 64, 64, 32, subgroup_size_8, 32, 2, 2, 2, 1, subgroup_size_8 };
  2343. s_warptile_mmq_int = { subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, subgroup_size_8 };
  2344. // K-quants use even more registers, mitigate by setting WMITER to 1
  2345. l_warptile_mmq_int_k = { 128, 128, 128, 32, subgroup_size_8 * 2, 64, 1, 4, 4, 1, subgroup_size_8 };
  2346. m_warptile_mmq_int_k = { 128, 64, 64, 32, subgroup_size_8, 32, 1, 2, 2, 1, subgroup_size_8 };
  2347. s_warptile_mmq_int_k = { subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, subgroup_size_8 };
  2348. l_warptile_id = { 128, 128, 128, 16, mul_mat_subgroup_size_16 * 2, 64, 2, tm_l, tn_l, tk_l, mul_mat_subgroup_size_16 };
  2349. m_warptile_id = { 128, 64, 64, 16, mul_mat_subgroup_size_16, 32, 2, tm_m, tn_m, tk_m, mul_mat_subgroup_size_16 };
  2350. s_warptile_id = { mul_mat_subgroup_size_16, 32, 32, 16, 32, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_16 };
  2351. l_warptile_mmqid = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, tm_l, tn_l, tk_l, mul_mat_subgroup_size_8 };
  2352. m_warptile_mmqid = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, tm_m, tn_m, tk_m, mul_mat_subgroup_size_8 };
  2353. s_warptile_mmqid = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, tm_s, tn_s, tk_s, mul_mat_subgroup_size_8 };
  2354. l_warptile_mmqid_int = { 128, 128, 128, 32, mul_mat_subgroup_size_8 * 2, 64, 2, 4, 4, 1, mul_mat_subgroup_size_8 };
  2355. m_warptile_mmqid_int = { 128, 64, 64, 32, mul_mat_subgroup_size_8, 32, 2, 2, 2, 1, mul_mat_subgroup_size_8 };
  2356. s_warptile_mmqid_int = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 2, 2, 1, 1, mul_mat_subgroup_size_8 };
  2357. l_warptile_mmqid_int_k = { 128, 128, 128, 32, mul_mat_subgroup_size_16 * 2, 64, 1, 4, 4, 1, mul_mat_subgroup_size_16 };
  2358. m_warptile_mmqid_int_k = { 128, 64, 64, 32, mul_mat_subgroup_size_16, 32, 1, 2, 2, 1, mul_mat_subgroup_size_16 };
  2359. s_warptile_mmqid_int_k = { mul_mat_subgroup_size_32, 32, 32, 32, 32, 32, 1, 2, 1, 1, mul_mat_subgroup_size_16 };
  2360. // chip specific tuning
  2361. if ((device->architecture == AMD_GCN) && (device->driver_id != vk::DriverId::eAmdProprietary)) {
  2362. m_warptile_mmq = m_warptile_mmq_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2363. m_warptile_mmqid = m_warptile_mmqid_int = { 256, 64, 64, 32, 16, 16, 2, 2, 2, 1, 16 };
  2364. }
  2365. l_mmq_wg_denoms = l_wg_denoms = {128, 128, 1 };
  2366. m_mmq_wg_denoms = m_wg_denoms = { 64, 64, 1 };
  2367. s_mmq_wg_denoms = s_wg_denoms = { 32, 32, 1 };
  2368. l_align = 128;
  2369. m_align = 64;
  2370. s_align = 32;
  2371. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  2372. ggml_type t = (ggml_type)i;
  2373. // Disable medium and large matrix multiplication if not enough shared memory is available
  2374. // Check mmq warptiles as the largest configuration
  2375. // Throw an error if not enough for any matrix multiplication is available
  2376. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmq, false, t)) {
  2377. std::cerr << "ggml_vulkan: Error: Shared memory size too small for matrix multiplication." << std::endl;
  2378. throw std::runtime_error("Shared memory size too small for matrix multiplication.");
  2379. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmq, false, t)) {
  2380. device->mul_mat_m[i] = false;
  2381. device->mul_mat_l[i] = false;
  2382. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmq, false, t)) {
  2383. device->mul_mat_l[i] = false;
  2384. }
  2385. // Disable mul_mat_id if not enough shared memory is available
  2386. if (!ggml_vk_matmul_shmem_support(device, s_warptile_mmqid, true, t)) {
  2387. device->mul_mat_id_s[i] = false;
  2388. device->mul_mat_id_m[i] = false;
  2389. device->mul_mat_id_l[i] = false;
  2390. } else if (!ggml_vk_matmul_shmem_support(device, m_warptile_mmqid, true, t)) {
  2391. device->mul_mat_id_m[i] = false;
  2392. device->mul_mat_id_l[i] = false;
  2393. } else if (!ggml_vk_matmul_shmem_support(device, l_warptile_mmqid, true, t)) {
  2394. device->mul_mat_id_l[i] = false;
  2395. }
  2396. }
  2397. }
  2398. if (!device->pipeline_matmul_f32) {
  2399. device->pipeline_matmul_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2400. }
  2401. if (!device->pipeline_matmul_f32_f16) {
  2402. device->pipeline_matmul_f32_f16 = std::make_shared<vk_matmul_pipeline_struct>();
  2403. }
  2404. if (!device->pipeline_matmul_id_f32) {
  2405. device->pipeline_matmul_id_f32 = std::make_shared<vk_matmul_pipeline_struct>();
  2406. }
  2407. if (!device->pipeline_matmul_bf16) {
  2408. device->pipeline_matmul_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2409. }
  2410. if (!device->pipeline_matmul_id_bf16) {
  2411. device->pipeline_matmul_id_bf16 = std::make_shared<vk_matmul_pipeline_struct>();
  2412. }
  2413. std::vector<std::future<void>> compiles;
  2414. auto const &ggml_vk_create_pipeline = [&](vk_device& device, vk_pipeline& pipeline, const char *name, size_t spv_size, const void* spv_data, const char *entrypoint,
  2415. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2416. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2417. if (!require_full_subgroups && required_subgroup_size == 0) {
  2418. required_subgroup_size = get_subgroup_size(name, device->architecture);
  2419. }
  2420. if (!pipeline) {
  2421. pipeline = std::make_shared<vk_pipeline_struct>();
  2422. }
  2423. if (!pipeline->initialized) {
  2424. pipeline->name = name;
  2425. pipeline->parameter_count = parameter_count;
  2426. pipeline->push_constant_size = push_constant_size;
  2427. pipeline->wg_denoms = wg_denoms;
  2428. pipeline->align = align;
  2429. pipeline->initialized = true;
  2430. }
  2431. if (!pipeline->needed || pipeline->compiled) {
  2432. return;
  2433. }
  2434. // TODO: We're no longer benefitting from the async compiles (shaders are
  2435. // compiled individually, as needed) and this complexity can be removed.
  2436. {
  2437. // wait until fewer than N compiles are in progress
  2438. uint32_t N = std::max(1u, std::thread::hardware_concurrency());
  2439. std::unique_lock<std::mutex> guard(compile_count_mutex);
  2440. while (compile_count >= N) {
  2441. compile_count_cond.wait(guard);
  2442. }
  2443. compile_count++;
  2444. }
  2445. compiles.push_back(std::async(ggml_vk_create_pipeline_func, std::ref(device), std::ref(pipeline), spv_size, spv_data, entrypoint,
  2446. parameter_count, wg_denoms, specialization_constants, disable_robustness, require_full_subgroups, required_subgroup_size));
  2447. };
  2448. auto const &ggml_vk_create_pipeline2 = [&](vk_device& device, vk_pipeline& pipeline, const std::string &name, size_t spv_size, const void* spv_data, const char *entrypoint,
  2449. uint32_t parameter_count, uint32_t push_constant_size, std::array<uint32_t, 3> wg_denoms, const std::vector<uint32_t>& specialization_constants,
  2450. uint32_t align, bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0) {
  2451. return ggml_vk_create_pipeline(device, pipeline, name.c_str(), spv_size, spv_data, entrypoint,
  2452. parameter_count, push_constant_size, wg_denoms, specialization_constants,
  2453. align, disable_robustness, require_full_subgroups, required_subgroup_size);
  2454. };
  2455. 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> {
  2456. return {fa_rows_cols(path, hsk, hsv, clamp, type, small_rows)[0], 1, 1};
  2457. };
  2458. 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> {
  2459. // For large number of rows, 128 invocations seems to work best.
  2460. // For small number of rows (e.g. N==1), 256 works better. But matrix granularity for 256 is 32, so we
  2461. // can't use 256 for D==80.
  2462. // For scalar, use 128 (arbitrary)
  2463. // The same D_split value is used for both HSK and HSV, so just base it on the union of the LSBs.
  2464. const uint32_t D = (hsk|hsv);
  2465. uint32_t wg_size = (path == FA_SCALAR || path == FA_COOPMAT1)
  2466. ? scalar_flash_attention_workgroup_size
  2467. : ((small_rows && (D % 32) == 0) ? 256 : 128);
  2468. auto rows_cols = fa_rows_cols(path, hsk, hsv, clamp, type, small_rows);
  2469. // D_split can't be larger than a subgroup because we use subgroupShuffle to reduce it.
  2470. // D_split can't be larger than the LSB of D divided by 4 due to vectorization in the shader.
  2471. const uint32_t D_lsb = D ^ (D & (D-1));
  2472. uint32_t D_split = std::min(std::min(device->subgroup_size, 8u), D_lsb / 4);
  2473. return {wg_size, rows_cols[0], rows_cols[1], hsk, hsv, clamp, D_split};
  2474. };
  2475. #define CREATE_FA(TYPE, NAMELC, FAPATH, SUFFIX) \
  2476. for (auto &fa : device->pipeline_flash_attn_f32_f16[TYPE]) { \
  2477. uint32_t HSK = fa.first.HSK; \
  2478. uint32_t HSV = fa.first.HSV; \
  2479. bool small_rows = fa.first.small_rows; \
  2480. FaCodePath path = fa.first.path; \
  2481. bool aligned = fa.first.aligned; \
  2482. bool f32acc = fa.first.f32acc; \
  2483. if (path == FAPATH) { \
  2484. if (aligned) { \
  2485. if (f32acc) { \
  2486. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_aligned_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_align(FAPATH,HSK,HSV,TYPE,small_rows), true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2487. } else { \
  2488. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_aligned_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,0,TYPE,small_rows), fa_align(FAPATH,HSK,HSV,TYPE,small_rows), true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2489. } \
  2490. } else { \
  2491. if (f32acc) { \
  2492. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_f32acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,1,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows), 1, true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2493. } else { \
  2494. ggml_vk_create_pipeline(device, fa.second, "flash_attn_f32_f16_f16acc" #NAMELC, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _len, flash_attn_f32_f16_ ## NAMELC ## _f16acc ## SUFFIX ## _data, "main", 6, sizeof(vk_flash_attn_push_constants), fa_wg_denoms(FAPATH, HSK,HSV,1,TYPE,small_rows), fa_spec_constants(FAPATH, HSK,HSV,1,TYPE,small_rows), 1, true, true, (FAPATH==FA_COOPMAT1 ? 32 : 0)); \
  2495. } \
  2496. } \
  2497. } \
  2498. }
  2499. CREATE_FA(GGML_TYPE_F32, f32, FA_SCALAR, )
  2500. CREATE_FA(GGML_TYPE_F16, f16, FA_SCALAR, )
  2501. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_SCALAR, )
  2502. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_SCALAR, )
  2503. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2504. if (device->coopmat1_fa_support) {
  2505. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT1, _cm1)
  2506. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT1, _cm1)
  2507. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT1, _cm1)
  2508. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT1, _cm1)
  2509. }
  2510. #endif
  2511. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2512. if (device->coopmat2) {
  2513. CREATE_FA(GGML_TYPE_F32, f32, FA_COOPMAT2, _cm2)
  2514. CREATE_FA(GGML_TYPE_F16, f16, FA_COOPMAT2, _cm2)
  2515. CREATE_FA(GGML_TYPE_Q4_0, q4_0, FA_COOPMAT2, _cm2)
  2516. CREATE_FA(GGML_TYPE_Q4_1, q4_1, FA_COOPMAT2, _cm2)
  2517. CREATE_FA(GGML_TYPE_Q5_0, q5_0, FA_COOPMAT2, _cm2)
  2518. CREATE_FA(GGML_TYPE_Q5_1, q5_1, FA_COOPMAT2, _cm2)
  2519. CREATE_FA(GGML_TYPE_Q8_0, q8_0, FA_COOPMAT2, _cm2)
  2520. CREATE_FA(GGML_TYPE_IQ4_NL, iq4_nl, FA_COOPMAT2, _cm2)
  2521. }
  2522. #endif
  2523. #undef CREATE_FA
  2524. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2525. if (device->coopmat2) {
  2526. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2527. #define CREATE_MM(PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2528. 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); \
  2529. 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); \
  2530. 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); \
  2531. 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); \
  2532. 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); \
  2533. 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); \
  2534. // Create 2 variants, {f16,f32} accumulator
  2535. #define CREATE_MM2(PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2536. CREATE_MM(PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2537. CREATE_MM(PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT) \
  2538. CREATE_MM2(pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2539. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2540. if (device->coopmat_bf16_support) {
  2541. CREATE_MM(pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3)
  2542. }
  2543. #endif
  2544. 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)
  2545. 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)
  2546. 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)
  2547. 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)
  2548. 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)
  2549. 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)
  2550. 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)
  2551. 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)
  2552. 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)
  2553. 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)
  2554. 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)
  2555. 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)
  2556. 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)
  2557. 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)
  2558. 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)
  2559. 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)
  2560. 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)
  2561. 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)
  2562. 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)
  2563. 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)
  2564. GGML_ASSERT(device->subgroup_ballot);
  2565. CREATE_MM2(pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2566. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2567. if (device->coopmat_bf16_support) {
  2568. CREATE_MM(pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4)
  2569. }
  2570. #endif
  2571. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2572. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2573. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2574. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2575. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2576. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2577. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2578. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2579. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2580. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2581. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2582. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2583. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2584. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2585. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2586. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2587. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2588. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2589. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2590. CREATE_MM2(pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f16, mmqid_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4)
  2591. #undef CREATE_MM
  2592. #undef CREATE_MM2
  2593. } else
  2594. #endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  2595. #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2596. if (device->coopmat_support) {
  2597. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2598. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2599. if (device->mul_mat ## ID ## _l[TYPE]) \
  2600. 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); \
  2601. if (device->mul_mat ## ID ## _m[TYPE]) \
  2602. 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); \
  2603. if (device->mul_mat ## ID ## _s[TYPE]) \
  2604. 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); \
  2605. if (device->mul_mat ## ID ## _l[TYPE]) \
  2606. 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); \
  2607. if (device->mul_mat ## ID ## _m[TYPE]) \
  2608. 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); \
  2609. if (device->mul_mat ## ID ## _s[TYPE]) \
  2610. 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); \
  2611. // Create 2 variants, {f16,f32} accumulator
  2612. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2613. if (device->coopmat_acc_f16_support) { \
  2614. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2615. } \
  2616. if (device->coopmat_acc_f32_support) { \
  2617. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2618. } \
  2619. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2620. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2621. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2622. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, );
  2623. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2624. if (device->coopmat_bf16_support) {
  2625. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, )
  2626. }
  2627. #endif
  2628. if (device->coopmat_acc_f16_support) {
  2629. 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, );
  2630. 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, );
  2631. 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, );
  2632. 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, );
  2633. 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, );
  2634. 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, );
  2635. 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, );
  2636. 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, );
  2637. 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, );
  2638. 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, );
  2639. 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, );
  2640. 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, );
  2641. 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, );
  2642. 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, );
  2643. 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, );
  2644. 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, );
  2645. 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, );
  2646. 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, );
  2647. 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, );
  2648. 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, );
  2649. } else {
  2650. 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, );
  2651. 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, );
  2652. 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, );
  2653. 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, );
  2654. 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, );
  2655. 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, );
  2656. 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, );
  2657. 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, );
  2658. 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, );
  2659. 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, );
  2660. 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, );
  2661. 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, );
  2662. 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, );
  2663. 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, );
  2664. 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, );
  2665. 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, );
  2666. 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, );
  2667. 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, );
  2668. 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, );
  2669. 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, );
  2670. }
  2671. GGML_ASSERT(device->subgroup_ballot);
  2672. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2673. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2674. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2675. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2676. if (device->coopmat_bf16_support) {
  2677. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id);
  2678. }
  2679. #endif
  2680. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2681. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2682. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2683. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2684. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2685. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2686. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2687. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2688. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2689. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2690. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2691. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2692. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2693. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2694. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2695. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2696. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2697. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2698. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2699. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_id_push_constants, 4, _id);
  2700. #undef CREATE_MM2
  2701. #undef CREATE_MM
  2702. } else
  2703. #endif // defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  2704. if (device->fp16) {
  2705. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2706. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2707. if (device->mul_mat ## ID ## _l[TYPE]) \
  2708. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2709. if (device->mul_mat ## ID ## _m[TYPE]) \
  2710. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2711. if (device->mul_mat ## ID ## _s[TYPE]) \
  2712. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _len, NAMELC ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2713. if (device->mul_mat ## ID ## _l[TYPE]) \
  2714. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2715. if (device->mul_mat ## ID ## _m[TYPE]) \
  2716. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2717. if (device->mul_mat ## ID ## _s[TYPE]) \
  2718. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _len, NAMELC ## _aligned ## F16ACC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2719. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2720. if (device->mul_mat ## ID ## _l[TYPE]) { \
  2721. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->l, #NAMELC "_l", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2722. } \
  2723. if (device->mul_mat ## ID ## _m[TYPE]) { \
  2724. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->m, #NAMELC "_m", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2725. } \
  2726. if (device->mul_mat ## ID ## _s[TYPE]) { \
  2727. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME .f32acc->s, #NAMELC "_s", NAMELC ## _len, NAMELC ## _data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2728. } \
  2729. // Create 2 variants, {f16,f32} accumulator
  2730. #define CREATE_MM2(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2731. CREATE_MM(TYPE, PIPELINE_NAME . f16acc, NAMELC, _f16acc, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2732. CREATE_MM(TYPE, PIPELINE_NAME . f32acc, NAMELC, , WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2733. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2734. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2735. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16, matmul_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2736. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_f16_f32, matmul_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2737. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2738. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0], matmul_q4_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2739. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1], matmul_q4_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2740. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0], matmul_q5_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2741. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1], matmul_q5_1_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2742. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0], matmul_q8_0_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2743. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K], matmul_q2_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2744. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K], matmul_q3_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2745. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K], matmul_q4_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2746. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K], matmul_q5_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2747. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K], matmul_q6_k_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2748. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S], matmul_iq1_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2749. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M], matmul_iq1_m_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2750. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS], matmul_iq2_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2751. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS], matmul_iq2_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2752. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S], matmul_iq2_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2753. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS], matmul_iq3_xxs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2754. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S], matmul_iq3_s_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2755. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS], matmul_iq4_xs_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2756. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL], matmul_iq4_nl_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2757. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4], matmul_mxfp4_f32, mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2758. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2759. if (device->integer_dot_product) {
  2760. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_0], matmul_q4_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2761. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_1], matmul_q4_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2762. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_0], matmul_q5_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2763. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_1], matmul_q5_1_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2764. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q8_0], matmul_q8_0_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2765. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_MXFP4], matmul_mxfp4_q8_1, mmq_wg_denoms, warptile_mmq_int, vk_mat_mat_push_constants, 3, , 0);
  2766. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q2_K], matmul_q2_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2767. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q3_K], matmul_q3_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2768. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_K], matmul_q4_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2769. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_K], matmul_q5_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2770. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q6_K], matmul_q6_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, , 0);
  2771. }
  2772. #endif
  2773. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2774. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2775. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_subgroup_f16, wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2776. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_subgroup_f16_f32, wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2777. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2778. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2779. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2780. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2781. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2782. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2783. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2784. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2785. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2786. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2787. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2788. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_subgroup_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2789. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_subgroup_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2790. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_subgroup_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2791. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_subgroup_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2792. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_subgroup_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2793. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_subgroup_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2794. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_subgroup_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2795. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_subgroup_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2796. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_subgroup_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2797. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2798. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2799. if (device->integer_dot_product) {
  2800. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_0], matmul_id_subgroup_q4_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2801. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_1], matmul_id_subgroup_q4_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2802. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_0], matmul_id_subgroup_q5_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2803. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_1], matmul_id_subgroup_q5_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2804. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q8_0], matmul_id_subgroup_q8_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2805. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_MXFP4], matmul_id_subgroup_mxfp4_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2806. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q2_K], matmul_id_subgroup_q2_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2807. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q3_K], matmul_id_subgroup_q3_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2808. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_K], matmul_id_subgroup_q4_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2809. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_K], matmul_id_subgroup_q5_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2810. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q6_K], matmul_id_subgroup_q6_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2811. }
  2812. #endif
  2813. } else {
  2814. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2815. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16, matmul_id_f16, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2816. CREATE_MM2(GGML_TYPE_F16, pipeline_matmul_id_f16_f32, matmul_id_f16_f32, wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2817. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2818. CREATE_MM2(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0], matmul_id_q4_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2819. CREATE_MM2(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1], matmul_id_q4_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2820. CREATE_MM2(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0], matmul_id_q5_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2821. CREATE_MM2(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1], matmul_id_q5_1_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2822. CREATE_MM2(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0], matmul_id_q8_0_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2823. CREATE_MM2(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K], matmul_id_q2_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2824. CREATE_MM2(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K], matmul_id_q3_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2825. CREATE_MM2(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K], matmul_id_q4_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2826. CREATE_MM2(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K], matmul_id_q5_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2827. CREATE_MM2(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K], matmul_id_q6_k_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2828. CREATE_MM2(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S], matmul_id_iq1_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2829. CREATE_MM2(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M], matmul_id_iq1_m_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2830. CREATE_MM2(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS], matmul_id_iq2_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2831. CREATE_MM2(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS], matmul_id_iq2_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2832. CREATE_MM2(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S], matmul_id_iq2_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2833. CREATE_MM2(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS], matmul_id_iq3_xxs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2834. CREATE_MM2(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S], matmul_id_iq3_s_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2835. CREATE_MM2(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS], matmul_id_iq4_xs_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2836. CREATE_MM2(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL], matmul_id_iq4_nl_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2837. CREATE_MM2(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4], matmul_id_mxfp4_f32, mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2838. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2839. if (device->integer_dot_product) {
  2840. CREATE_MMQ(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_0], matmul_id_q4_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2841. CREATE_MMQ(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_1], matmul_id_q4_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2842. CREATE_MMQ(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_0], matmul_id_q5_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2843. CREATE_MMQ(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_1], matmul_id_q5_1_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2844. CREATE_MMQ(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q8_0], matmul_id_q8_0_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2845. CREATE_MMQ(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_MXFP4], matmul_id_mxfp4_q8_1, mmq_wg_denoms, warptile_mmqid_int, vk_mat_mat_id_push_constants, 4, _id, 0);
  2846. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q2_K], matmul_id_q2_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2847. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q3_K], matmul_id_q3_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2848. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q4_K], matmul_id_q4_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2849. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q5_K], matmul_id_q5_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2850. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id_q8_1[GGML_TYPE_Q6_K], matmul_id_q6_k_q8_1, mmq_wg_denoms, warptile_mmqid_int_k, vk_mat_mat_id_push_constants, 4, _id, 0);
  2851. }
  2852. #endif
  2853. }
  2854. #undef CREATE_MM2
  2855. #undef CREATE_MMQ
  2856. #undef CREATE_MM
  2857. } else {
  2858. // Create 6 variants, {s,m,l}x{unaligned,aligned}
  2859. #define CREATE_MM(TYPE, PIPELINE_NAME, NAMELC, F16ACC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID, REQSUBGROUPSIZE) \
  2860. if (device->mul_mat ## ID ## _l[TYPE]) \
  2861. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->l, #NAMELC #F16ACC "_l", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2862. if (device->mul_mat ## ID ## _m[TYPE]) \
  2863. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->m, #NAMELC #F16ACC "_m", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2864. if (device->mul_mat ## ID ## _s[TYPE]) \
  2865. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->s, #NAMELC #F16ACC "_s", NAMELC ## F16ACC ## _fp32_len, NAMELC ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, 1, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2866. if (device->mul_mat ## ID ## _l[TYPE]) \
  2867. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_l, #NAMELC #F16ACC "_aligned_l", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), l_ ## WG_DENOMS, l_ ## WARPTILE, l_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2868. if (device->mul_mat ## ID ## _m[TYPE]) \
  2869. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_m, #NAMELC #F16ACC "_aligned_m", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), m_ ## WG_DENOMS, m_ ## WARPTILE, m_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2870. if (device->mul_mat ## ID ## _s[TYPE]) \
  2871. ggml_vk_create_pipeline(device, device-> PIPELINE_NAME ->a_s, #NAMELC #F16ACC "_aligned_s", NAMELC ## _aligned ## F16ACC ## _fp32_len, NAMELC ## _aligned ## F16ACC ## _fp32_data, "main", PARAMCOUNT, sizeof(PUSHCONST), s_ ## WG_DENOMS, s_ ## WARPTILE, s_align, false, REQSUBGROUPSIZE > 0, REQSUBGROUPSIZE); \
  2872. #define CREATE_MMQ(TYPE, PIPELINE_NAME, NAMELC, WG_DENOMS, WARPTILE, PUSHCONST, PARAMCOUNT, ID) \
  2873. if (device->mul_mat ## ID ## _l[TYPE]) \
  2874. 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); \
  2875. if (device->mul_mat ## ID ## _m[TYPE]) \
  2876. 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); \
  2877. if (device->mul_mat ## ID ## _s[TYPE]) \
  2878. 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); \
  2879. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32, matmul_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2880. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_f32_f16, matmul_f32_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2881. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16.f32acc, matmul_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2882. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_f16_f32.f32acc, matmul_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2883. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2884. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_0].f32acc, matmul_q4_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2885. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_1].f32acc, matmul_q4_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2886. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_0].f32acc, matmul_q5_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2887. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_1].f32acc, matmul_q5_1_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2888. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q8_0].f32acc, matmul_q8_0_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2889. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2890. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2891. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2892. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2893. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2894. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_S].f32acc, matmul_iq1_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2895. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ1_M].f32acc, matmul_iq1_m_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2896. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XXS].f32acc, matmul_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2897. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_XS].f32acc, matmul_iq2_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2898. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ2_S].f32acc, matmul_iq2_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2899. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_XXS].f32acc, matmul_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2900. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ3_S].f32acc, matmul_iq3_s_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2901. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_XS].f32acc, matmul_iq4_xs_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2902. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat[GGML_TYPE_IQ4_NL].f32acc, matmul_iq4_nl_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2903. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat[GGML_TYPE_MXFP4].f32acc, matmul_mxfp4_f32, , mmq_wg_denoms, warptile_mmq, vk_mat_mat_push_constants, 3, , 0);
  2904. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  2905. if (device->integer_dot_product) {
  2906. 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, );
  2907. 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, );
  2908. 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, );
  2909. 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, );
  2910. 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, );
  2911. CREATE_MMQ(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q2_K].f32acc, matmul_q2_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2912. CREATE_MMQ(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q3_K].f32acc, matmul_q3_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2913. CREATE_MMQ(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q4_K].f32acc, matmul_q4_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2914. CREATE_MMQ(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q5_K].f32acc, matmul_q5_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2915. CREATE_MMQ(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_q8_1[GGML_TYPE_Q6_K].f32acc, matmul_q6_k_q8_1, mmq_wg_denoms, warptile_mmq_int_k, vk_mat_mat_push_constants, 3, );
  2916. }
  2917. #endif
  2918. if (device->subgroup_ballot && device->subgroup_require_full_support && subgroup_min_size_16) {
  2919. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_subgroup_f32_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2920. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_subgroup_f16, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2921. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_subgroup_f16_f32, , wg_denoms, warptile_id, vk_mat_mat_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2922. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_subgroup_bf16, , wg_denoms, warptile_id, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size_16);
  2923. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_subgroup_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2924. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_subgroup_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2925. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_subgroup_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2926. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_subgroup_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2927. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_subgroup_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2928. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_subgroup_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2929. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_subgroup_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2930. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_subgroup_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2931. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_subgroup_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2932. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_subgroup_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2933. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_subgroup_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2934. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_subgroup_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2935. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_subgroup_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2936. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_subgroup_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2937. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_subgroup_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2938. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_subgroup_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2939. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_subgroup_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2940. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_subgroup_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2941. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_subgroup_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2942. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_subgroup_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, mul_mat_subgroup_size);
  2943. } else {
  2944. CREATE_MM(GGML_TYPE_F32, pipeline_matmul_id_f32, matmul_id_f32_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2945. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16.f32acc, matmul_id_f16, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2946. CREATE_MM(GGML_TYPE_F16, pipeline_matmul_id_f16_f32.f32acc, matmul_id_f16_f32, , wg_denoms, warptile, vk_mat_mat_push_constants, 4, _id, 0);
  2947. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2948. CREATE_MM(GGML_TYPE_Q4_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_0].f32acc, matmul_id_q4_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2949. CREATE_MM(GGML_TYPE_Q4_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_1].f32acc, matmul_id_q4_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2950. CREATE_MM(GGML_TYPE_Q5_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_0].f32acc, matmul_id_q5_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2951. CREATE_MM(GGML_TYPE_Q5_1, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_1].f32acc, matmul_id_q5_1_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2952. CREATE_MM(GGML_TYPE_Q8_0, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q8_0].f32acc, matmul_id_q8_0_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2953. CREATE_MM(GGML_TYPE_Q2_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q2_K].f32acc, matmul_id_q2_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2954. CREATE_MM(GGML_TYPE_Q3_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q3_K].f32acc, matmul_id_q3_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2955. CREATE_MM(GGML_TYPE_Q4_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q4_K].f32acc, matmul_id_q4_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2956. CREATE_MM(GGML_TYPE_Q5_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q5_K].f32acc, matmul_id_q5_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2957. CREATE_MM(GGML_TYPE_Q6_K, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_Q6_K].f32acc, matmul_id_q6_k_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2958. CREATE_MM(GGML_TYPE_IQ1_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_S].f32acc, matmul_id_iq1_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2959. CREATE_MM(GGML_TYPE_IQ1_M, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ1_M].f32acc, matmul_id_iq1_m_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2960. CREATE_MM(GGML_TYPE_IQ2_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XXS].f32acc, matmul_id_iq2_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2961. CREATE_MM(GGML_TYPE_IQ2_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_XS].f32acc, matmul_id_iq2_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2962. CREATE_MM(GGML_TYPE_IQ2_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ2_S].f32acc, matmul_id_iq2_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2963. CREATE_MM(GGML_TYPE_IQ3_XXS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_XXS].f32acc, matmul_id_iq3_xxs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2964. CREATE_MM(GGML_TYPE_IQ3_S, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ3_S].f32acc, matmul_id_iq3_s_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2965. CREATE_MM(GGML_TYPE_IQ4_XS, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_XS].f32acc, matmul_id_iq4_xs_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2966. CREATE_MM(GGML_TYPE_IQ4_NL, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_IQ4_NL].f32acc, matmul_id_iq4_nl_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2967. CREATE_MM(GGML_TYPE_MXFP4, pipeline_dequant_mul_mat_mat_id[GGML_TYPE_MXFP4].f32acc, matmul_id_mxfp4_f32, , mmq_wg_denoms, warptile_mmqid, vk_mat_mat_id_push_constants, 4, _id, 0);
  2968. }
  2969. }
  2970. // reusing CREATE_MM from the fp32 path
  2971. if ((device->coopmat2 || device->coopmat_support)
  2972. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  2973. && !device->coopmat_bf16_support
  2974. #endif
  2975. ) {
  2976. // use scalar tile sizes
  2977. l_warptile = { 128, 128, 128, 16, subgroup_size_8 * 2, 64, 2, 4, 4, 1, subgroup_size_8 };
  2978. m_warptile = { 128, 64, 64, 16, subgroup_size_8, 32, 2, 4, 2, 1, subgroup_size_8 };
  2979. s_warptile = { subgroup_size_16, 32, 32, 16, 32, 32, 2, 2, 2, 1, subgroup_size_8 };
  2980. l_wg_denoms = {128, 128, 1 };
  2981. m_wg_denoms = { 64, 64, 1 };
  2982. s_wg_denoms = { 32, 32, 1 };
  2983. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_bf16, matmul_bf16, , wg_denoms, warptile, vk_mat_mat_push_constants, 3, , 0);
  2984. CREATE_MM(GGML_TYPE_BF16, pipeline_matmul_id_bf16, matmul_id_bf16, , wg_denoms, warptile, vk_mat_mat_id_push_constants, 4, _id, 0);
  2985. }
  2986. #undef CREATE_MM
  2987. // mul mat vec
  2988. // the number of rows computed per shader depends on GPU model and quant
  2989. uint32_t rm_stdq = 1;
  2990. uint32_t rm_kq = 2;
  2991. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  2992. if (device->architecture == AMD_GCN) {
  2993. rm_stdq = 2;
  2994. rm_kq = 4;
  2995. }
  2996. } else if (device->vendor_id == VK_VENDOR_ID_INTEL)
  2997. rm_stdq = 2;
  2998. uint32_t rm_iq = 2 * rm_kq;
  2999. const bool use_subgroups = device->subgroup_arithmetic && device->architecture != vk_device_architecture::AMD_GCN;
  3000. // Ensure a subgroup size >= 16 is available
  3001. const bool use_subgroups16 = use_subgroups && subgroup_min_size_16;
  3002. const uint32_t subgroup_size = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control && device->subgroup_min_size <= 16 && device->subgroup_max_size >= 16) ? 16 : device->subgroup_size;
  3003. const uint32_t subgroup_size16 = std::max(subgroup_size, 16u);
  3004. const uint32_t force_subgroup_size = use_subgroups ? subgroup_size : 0;
  3005. const uint32_t force_subgroup_size16 = use_subgroups16 ? subgroup_size16 : 0;
  3006. static constexpr uint32_t mul_mat_vec_num_bindings = 5;
  3007. static constexpr uint32_t mul_mat_vec_id_num_bindings = 6;
  3008. for (uint32_t w = 0; w < DMMV_WG_SIZE_COUNT; ++w) {
  3009. const uint32_t wg_size_subgroup = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size : (subgroup_size * 4);
  3010. const uint32_t wg_size_subgroup16 = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size16 : (subgroup_size16 * 4);
  3011. const shader_reduction_mode reduc = (use_subgroups && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  3012. (use_subgroups && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  3013. SHADER_REDUCTION_MODE_SHMEM;
  3014. const shader_reduction_mode reduc16 = (use_subgroups16 && w == DMMV_WG_SIZE_SUBGROUP) ? SHADER_REDUCTION_MODE_SUBGROUP :
  3015. (use_subgroups16 && w == DMMV_WG_SIZE_LARGE) ? SHADER_REDUCTION_MODE_HYBRID :
  3016. SHADER_REDUCTION_MODE_SHMEM;
  3017. for (uint32_t i = 0; i < mul_mat_vec_max_cols; ++i) {
  3018. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f32_f32", arr_dmmv_f32_f32_f32_len[reduc], arr_dmmv_f32_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3019. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f32_f32", arr_dmmv_f16_f32_f32_len[reduc], arr_dmmv_f16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3020. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f32_f32", arr_dmmv_bf16_f32_f32_len[reduc], arr_dmmv_bf16_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3021. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f32_f32", arr_dmmv_q4_0_f32_f32_len[reduc], arr_dmmv_q4_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3022. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f32_f32", arr_dmmv_q4_1_f32_f32_len[reduc], arr_dmmv_q4_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3023. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f32_f32", arr_dmmv_q5_0_f32_f32_len[reduc], arr_dmmv_q5_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3024. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f32_f32", arr_dmmv_q5_1_f32_f32_len[reduc], arr_dmmv_q5_1_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3025. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f32_f32", arr_dmmv_q8_0_f32_f32_len[reduc], arr_dmmv_q8_0_f32_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3026. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f32_f32", arr_dmmv_q2_k_f32_f32_len[reduc16], arr_dmmv_q2_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3027. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f32_f32", arr_dmmv_q3_k_f32_f32_len[reduc16], arr_dmmv_q3_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3028. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f32_f32", arr_dmmv_q4_k_f32_f32_len[reduc16], arr_dmmv_q4_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3029. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f32_f32", arr_dmmv_q5_k_f32_f32_len[reduc16], arr_dmmv_q5_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3030. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f32_f32", arr_dmmv_q6_k_f32_f32_len[reduc16], arr_dmmv_q6_k_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3031. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f32_f32", arr_dmmv_iq1_s_f32_f32_len[reduc16], arr_dmmv_iq1_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3032. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f32_f32", arr_dmmv_iq1_m_f32_f32_len[reduc16], arr_dmmv_iq1_m_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3033. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f32_f32", arr_dmmv_iq2_xxs_f32_f32_len[reduc16], arr_dmmv_iq2_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3034. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f32_f32", arr_dmmv_iq2_xs_f32_f32_len[reduc16], arr_dmmv_iq2_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3035. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f32_f32", arr_dmmv_iq2_s_f32_f32_len[reduc16], arr_dmmv_iq2_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3036. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f32_f32", arr_dmmv_iq3_xxs_f32_f32_len[reduc16], arr_dmmv_iq3_xxs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3037. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f32_f32", arr_dmmv_iq3_s_f32_f32_len[reduc16], arr_dmmv_iq3_s_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3038. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f32_f32", arr_dmmv_iq4_xs_f32_f32_len[reduc16], arr_dmmv_iq4_xs_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3039. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f32_f32", arr_dmmv_iq4_nl_f32_f32_len[reduc16], arr_dmmv_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3040. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f32_f32", arr_dmmv_mxfp4_f32_f32_len[reduc16], arr_dmmv_mxfp4_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3041. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f16_f32", arr_dmmv_f32_f16_f32_len[reduc], arr_dmmv_f32_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3042. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f16_f32", arr_dmmv_f16_f16_f32_len[reduc], arr_dmmv_f16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3043. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_BF16][i], "mul_mat_vec_bf16_f16_f32", arr_dmmv_bf16_f16_f32_len[reduc], arr_dmmv_bf16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
  3044. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_f16_f32", arr_dmmv_q4_0_f16_f32_len[reduc], arr_dmmv_q4_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3045. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_f16_f32", arr_dmmv_q4_1_f16_f32_len[reduc], arr_dmmv_q4_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3046. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_f16_f32", arr_dmmv_q5_0_f16_f32_len[reduc], arr_dmmv_q5_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3047. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_f16_f32", arr_dmmv_q5_1_f16_f32_len[reduc], arr_dmmv_q5_1_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup, 2*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3048. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_f16_f32", arr_dmmv_q8_0_f16_f32_len[reduc], arr_dmmv_q8_0_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup, 1*rm_stdq, i+1}, 1, true, use_subgroups, force_subgroup_size);
  3049. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_f16_f32", arr_dmmv_q2_k_f16_f32_len[reduc16], arr_dmmv_q2_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3050. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_f16_f32", arr_dmmv_q3_k_f16_f32_len[reduc16], arr_dmmv_q3_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3051. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_f16_f32", arr_dmmv_q4_k_f16_f32_len[reduc16], arr_dmmv_q4_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3052. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_f16_f32", arr_dmmv_q5_k_f16_f32_len[reduc16], arr_dmmv_q5_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3053. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_f16_f32", arr_dmmv_q6_k_f16_f32_len[reduc16], arr_dmmv_q6_k_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_kq, 1, 1}, {wg_size_subgroup16, rm_kq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3054. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_f16_f32", arr_dmmv_iq1_s_f16_f32_len[reduc16], arr_dmmv_iq1_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3055. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_f16_f32", arr_dmmv_iq1_m_f16_f32_len[reduc16], arr_dmmv_iq1_m_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3056. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XXS][i], "mul_mat_vec_iq2_xxs_f16_f32", arr_dmmv_iq2_xxs_f16_f32_len[reduc16], arr_dmmv_iq2_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3057. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_XS][i], "mul_mat_vec_iq2_xs_f16_f32", arr_dmmv_iq2_xs_f16_f32_len[reduc16], arr_dmmv_iq2_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3058. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ2_S][i], "mul_mat_vec_iq2_s_f16_f32", arr_dmmv_iq2_s_f16_f32_len[reduc16], arr_dmmv_iq2_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3059. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_XXS][i], "mul_mat_vec_iq3_xxs_f16_f32", arr_dmmv_iq3_xxs_f16_f32_len[reduc16], arr_dmmv_iq3_xxs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3060. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ3_S][i], "mul_mat_vec_iq3_s_f16_f32", arr_dmmv_iq3_s_f16_f32_len[reduc16], arr_dmmv_iq3_s_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3061. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_f16_f32", arr_dmmv_iq4_xs_f16_f32_len[reduc16], arr_dmmv_iq4_xs_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3062. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f16_f32", arr_dmmv_iq4_nl_f16_f32_len[reduc16], arr_dmmv_iq4_nl_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3063. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f16_f32", arr_dmmv_mxfp4_f16_f32_len[reduc16], arr_dmmv_mxfp4_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
  3064. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3065. if (device->integer_dot_product) {
  3066. const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size;
  3067. const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4);
  3068. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_q8_1_f32", arr_dmmv_q4_0_q8_1_f32_len[reduc], arr_dmmv_q4_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3069. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_q8_1_f32", arr_dmmv_q4_1_q8_1_f32_len[reduc], arr_dmmv_q4_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3070. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_q8_1_f32", arr_dmmv_q5_0_q8_1_f32_len[reduc], arr_dmmv_q5_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3071. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_q8_1_f32", arr_dmmv_q5_1_q8_1_f32_len[reduc], arr_dmmv_q5_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2*rm_stdq, 1, 1}, {wg_size_subgroup_int, 2*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3072. ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_q8_1_f32", arr_dmmv_q8_0_q8_1_f32_len[reduc], arr_dmmv_q8_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_stdq, 1, 1}, {wg_size_subgroup_int, 1*rm_stdq, i+1}, 1, true, use_subgroups, subgroup_size_int);
  3073. }
  3074. #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT
  3075. }
  3076. }
  3077. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  3078. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  3079. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2, 1, 1}, {device->subgroup_size, 2}, 1);
  3080. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  3081. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  3082. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  3083. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {2*rm_stdq, 1, 1}, {device->subgroup_size, 2*rm_stdq}, 1, true);
  3084. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {1*rm_stdq, 1, 1}, {device->subgroup_size, 1*rm_stdq}, 1, true);
  3085. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  3086. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  3087. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  3088. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  3089. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_kq, 1, 1}, {subgroup_size_16, rm_kq}, 1, true);
  3090. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3091. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3092. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3093. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3094. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3095. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3096. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3097. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3098. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3099. 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", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {subgroup_size_16, rm_iq}, 1, true);
  3100. // dequant shaders
  3101. 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);
  3102. 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);
  3103. 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);
  3104. 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);
  3105. 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);
  3106. 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);
  3107. 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);
  3108. 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);
  3109. 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);
  3110. 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);
  3111. 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);
  3112. 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);
  3113. 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);
  3114. 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);
  3115. 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);
  3116. 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);
  3117. 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);
  3118. 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);
  3119. 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);
  3120. 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);
  3121. 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);
  3122. // get_rows
  3123. 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);
  3124. 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);
  3125. 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);
  3126. 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);
  3127. 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);
  3128. 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);
  3129. 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);
  3130. 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);
  3131. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q2_K], "get_rows_q2_k", get_rows_q2_k_len, get_rows_q2_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3132. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q3_K], "get_rows_q3_k", get_rows_q3_k_len, get_rows_q3_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3133. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q4_K], "get_rows_q4_k", get_rows_q4_k_len, get_rows_q4_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3134. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q5_K], "get_rows_q5_k", get_rows_q5_k_len, get_rows_q5_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3135. ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_Q6_K], "get_rows_q6_k", get_rows_q6_k_len, get_rows_q6_k_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3136. 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);
  3137. 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);
  3138. 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);
  3139. 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);
  3140. 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);
  3141. 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);
  3142. 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);
  3143. 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);
  3144. 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);
  3145. 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);
  3146. 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);
  3147. 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);
  3148. 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);
  3149. 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);
  3150. 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);
  3151. 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);
  3152. 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);
  3153. 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);
  3154. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q2_K], "get_rows_q2_k_f32", get_rows_q2_k_f32_len, get_rows_q2_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3155. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q3_K], "get_rows_q3_k_f32", get_rows_q3_k_f32_len, get_rows_q3_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3156. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q4_K], "get_rows_q4_k_f32", get_rows_q4_k_f32_len, get_rows_q4_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3157. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q5_K], "get_rows_q5_k_f32", get_rows_q5_k_f32_len, get_rows_q5_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3158. ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_Q6_K], "get_rows_q6_k_f32", get_rows_q6_k_f32_len, get_rows_q6_k_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
  3159. 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);
  3160. 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);
  3161. 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);
  3162. 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);
  3163. 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);
  3164. 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);
  3165. 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);
  3166. 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);
  3167. 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);
  3168. 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);
  3169. 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);
  3170. 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);
  3171. if (device->subgroup_clustered && device->subgroup_require_full_support) {
  3172. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1_x4, "quantize_q8_1_x4", quantize_q8_1_x4_subgroup_len, quantize_q8_1_x4_subgroup_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1, true, true);
  3173. } else {
  3174. ggml_vk_create_pipeline(device, device->pipeline_quantize_q8_1_x4, "quantize_q8_1_x4", quantize_q8_1_x4_len, quantize_q8_1_x4_data, "main", 2, 1 * sizeof(uint32_t), {32 * device->subgroup_size / 8, 1, 1}, { device->subgroup_size }, 1);
  3175. }
  3176. for (uint32_t i = 0; i < p021_max_gqa_ratio; ++i) {
  3177. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3178. ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_subgroup_add_len, mul_mat_vec_p021_f16_f32_subgroup_add_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_p021_push_constants), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true, true);
  3179. } else {
  3180. ggml_vk_create_pipeline2(device, device->pipeline_mul_mat_vec_p021_f16_f32[i], "mul_mat_vec_p021_f16_f32"+std::to_string(i+1), mul_mat_vec_p021_f16_f32_len, mul_mat_vec_p021_f16_f32_data, "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_p021_push_constants), {1, 1, 1}, {device->subgroup_size, i + 1}, 1, true);
  3181. }
  3182. }
  3183. 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", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_nc_push_constants), {1, 1, 1}, {}, 1);
  3184. 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);
  3185. 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);
  3186. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_f32, "rms_norm_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0}, 1, true);
  3187. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_f32, "rms_norm_mul_f32", rms_norm_f32_len, rms_norm_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3188. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_partials_f32, "rms_norm_partials_f32", rms_norm_partials_f32_len, rms_norm_partials_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 0}, 1, true);
  3189. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_partials_f32, "rms_norm_mul_partials_f32", rms_norm_partials_f32_len, rms_norm_partials_f32_data, "main", 4, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3190. if (device->float_controls_rte_fp16 &&
  3191. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= device->properties.limits.maxPushConstantsSize) {
  3192. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_rope_f32_f32, "rms_norm_mul_rope_f32_f32", rms_norm_mul_rope_f32_f32_len, rms_norm_mul_rope_f32_f32_data, "main", 7, sizeof(vk_op_rms_norm_mul_rope_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3193. ggml_vk_create_pipeline(device, device->pipeline_rms_norm_mul_rope_f32_f16, "rms_norm_mul_rope_f32_f16", rms_norm_mul_rope_f32_f16_rte_len, rms_norm_mul_rope_f32_f16_rte_data, "main", 7, sizeof(vk_op_rms_norm_mul_rope_push_constants), {1, 1, 1}, {0, 1}, 1, true);
  3194. }
  3195. 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);
  3196. 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);
  3197. 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);
  3198. 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);
  3199. 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);
  3200. 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);
  3201. 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);
  3202. ggml_vk_create_pipeline(device, device->pipeline_cpy_i32_f32, "cpy_i32_f32", cpy_i32_f32_len, cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3203. ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_i32, "cpy_f32_i32", cpy_f32_i32_len, cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3204. 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);
  3205. 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);
  3206. 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);
  3207. 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);
  3208. 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);
  3209. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_i32_f32, "contig_cpy_i32_f32", contig_cpy_i32_f32_len, contig_cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3210. ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_i32, "contig_cpy_f32_i32", contig_cpy_f32_i32_len, contig_cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3211. ggml_vk_create_pipeline(device, device->pipeline_cpy_transpose_32, "cpy_transpose_32", cpy_transpose_32_len, cpy_transpose_32_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1);
  3212. ggml_vk_create_pipeline(device, device->pipeline_cpy_transpose_16, "cpy_transpose_16", cpy_transpose_16_len, cpy_transpose_16_data, "main", 2, sizeof(vk_op_unary_push_constants), {1, 1, 1}, {}, 1);
  3213. if (device->float_controls_rte_fp16) {
  3214. 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);
  3215. 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);
  3216. 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);
  3217. 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);
  3218. 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);
  3219. 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);
  3220. } else {
  3221. 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);
  3222. 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);
  3223. 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);
  3224. 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);
  3225. 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);
  3226. 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);
  3227. }
  3228. #define SET_ROWS(itype, rte) \
  3229. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_F32], "set_rows_f32" #itype, set_rows_f32 ## itype ## rte ## _len, set_rows_f32 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3230. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_F16], "set_rows_f16" #itype, set_rows_f16 ## itype ## rte ## _len, set_rows_f16 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3231. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_BF16], "set_rows_bf16" #itype, set_rows_bf16 ## itype ## rte ## _len, set_rows_bf16 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3232. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q4_0], "set_rows_q4_0" #itype, set_rows_q4_0 ## itype ## rte ## _len, set_rows_q4_0 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3233. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q4_1], "set_rows_q4_1" #itype, set_rows_q4_1 ## itype ## rte ## _len, set_rows_q4_1 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3234. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q5_0], "set_rows_q5_0" #itype, set_rows_q5_0 ## itype ## rte ## _len, set_rows_q5_0 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3235. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q5_1], "set_rows_q5_1" #itype, set_rows_q5_1 ## itype ## rte ## _len, set_rows_q5_1 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3236. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_Q8_0], "set_rows_q8_0" #itype, set_rows_q8_0 ## itype ## rte ## _len, set_rows_q8_0 ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true); \
  3237. ggml_vk_create_pipeline(device, device->pipeline_set_rows ## itype [GGML_TYPE_IQ4_NL], "set_rows_iq4_nl" #itype, set_rows_iq4_nl ## itype ## rte ## _len, set_rows_iq4_nl ## itype ## rte ## _data, "main", 3, sizeof(vk_op_binary_push_constants), {1, 1, 1}, {1}, 1, true);
  3238. if (device->float_controls_rte_fp16) {
  3239. SET_ROWS(_i32, _rte)
  3240. SET_ROWS(_i64, _rte)
  3241. } else {
  3242. SET_ROWS(_i32, )
  3243. SET_ROWS(_i64, )
  3244. }
  3245. #undef SET_ROWS
  3246. 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);
  3247. 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);
  3248. 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);
  3249. 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);
  3250. 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);
  3251. 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);
  3252. auto get_suffix = [](bool src0_f16, bool src1_f16, bool dst_f16) {
  3253. std::string s;
  3254. s += std::string(src0_f16 ? "_f16" : "_f32");
  3255. s += std::string(src1_f16 ? "_f16" : "_f32");
  3256. s += std::string(dst_f16 ? "_f16" : "_f32");
  3257. return s;
  3258. };
  3259. bool rte = device->float_controls_rte_fp16;
  3260. #define CREATE_BINARY(name, namemod, spec, bindings) \
  3261. for (int s0 : {0,1}) for (int s1 : {0,1}) for (int d : {0,1}) \
  3262. ggml_vk_create_pipeline2(device, device->pipeline_ ## name ## namemod[s0][s1][d], \
  3263. #name + get_suffix(s0, s1, d) + #namemod, name ## _len[s0][s1][d][rte], name ## _data[s0][s1][d][rte], \
  3264. "main", (bindings), sizeof(vk_op_binary_push_constants), {512, 1, 1}, spec, 1);
  3265. CREATE_BINARY(add, , {0}, 4)
  3266. CREATE_BINARY(add, _norepeat, {1}, 4)
  3267. CREATE_BINARY(sub, , {0}, 3)
  3268. CREATE_BINARY(sub, _norepeat, {1}, 3)
  3269. CREATE_BINARY(mul, , {0}, 3)
  3270. CREATE_BINARY(mul, _norepeat, {1}, 3)
  3271. CREATE_BINARY(div, , {0}, 3)
  3272. CREATE_BINARY(div, _norepeat, {1}, 3)
  3273. CREATE_BINARY(add_rms, , {0}, 4)
  3274. CREATE_BINARY(add_rms, _norepeat, {1}, 4)
  3275. #undef CREATE_BINARY
  3276. if (device->multi_add) {
  3277. for (uint32_t i = 0; i < MAX_FUSED_ADDS; ++i) {
  3278. ggml_vk_create_pipeline2(device, device->pipeline_multi_add[i], "multi_add_f32_" + std::to_string(i+1), multi_add_f32_len, multi_add_f32_data, "main", MAX_PARAMETER_COUNT, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1);
  3279. ggml_vk_create_pipeline2(device, device->pipeline_multi_add_rms[i], "multi_add_rms_f32_" + std::to_string(i+1), multi_add_rms_f32_len, multi_add_rms_f32_data, "main", MAX_PARAMETER_COUNT, sizeof(vk_op_multi_add_push_constants), {512, 1, 1}, {i+2}, 1);
  3280. }
  3281. }
  3282. 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);
  3283. 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);
  3284. 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);
  3285. 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);
  3286. 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);
  3287. 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);
  3288. 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);
  3289. ggml_vk_create_pipeline(device, device->pipeline_upscale_bicubic_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BICUBIC}, 1);
  3290. 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);
  3291. 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);
  3292. ggml_vk_create_pipeline(device, device->pipeline_sqrt_f32, "sqrt_f32", sqrt_f32_len, sqrt_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3293. 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);
  3294. 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);
  3295. if (device->float_controls_rte_fp16) {
  3296. ggml_vk_create_pipeline(device, device->pipeline_log[0], "log_f32_rte", log_f32_rte_len, log_f32_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3297. ggml_vk_create_pipeline(device, device->pipeline_log[1], "log_f16_rte", log_f16_rte_len, log_f16_rte_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3298. } else {
  3299. ggml_vk_create_pipeline(device, device->pipeline_log[0], "log_f32", log_f32_len, log_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3300. ggml_vk_create_pipeline(device, device->pipeline_log[1], "log_f16", log_f16_len, log_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3301. }
  3302. 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);
  3303. ggml_vk_create_pipeline(device, device->pipeline_pad_f32, "pad_f32", pad_f32_len, pad_f32_data, "main", 2, sizeof(vk_op_pad_push_constants), {512, 1, 1}, {}, 1);
  3304. 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);
  3305. 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);
  3306. 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);
  3307. #define CREATE_UNARY(name) \
  3308. 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); \
  3309. 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);
  3310. CREATE_UNARY(gelu)
  3311. CREATE_UNARY(gelu_erf)
  3312. CREATE_UNARY(gelu_quick)
  3313. CREATE_UNARY(silu)
  3314. CREATE_UNARY(relu)
  3315. CREATE_UNARY(neg)
  3316. CREATE_UNARY(tanh)
  3317. CREATE_UNARY(sigmoid)
  3318. CREATE_UNARY(hardsigmoid)
  3319. CREATE_UNARY(hardswish)
  3320. CREATE_UNARY(abs)
  3321. CREATE_UNARY(softplus)
  3322. CREATE_UNARY(step)
  3323. CREATE_UNARY(round)
  3324. CREATE_UNARY(ceil)
  3325. CREATE_UNARY(floor)
  3326. CREATE_UNARY(trunc)
  3327. #undef CREATE_UNARY
  3328. #define CREATE_UNARY_RTE(name) \
  3329. if (device->float_controls_rte_fp16) { \
  3330. ggml_vk_create_pipeline(device, device->pipeline_ ## name [0], #name "_f32_rte", name ## _f32_rte_len, name ## _f32_rte_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3331. ggml_vk_create_pipeline(device, device->pipeline_ ## name [1], #name "_f16_rte", name ## _f16_rte_len, name ## _f16_rte_data, "main", 2, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); \
  3332. } else { \
  3333. 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); \
  3334. 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); \
  3335. }
  3336. CREATE_UNARY_RTE(exp)
  3337. #undef CREATE_UNARY_RTE
  3338. ggml_vk_create_pipeline(device, device->pipeline_add1_f16_f16, "add1_f16_f16", add1_f16_f16_len, add1_f16_f16_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  3339. ggml_vk_create_pipeline(device, device->pipeline_add1_f16_f32, "add1_f16_f32", add1_f16_f32_len, add1_f16_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  3340. ggml_vk_create_pipeline(device, device->pipeline_add1_f32_f32, "add1_f32_f32", add1_f32_f32_len, add1_f32_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {512, 1, 1}, {}, 1);
  3341. ggml_vk_create_pipeline(device, device->pipeline_arange_f32, "arange_f32", arange_f32_len, arange_f32_data, "main", 1, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3342. ggml_vk_create_pipeline(device, device->pipeline_fill_f32, "fill_f32", fill_f32_len, fill_f32_data, "main", 1, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
  3343. #define CREATE_GLU(name) \
  3344. if (device->float_controls_rte_fp16) { \
  3345. 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); \
  3346. 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); \
  3347. } else { \
  3348. 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); \
  3349. 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); \
  3350. }
  3351. CREATE_GLU(geglu)
  3352. CREATE_GLU(reglu)
  3353. CREATE_GLU(swiglu)
  3354. CREATE_GLU(swiglu_oai)
  3355. CREATE_GLU(geglu_erf)
  3356. CREATE_GLU(geglu_quick)
  3357. #undef CREATE_GLU
  3358. 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);
  3359. 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);
  3360. 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);
  3361. 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);
  3362. 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);
  3363. 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);
  3364. 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);
  3365. ggml_vk_create_pipeline(device, device->pipeline_soft_max_back_f32, "soft_max_back_f32", soft_max_back_f32_len, soft_max_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1, true);
  3366. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32, "rope_norm_f32", rope_norm_f32_len, rope_norm_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3367. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32, "rope_neox_f32", rope_neox_f32_len, rope_neox_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3368. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f32, "rope_multi_f32", rope_multi_f32_len, rope_multi_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3369. ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f32, "rope_vision_f32", rope_vision_f32_len, rope_vision_f32_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3370. if (device->float_controls_rte_fp16) {
  3371. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f16, "rope_norm_f16", rope_norm_f16_rte_len, rope_norm_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3372. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_rte_len, rope_neox_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3373. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f16, "rope_multi_f16", rope_multi_f16_rte_len, rope_multi_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3374. ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f16, "rope_vision_f16", rope_vision_f16_rte_len, rope_vision_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3375. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32_f16, "rope_norm_f32_f16", rope_norm_f32_f16_rte_len, rope_norm_f32_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3376. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32_f16, "rope_neox_f32_f16", rope_neox_f32_f16_rte_len, rope_neox_f32_f16_rte_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3377. } else {
  3378. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f16, "rope_norm_f16", rope_norm_f16_len, rope_norm_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3379. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f16, "rope_neox_f16", rope_neox_f16_len, rope_neox_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3380. ggml_vk_create_pipeline(device, device->pipeline_rope_multi_f16, "rope_multi_f16", rope_multi_f16_len, rope_multi_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3381. ggml_vk_create_pipeline(device, device->pipeline_rope_vision_f16, "rope_vision_f16", rope_vision_f16_len, rope_vision_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3382. ggml_vk_create_pipeline(device, device->pipeline_rope_norm_f32_f16, "rope_norm_f32_f16", rope_norm_f32_f16_len, rope_norm_f32_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3383. ggml_vk_create_pipeline(device, device->pipeline_rope_neox_f32_f16, "rope_neox_f32_f16", rope_neox_f32_f16_len, rope_neox_f32_f16_data, "main", 5, sizeof(vk_op_rope_push_constants), {1, 512, 1}, {}, 1);
  3384. }
  3385. for (uint32_t i = 0; i < num_argsort_pipelines; ++i) {
  3386. uint32_t BLOCK_SIZE = 1u << std::min(i, device->max_workgroup_size_log2);
  3387. if (i <= device->max_workgroup_size_log2 &&
  3388. 2 * sizeof(int) * BLOCK_SIZE <= device->properties.limits.maxComputeSharedMemorySize) {
  3389. const uint32_t NCOLS_PADDED_LOG2 = i;
  3390. ggml_vk_create_pipeline2(device, device->pipeline_argsort_f32[i], "argsort_f32_"+std::to_string(i), argsort_f32_len, argsort_f32_data, "main", 3, sizeof(vk_op_argsort_push_constants), {BLOCK_SIZE, 1, 1}, {BLOCK_SIZE, NCOLS_PADDED_LOG2}, 1, true);
  3391. }
  3392. const uint32_t WG_UNROLL_FACTOR = BLOCK_SIZE > 1 ? 2 : 1;
  3393. BLOCK_SIZE /= WG_UNROLL_FACTOR;
  3394. ggml_vk_create_pipeline2(device, device->pipeline_argsort_large_f32[i], "argsort_large_f32_"+std::to_string(i), argsort_large_f32_len, argsort_large_f32_data, "main", 3, sizeof(vk_op_argsort_push_constants), {BLOCK_SIZE * WG_UNROLL_FACTOR, 1, 1}, {BLOCK_SIZE, WG_UNROLL_FACTOR}, 1, true);
  3395. }
  3396. 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);
  3397. ggml_vk_create_pipeline(device, device->pipeline_sum_rows_f32, "sum_rows_f32", sum_rows_f32_len, sum_rows_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { device->subgroup_size }, 1);
  3398. 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);
  3399. #define IM2COL(bda) \
  3400. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32, "im2col_f32", im2col_f32 ## bda ## _len, im2col_f32 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \
  3401. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32, "im2col_3d_f32", im2col_3d_f32 ## bda ## _len, im2col_3d_f32 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \
  3402. if (device->float_controls_rte_fp16) { \
  3403. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16_rte ## bda ## _len, im2col_f32_f16_rte ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \
  3404. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32_f16, "im2col_3d_f32_f16", im2col_3d_f32_f16_rte ## bda ## _len, im2col_3d_f32_f16_rte ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \
  3405. } else { \
  3406. ggml_vk_create_pipeline(device, device->pipeline_im2col_f32_f16, "im2col_f32_f16", im2col_f32_f16 ## bda ## _len, im2col_f32_f16 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_push_constants), {512, 1, 1}, { device->subgroup_size }, 1, true); \
  3407. ggml_vk_create_pipeline(device, device->pipeline_im2col_3d_f32_f16, "im2col_3d_f32_f16", im2col_3d_f32_f16 ## bda ## _len, im2col_3d_f32_f16 ## bda ## _data, "main", 2, sizeof(vk_op_im2col_3d_push_constants), {512, 1, 1}, { 512 }, 1, true); \
  3408. }
  3409. if (device->shader_int64 && device->buffer_device_address) {
  3410. IM2COL(_bda)
  3411. } else {
  3412. IM2COL()
  3413. }
  3414. 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);
  3415. 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);
  3416. 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);
  3417. 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);
  3418. 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);
  3419. if (device->subgroup_arithmetic && device->subgroup_require_full_support) {
  3420. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 16}, 1, true, true);
  3421. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 16}, 1, true, true);
  3422. } else {
  3423. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 16}, 1, true, true);
  3424. ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 16}, 1, true, true);
  3425. }
  3426. ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_f32, "ssm_conv_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 3, sizeof(vk_op_ssm_conv_push_constants), {32, 1, 1}, {32}, 1);
  3427. 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);
  3428. 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);
  3429. // conv2d, conv_transpose_2d
  3430. for (uint32_t s = 0; s < CONV_SHAPE_COUNT; ++s) {
  3431. uint32_t conv2d_WG_SIZE = 256;
  3432. uint32_t conv2d_BS_K = 128;
  3433. uint32_t conv2d_BS_CRS = 16;
  3434. uint32_t use_collectives = 0; // Enables subgroup ops for preventing the re-calculation of indices.
  3435. uint32_t conv2d_BS_NPQ = 128;
  3436. uint32_t conv2d_TS_K = 8;
  3437. uint32_t conv2d_SHMEM_PAD = 4;
  3438. bool conv2d_UNROLL = true;
  3439. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3440. if (device->coopmat2) {
  3441. conv2d_SHMEM_PAD = 8; // 8 float16_t
  3442. }
  3443. #endif
  3444. if (device->vendor_id == VK_VENDOR_ID_INTEL) {
  3445. conv2d_SHMEM_PAD = 0;
  3446. conv2d_UNROLL = false;
  3447. } else if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3448. conv2d_SHMEM_PAD = device->architecture == vk_device_architecture::AMD_GCN ? 1 : 4;
  3449. }
  3450. switch (s) {
  3451. default:
  3452. case CONV_SHAPE_128x128:
  3453. conv2d_BS_K = conv_shapes_wg_denoms[CONV_SHAPE_128x128][0];
  3454. conv2d_BS_NPQ = conv_shapes_wg_denoms[CONV_SHAPE_128x128][1];
  3455. conv2d_BS_CRS = 16;
  3456. if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != vk_device_architecture::AMD_GCN) {
  3457. conv2d_UNROLL = false;
  3458. }
  3459. break;
  3460. case CONV_SHAPE_64x32:
  3461. conv2d_BS_K = conv_shapes_wg_denoms[CONV_SHAPE_64x32][0];
  3462. conv2d_BS_NPQ = conv_shapes_wg_denoms[CONV_SHAPE_64x32][1];
  3463. conv2d_BS_CRS = 32;
  3464. conv2d_TS_K = 4;
  3465. break;
  3466. case CONV_SHAPE_32x256:
  3467. conv2d_BS_K = conv_shapes_wg_denoms[CONV_SHAPE_32x256][0];
  3468. conv2d_BS_NPQ = conv_shapes_wg_denoms[CONV_SHAPE_32x256][1];
  3469. conv2d_BS_CRS = 16;
  3470. break;
  3471. }
  3472. // Use collectives on pre-Turing NVIDIA GPUs and GCN AMD cards, which had slower integer math.
  3473. bool allow_collectives_nv = device->vendor_id != VK_VENDOR_ID_NVIDIA ||
  3474. device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  3475. bool allow_collectives_amd = device->vendor_id != VK_VENDOR_ID_AMD ||
  3476. device->architecture == vk_device_architecture::AMD_GCN;
  3477. if (device->subgroup_shuffle &&
  3478. device->vendor_id != VK_VENDOR_ID_INTEL && // Do not enable collectives on Intel, see PR 14316.
  3479. allow_collectives_nv &&
  3480. allow_collectives_amd) {
  3481. use_collectives = 1;
  3482. conv2d_BS_CRS = std::min(
  3483. device->subgroup_size,
  3484. conv2d_BS_CRS); // CRS block size should be capped at subgroup size for correctness when shuffle is used.
  3485. }
  3486. uint32_t conv2d_shmem_req =
  3487. (conv2d_BS_K * (conv2d_BS_CRS + conv2d_SHMEM_PAD) + conv2d_BS_CRS * (conv2d_BS_NPQ + conv2d_SHMEM_PAD)) * sizeof(float);
  3488. if (device->properties.limits.maxComputeSharedMemorySize < conv2d_shmem_req) {
  3489. conv2d_BS_CRS = 8;
  3490. if (use_collectives) {
  3491. conv2d_BS_CRS = std::min(device->subgroup_size, conv2d_BS_CRS);
  3492. }
  3493. }
  3494. std::array<uint32_t, 3> wg_denoms = { conv2d_BS_K, conv2d_BS_NPQ, 1 };
  3495. 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 };
  3496. #define CREATE_CONV(name, type_suffix, spv_suffix) \
  3497. for (auto &c : device->pipeline_##name##type_suffix[s]) { \
  3498. const vk_conv2d_pipeline_state &state = c.first; \
  3499. std::vector<uint32_t> spec_constants_cpy = spec_constants; \
  3500. spec_constants_cpy.push_back(state.s0); \
  3501. spec_constants_cpy.push_back(state.s1); \
  3502. spec_constants_cpy.push_back(state.p0); \
  3503. spec_constants_cpy.push_back(state.p1); \
  3504. spec_constants_cpy.push_back(state.d0); \
  3505. spec_constants_cpy.push_back(state.d1); \
  3506. spec_constants_cpy.push_back(state.KW); \
  3507. spec_constants_cpy.push_back(state.KH); \
  3508. ggml_vk_create_pipeline( \
  3509. device, c.second, #name #type_suffix, \
  3510. name##type_suffix##spv_suffix##_len, name##type_suffix##spv_suffix##_data, "main", 3, \
  3511. sizeof(vk_op_##name##_push_constants), wg_denoms, spec_constants_cpy, 1, true, use_collectives); \
  3512. }
  3513. #define CREATE_CONVS(spv_suffix) \
  3514. CREATE_CONV(conv2d, _f32, spv_suffix) \
  3515. CREATE_CONV(conv2d, _f16_f32, spv_suffix) \
  3516. if (device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_conv_transpose_2d_push_constants)) { \
  3517. CREATE_CONV(conv_transpose_2d, _f32, spv_suffix) \
  3518. CREATE_CONV(conv_transpose_2d, _f16_f32, spv_suffix) \
  3519. }
  3520. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3521. if (device->coopmat2) {
  3522. CREATE_CONVS(_cm2)
  3523. } else
  3524. #endif
  3525. if (conv2d_UNROLL) {
  3526. CREATE_CONVS(_unroll)
  3527. } else {
  3528. CREATE_CONVS( )
  3529. }
  3530. #undef CREATE_CONV
  3531. #undef CREATE_CONVS
  3532. }
  3533. 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);
  3534. 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);
  3535. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_whcn_f16_f32, "conv2d_dw_whcn_f16_f32", conv2d_dw_whcn_f16_f32_len, conv2d_dw_whcn_f16_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3536. ggml_vk_create_pipeline(device, device->pipeline_conv2d_dw_cwhn_f16_f32, "conv2d_dw_cwhn_f16_f32", conv2d_dw_cwhn_f16_f32_len, conv2d_dw_cwhn_f16_f32_data, "main", 3, sizeof(vk_op_conv2d_dw_push_constants), {512, 1, 1}, {}, 1);
  3537. for (uint32_t i = 0; i < num_topk_moe_pipelines; ++i) {
  3538. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_EARLY_SOFTMAX], "topk_moe_f32_early_softmax_"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 0, 0}, 1, true, true);
  3539. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_EARLY_SOFTMAX_NORM], "topk_moe_f32_early_softmax_norm"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 1, 0}, 1, true, true);
  3540. ggml_vk_create_pipeline2(device, device->pipeline_topk_moe[i][TOPK_MOE_LATE_SOFTMAX], "topk_moe_f32_late_softmax"+std::to_string(i), topk_moe_f32_len, topk_moe_f32_data, "main", 3, sizeof(vk_op_topk_moe_push_constants), {1, 1, 1}, {device->subgroup_size, 1u<<i, 0, 1}, 1, true, true);
  3541. }
  3542. for (auto &c : compiles) {
  3543. c.wait();
  3544. }
  3545. }
  3546. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch);
  3547. static vk_device ggml_vk_get_device(size_t idx) {
  3548. VK_LOG_DEBUG("ggml_vk_get_device(" << idx << ")");
  3549. if (vk_instance.devices[idx] == nullptr) {
  3550. VK_LOG_DEBUG("Initializing new vk_device");
  3551. vk_device device = std::make_shared<vk_device_struct>();
  3552. vk_instance.devices[idx] = device;
  3553. #ifdef GGML_VULKAN_MEMORY_DEBUG
  3554. device->memory_logger = std::unique_ptr<vk_memory_logger>(new vk_memory_logger());
  3555. #endif
  3556. if (vk_perf_logger_enabled) {
  3557. device->perf_logger = std::unique_ptr<vk_perf_logger>(new vk_perf_logger());
  3558. }
  3559. size_t dev_num = vk_instance.device_indices[idx];
  3560. std::vector<vk::PhysicalDevice> physical_devices = vk_instance.instance.enumeratePhysicalDevices();
  3561. if (dev_num >= physical_devices.size()) {
  3562. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  3563. throw std::runtime_error("Device not found");
  3564. }
  3565. device->physical_device = physical_devices[dev_num];
  3566. const std::vector<vk::ExtensionProperties> ext_props = device->physical_device.enumerateDeviceExtensionProperties();
  3567. device->architecture = get_device_architecture(device->physical_device);
  3568. const char* GGML_VK_PREFER_HOST_MEMORY = getenv("GGML_VK_PREFER_HOST_MEMORY");
  3569. device->prefer_host_memory = GGML_VK_PREFER_HOST_MEMORY != nullptr;
  3570. const char* GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM = getenv("GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM");
  3571. device->disable_host_visible_vidmem = GGML_VK_DISABLE_HOST_VISIBLE_VIDMEM != nullptr;
  3572. const char* GGML_VK_ALLOW_SYSMEM_FALLBACK = getenv("GGML_VK_ALLOW_SYSMEM_FALLBACK");
  3573. device->allow_sysmem_fallback = GGML_VK_ALLOW_SYSMEM_FALLBACK != nullptr;
  3574. const char* GGML_VK_DISABLE_GRAPH_OPTIMIZE = getenv("GGML_VK_DISABLE_GRAPH_OPTIMIZE");
  3575. device->disable_graph_optimize = GGML_VK_DISABLE_GRAPH_OPTIMIZE != nullptr;
  3576. bool fp16_storage = false;
  3577. bool fp16_compute = false;
  3578. bool maintenance4_support = false;
  3579. bool sm_builtins = false;
  3580. bool amd_shader_core_properties2 = false;
  3581. bool pipeline_robustness = false;
  3582. bool coopmat2_support = false;
  3583. bool pipeline_executable_properties_support = false;
  3584. device->coopmat_support = false;
  3585. device->integer_dot_product = false;
  3586. bool bfloat16_support = false;
  3587. for (const auto& properties : ext_props) {
  3588. if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) {
  3589. maintenance4_support = true;
  3590. } else if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  3591. fp16_storage = true;
  3592. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  3593. fp16_compute = true;
  3594. } else if (strcmp("VK_NV_shader_sm_builtins", properties.extensionName) == 0) {
  3595. sm_builtins = true;
  3596. } else if (strcmp("VK_AMD_shader_core_properties2", properties.extensionName) == 0) {
  3597. amd_shader_core_properties2 = true;
  3598. } else if (strcmp("VK_EXT_pipeline_robustness", properties.extensionName) == 0) {
  3599. pipeline_robustness = true;
  3600. } else if (strcmp("VK_EXT_subgroup_size_control", properties.extensionName) == 0) {
  3601. device->subgroup_size_control = true;
  3602. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  3603. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  3604. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  3605. device->coopmat_support = true;
  3606. device->coopmat_m = 0;
  3607. device->coopmat_n = 0;
  3608. device->coopmat_k = 0;
  3609. #endif
  3610. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3611. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  3612. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  3613. coopmat2_support = true;
  3614. #endif
  3615. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  3616. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  3617. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  3618. device->integer_dot_product = true;
  3619. #endif
  3620. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  3621. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  3622. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  3623. bfloat16_support = true;
  3624. #endif
  3625. } else if (strcmp("VK_KHR_pipeline_executable_properties", properties.extensionName) == 0) {
  3626. pipeline_executable_properties_support = true;
  3627. }
  3628. }
  3629. vk::PhysicalDeviceProperties2 props2;
  3630. vk::PhysicalDeviceMaintenance3Properties props3;
  3631. vk::PhysicalDeviceMaintenance4Properties props4;
  3632. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  3633. vk::PhysicalDeviceDriverProperties driver_props;
  3634. vk::PhysicalDeviceShaderSMBuiltinsPropertiesNV sm_props;
  3635. vk::PhysicalDeviceShaderCoreProperties2AMD amd_shader_core_properties2_props;
  3636. vk::PhysicalDeviceVulkan11Properties vk11_props;
  3637. vk::PhysicalDeviceVulkan12Properties vk12_props;
  3638. vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
  3639. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  3640. props2.pNext = &props3;
  3641. props3.pNext = &subgroup_props;
  3642. subgroup_props.pNext = &driver_props;
  3643. driver_props.pNext = &vk11_props;
  3644. vk11_props.pNext = &vk12_props;
  3645. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&vk12_props;
  3646. if (maintenance4_support) {
  3647. last_struct->pNext = (VkBaseOutStructure *)&props4;
  3648. last_struct = (VkBaseOutStructure *)&props4;
  3649. }
  3650. if (sm_builtins) {
  3651. last_struct->pNext = (VkBaseOutStructure *)&sm_props;
  3652. last_struct = (VkBaseOutStructure *)&sm_props;
  3653. }
  3654. if (amd_shader_core_properties2) {
  3655. last_struct->pNext = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3656. last_struct = (VkBaseOutStructure *)&amd_shader_core_properties2_props;
  3657. }
  3658. if (device->subgroup_size_control) {
  3659. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_props;
  3660. last_struct = (VkBaseOutStructure *)&subgroup_size_control_props;
  3661. }
  3662. #if defined(VK_NV_cooperative_matrix2)
  3663. vk::PhysicalDeviceCooperativeMatrix2PropertiesNV coopmat2_props;
  3664. if (coopmat2_support) {
  3665. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_props;
  3666. last_struct = (VkBaseOutStructure *)&coopmat2_props;
  3667. }
  3668. #endif
  3669. if (device->integer_dot_product) {
  3670. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3671. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  3672. }
  3673. device->physical_device.getProperties2(&props2);
  3674. device->properties = props2.properties;
  3675. device->vendor_id = device->properties.vendorID;
  3676. device->driver_id = driver_props.driverID;
  3677. const char* GGML_VK_FORCE_MAX_ALLOCATION_SIZE = getenv("GGML_VK_FORCE_MAX_ALLOCATION_SIZE");
  3678. if (GGML_VK_FORCE_MAX_ALLOCATION_SIZE != nullptr) {
  3679. device->max_memory_allocation_size = std::stoull(GGML_VK_FORCE_MAX_ALLOCATION_SIZE);
  3680. } else if (maintenance4_support) {
  3681. device->max_memory_allocation_size = std::min(props3.maxMemoryAllocationSize, props4.maxBufferSize);
  3682. } else {
  3683. device->max_memory_allocation_size = props3.maxMemoryAllocationSize;
  3684. }
  3685. const char* GGML_VK_FORCE_MAX_BUFFER_SIZE = getenv("GGML_VK_FORCE_MAX_BUFFER_SIZE");
  3686. if (GGML_VK_FORCE_MAX_BUFFER_SIZE != nullptr) {
  3687. device->max_buffer_size = std::stoull(GGML_VK_FORCE_MAX_BUFFER_SIZE);
  3688. } else if (maintenance4_support) {
  3689. device->max_buffer_size = props4.maxBufferSize;
  3690. } else {
  3691. device->max_buffer_size = device->max_memory_allocation_size;
  3692. }
  3693. const char* GGML_VK_SUBALLOCATION_BLOCK_SIZE = getenv("GGML_VK_SUBALLOCATION_BLOCK_SIZE");
  3694. if (GGML_VK_SUBALLOCATION_BLOCK_SIZE != nullptr) {
  3695. device->suballocation_block_size = std::stoull(GGML_VK_SUBALLOCATION_BLOCK_SIZE);
  3696. } else {
  3697. // Limit batching of allocations to 1GB by default to avoid fragmentation issues
  3698. device->suballocation_block_size = 1024*1024*1024;
  3699. }
  3700. device->suballocation_block_size = std::min(device->suballocation_block_size, device->max_memory_allocation_size);
  3701. device->subgroup_size = subgroup_props.subgroupSize;
  3702. device->uma = device->properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  3703. if (sm_builtins) {
  3704. device->shader_core_count = sm_props.shaderSMCount;
  3705. } else if (amd_shader_core_properties2) {
  3706. device->shader_core_count = amd_shader_core_properties2_props.activeComputeUnitCount;
  3707. } else {
  3708. device->shader_core_count = 0;
  3709. }
  3710. device->float_controls_rte_fp16 = vk12_props.shaderRoundingModeRTEFloat16;
  3711. device->subgroup_arithmetic = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3712. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eArithmetic);
  3713. #ifdef __APPLE__
  3714. // Workaround for subgroup arithmetic failing on MoltenVK with AMD GPUs (issue 15846)
  3715. if (device->vendor_id == VK_VENDOR_ID_AMD) {
  3716. device->subgroup_arithmetic = false;
  3717. }
  3718. #endif
  3719. device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3720. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle);
  3721. device->subgroup_clustered = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3722. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eClustered);
  3723. device->subgroup_ballot = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3724. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eBallot);
  3725. device->subgroup_vote = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) &&
  3726. (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eVote);
  3727. const bool force_disable_f16 = getenv("GGML_VK_DISABLE_F16") != nullptr;
  3728. device->fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  3729. if (!ggml_vk_khr_cooperative_matrix_support(device->properties, driver_props, device->architecture)) {
  3730. device->coopmat_support = false;
  3731. }
  3732. device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated;
  3733. device->max_workgroup_size_log2 = uint32_t(log2f(float(device->properties.limits.maxComputeWorkGroupInvocations)));
  3734. std::vector<vk::QueueFamilyProperties> queue_family_props = device->physical_device.getQueueFamilyProperties();
  3735. // Try to find a non-graphics compute queue and transfer-focused queues
  3736. const uint32_t compute_queue_family_index = ggml_vk_find_queue_family_index(queue_family_props, vk::QueueFlagBits::eCompute, vk::QueueFlagBits::eGraphics, -1, 1);
  3737. 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);
  3738. const float priorities[] = { 1.0f, 1.0f };
  3739. device->single_queue = compute_queue_family_index == transfer_queue_family_index && queue_family_props[compute_queue_family_index].queueCount == 1;
  3740. std::vector<vk::DeviceQueueCreateInfo> device_queue_create_infos;
  3741. if (compute_queue_family_index != transfer_queue_family_index) {
  3742. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3743. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), transfer_queue_family_index, 1, priorities + 1});
  3744. } else if(!device->single_queue) {
  3745. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 2, priorities});
  3746. } else {
  3747. device_queue_create_infos.push_back({vk::DeviceQueueCreateFlags(), compute_queue_family_index, 1, priorities});
  3748. }
  3749. vk::DeviceCreateInfo device_create_info;
  3750. std::vector<const char *> device_extensions;
  3751. vk::PhysicalDeviceFeatures device_features = device->physical_device.getFeatures();
  3752. VkPhysicalDeviceFeatures2 device_features2;
  3753. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  3754. device_features2.pNext = nullptr;
  3755. device_features2.features = (VkPhysicalDeviceFeatures)device_features;
  3756. VkPhysicalDeviceVulkan11Features vk11_features;
  3757. vk11_features.pNext = nullptr;
  3758. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  3759. device_features2.pNext = &vk11_features;
  3760. VkPhysicalDeviceVulkan12Features vk12_features;
  3761. vk12_features.pNext = nullptr;
  3762. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  3763. vk11_features.pNext = &vk12_features;
  3764. last_struct = (VkBaseOutStructure *)&vk12_features;
  3765. VkPhysicalDevicePipelineRobustnessFeaturesEXT pl_robustness_features;
  3766. pl_robustness_features.pNext = nullptr;
  3767. pl_robustness_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_ROBUSTNESS_FEATURES_EXT;
  3768. pl_robustness_features.pipelineRobustness = VK_FALSE;
  3769. if (pipeline_robustness) {
  3770. last_struct->pNext = (VkBaseOutStructure *)&pl_robustness_features;
  3771. last_struct = (VkBaseOutStructure *)&pl_robustness_features;
  3772. device_extensions.push_back("VK_EXT_pipeline_robustness");
  3773. }
  3774. VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroup_size_control_features;
  3775. subgroup_size_control_features.pNext = nullptr;
  3776. subgroup_size_control_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
  3777. subgroup_size_control_features.computeFullSubgroups = false;
  3778. subgroup_size_control_features.subgroupSizeControl = false;
  3779. if (device->subgroup_size_control) {
  3780. last_struct->pNext = (VkBaseOutStructure *)&subgroup_size_control_features;
  3781. last_struct = (VkBaseOutStructure *)&subgroup_size_control_features;
  3782. }
  3783. #if defined(VK_KHR_cooperative_matrix)
  3784. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  3785. coopmat_features.pNext = nullptr;
  3786. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  3787. coopmat_features.cooperativeMatrix = VK_FALSE;
  3788. if (device->coopmat_support) {
  3789. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  3790. last_struct = (VkBaseOutStructure *)&coopmat_features;
  3791. }
  3792. #endif
  3793. #if defined(VK_NV_cooperative_matrix2)
  3794. VkPhysicalDeviceCooperativeMatrix2FeaturesNV coopmat2_features {};
  3795. coopmat2_features.pNext = nullptr;
  3796. coopmat2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_2_FEATURES_NV;
  3797. if (coopmat2_support) {
  3798. last_struct->pNext = (VkBaseOutStructure *)&coopmat2_features;
  3799. last_struct = (VkBaseOutStructure *)&coopmat2_features;
  3800. device_extensions.push_back("VK_NV_cooperative_matrix2");
  3801. }
  3802. #endif
  3803. #if defined(VK_KHR_shader_bfloat16)
  3804. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  3805. bfloat16_features.pNext = nullptr;
  3806. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  3807. if (bfloat16_support) {
  3808. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  3809. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  3810. device_extensions.push_back("VK_KHR_shader_bfloat16");
  3811. }
  3812. #endif
  3813. VkPhysicalDeviceMaintenance4Features maint4_features {};
  3814. maint4_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_FEATURES;
  3815. if (maintenance4_support) {
  3816. last_struct->pNext = (VkBaseOutStructure *)&maint4_features;
  3817. last_struct = (VkBaseOutStructure *)&maint4_features;
  3818. device_extensions.push_back("VK_KHR_maintenance4");
  3819. }
  3820. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  3821. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  3822. if (device->integer_dot_product) {
  3823. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3824. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  3825. device_extensions.push_back("VK_KHR_shader_integer_dot_product");
  3826. }
  3827. VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pep_features {};
  3828. pep_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR;
  3829. if (pipeline_executable_properties_support) {
  3830. last_struct->pNext = (VkBaseOutStructure *)&pep_features;
  3831. last_struct = (VkBaseOutStructure *)&pep_features;
  3832. device_extensions.push_back("VK_KHR_pipeline_executable_properties");
  3833. }
  3834. vkGetPhysicalDeviceFeatures2(device->physical_device, &device_features2);
  3835. device->pipeline_executable_properties_support = pipeline_executable_properties_support;
  3836. device->fp16 = device->fp16 && vk12_features.shaderFloat16;
  3837. #if defined(VK_KHR_shader_bfloat16)
  3838. device->bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  3839. #else
  3840. device->bf16 = false;
  3841. #endif
  3842. device->pipeline_robustness = pl_robustness_features.pipelineRobustness;
  3843. device->multi_add = vk12_props.shaderRoundingModeRTEFloat16 &&
  3844. device->properties.limits.maxPushConstantsSize >= sizeof(vk_op_multi_add_push_constants) &&
  3845. getenv("GGML_VK_DISABLE_MULTI_ADD") == nullptr;
  3846. device->shader_int64 = device_features2.features.shaderInt64;
  3847. device->buffer_device_address = vk12_features.bufferDeviceAddress;
  3848. device->vulkan_memory_model = vk12_features.vulkanMemoryModel;
  3849. if (device->subgroup_size_control) {
  3850. device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize;
  3851. device->subgroup_max_size = subgroup_size_control_props.maxSubgroupSize;
  3852. device_extensions.push_back("VK_EXT_subgroup_size_control");
  3853. }
  3854. device->subgroup_size_control = device->subgroup_size_control &&
  3855. (subgroup_size_control_props.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute) &&
  3856. subgroup_size_control_features.subgroupSizeControl;
  3857. device->subgroup_require_full_support = subgroup_size_control_features.computeFullSubgroups;
  3858. #if defined(VK_KHR_cooperative_matrix)
  3859. device->coopmat_support = device->coopmat_support && coopmat_features.cooperativeMatrix;
  3860. // coopmat1 fa shader currently assumes 32 invocations per subgroup
  3861. device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support &&
  3862. device->subgroup_size_control && device->subgroup_min_size <= 32 &&
  3863. device->subgroup_max_size >= 32;
  3864. #endif
  3865. if (coopmat2_support) {
  3866. #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  3867. if (coopmat2_features.cooperativeMatrixWorkgroupScope &&
  3868. coopmat2_features.cooperativeMatrixFlexibleDimensions &&
  3869. coopmat2_features.cooperativeMatrixReductions &&
  3870. coopmat2_features.cooperativeMatrixConversions &&
  3871. coopmat2_features.cooperativeMatrixPerElementOperations &&
  3872. coopmat2_features.cooperativeMatrixTensorAddressing &&
  3873. coopmat2_features.cooperativeMatrixBlockLoads &&
  3874. vk12_features.bufferDeviceAddress) {
  3875. std::vector<VkCooperativeMatrixFlexibleDimensionsPropertiesNV> flexible_dimensions;
  3876. uint32_t count = 0;
  3877. PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV
  3878. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV =
  3879. (PFN_vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV)
  3880. vk_instance.instance.getProcAddr("vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV");
  3881. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, nullptr);
  3882. VkCooperativeMatrixFlexibleDimensionsPropertiesNV empty_prop {};
  3883. empty_prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_FLEXIBLE_DIMENSIONS_PROPERTIES_NV;
  3884. flexible_dimensions.resize(count, empty_prop);
  3885. _vkGetPhysicalDeviceCooperativeMatrixFlexibleDimensionsPropertiesNV(device->physical_device, &count, flexible_dimensions.data());
  3886. bool found_fp16_128 = false,
  3887. found_fp16_256 = false,
  3888. found_fp32_128 = false,
  3889. found_fp32_256 = false;
  3890. // need to support fp16*fp16 with fp16/fp32 accumulator, for workgroupsize 128
  3891. // with 32x16x16 and 256 with 32x32x16.
  3892. for (auto &prop : flexible_dimensions) {
  3893. if (prop.saturatingAccumulation == VK_FALSE &&
  3894. prop.scope == VK_SCOPE_WORKGROUP_KHR &&
  3895. prop.AType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3896. prop.BType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3897. if (prop.workgroupInvocations == 128 &&
  3898. prop.MGranularity <= 32 &&
  3899. prop.NGranularity <= 16 &&
  3900. prop.KGranularity <= 16) {
  3901. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3902. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3903. found_fp16_128 = true;
  3904. }
  3905. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3906. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3907. found_fp32_128 = true;
  3908. }
  3909. }
  3910. if (prop.workgroupInvocations == 256 &&
  3911. prop.MGranularity <= 32 &&
  3912. prop.NGranularity <= 32 &&
  3913. prop.KGranularity <= 16) {
  3914. if (prop.CType == VK_COMPONENT_TYPE_FLOAT16_KHR &&
  3915. prop.ResultType == VK_COMPONENT_TYPE_FLOAT16_KHR) {
  3916. found_fp16_256 = true;
  3917. }
  3918. if (prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  3919. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR) {
  3920. found_fp32_256 = true;
  3921. }
  3922. }
  3923. }
  3924. }
  3925. if (found_fp16_128 && found_fp16_256 &&
  3926. found_fp32_128 && found_fp32_256 &&
  3927. coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) {
  3928. device->coopmat2 = true;
  3929. }
  3930. }
  3931. #endif
  3932. }
  3933. if (!vk11_features.storageBuffer16BitAccess) {
  3934. std::cerr << "ggml_vulkan: device " << GGML_VK_NAME << idx << " does not support 16-bit storage." << std::endl;
  3935. throw std::runtime_error("Unsupported device");
  3936. }
  3937. device_extensions.push_back("VK_KHR_16bit_storage");
  3938. #ifdef GGML_VULKAN_VALIDATE
  3939. device_extensions.push_back("VK_KHR_shader_non_semantic_info");
  3940. #endif
  3941. if (device->fp16) {
  3942. device_extensions.push_back("VK_KHR_shader_float16_int8");
  3943. }
  3944. #if defined(VK_KHR_cooperative_matrix)
  3945. if (device->coopmat_support) {
  3946. // Query supported shapes
  3947. std::vector<VkCooperativeMatrixPropertiesKHR> cm_props;
  3948. PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR =
  3949. (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR)vkGetInstanceProcAddr(vk_instance.instance, "vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR");
  3950. uint32_t cm_props_num;
  3951. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, nullptr);
  3952. cm_props.resize(cm_props_num);
  3953. for (auto& prop : cm_props) {
  3954. prop.sType = VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_KHR;
  3955. }
  3956. pfn_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(device->physical_device, &cm_props_num, cm_props.data());
  3957. VK_LOG_DEBUG("ggml_vulkan: Cooperative Matrix Shapes: " << cm_props.size());
  3958. for (auto& prop : cm_props) {
  3959. 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));
  3960. if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eFloat16 &&
  3961. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eFloat16 &&
  3962. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  3963. ) {
  3964. if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat32 &&
  3965. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat32) {
  3966. // coopmat sizes not set yet
  3967. if (device->coopmat_m == 0) {
  3968. device->coopmat_acc_f32_support = true;
  3969. device->coopmat_m = prop.MSize;
  3970. device->coopmat_n = prop.NSize;
  3971. device->coopmat_k = prop.KSize;
  3972. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3973. // Only enable if shape is identical
  3974. device->coopmat_acc_f32_support = true;
  3975. }
  3976. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3977. device->coopmat_support_16x16x16_f32acc = true;
  3978. }
  3979. } else if ((vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eFloat16 &&
  3980. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eFloat16) {
  3981. // coopmat sizes not set yet
  3982. if (device->coopmat_m == 0) {
  3983. device->coopmat_acc_f16_support = true;
  3984. device->coopmat_m = prop.MSize;
  3985. device->coopmat_n = prop.NSize;
  3986. device->coopmat_k = prop.KSize;
  3987. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  3988. // Only enable if shape is identical
  3989. device->coopmat_acc_f16_support = true;
  3990. }
  3991. if (prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16) {
  3992. device->coopmat_support_16x16x16_f16acc = true;
  3993. }
  3994. }
  3995. } else if ((vk::ComponentTypeKHR)prop.AType == vk::ComponentTypeKHR::eSint8 &&
  3996. (vk::ComponentTypeKHR)prop.BType == vk::ComponentTypeKHR::eSint8 &&
  3997. (vk::ComponentTypeKHR)prop.CType == vk::ComponentTypeKHR::eSint32 &&
  3998. (vk::ComponentTypeKHR)prop.ResultType == vk::ComponentTypeKHR::eSint32 &&
  3999. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup &&
  4000. device->coopmat_int_m == 0
  4001. ) {
  4002. device->coopmat_int_support = true;
  4003. device->coopmat_int_m = prop.MSize;
  4004. device->coopmat_int_n = prop.NSize;
  4005. device->coopmat_int_k = prop.KSize;
  4006. }
  4007. #if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4008. if (prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  4009. prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR &&
  4010. prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4011. prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
  4012. (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup
  4013. ) {
  4014. // coopmat sizes not set yet
  4015. if (device->coopmat_m == 0) {
  4016. device->coopmat_bf16_support = true;
  4017. device->coopmat_m = prop.MSize;
  4018. device->coopmat_n = prop.NSize;
  4019. device->coopmat_k = prop.KSize;
  4020. } else if (device->coopmat_m == prop.MSize && device->coopmat_n == prop.NSize && device->coopmat_k == prop.KSize) {
  4021. // Only enable if shape is identical
  4022. device->coopmat_bf16_support = true;
  4023. }
  4024. }
  4025. #endif
  4026. }
  4027. if (device->coopmat_m == 0 || !device->coopmat_acc_f32_support) {
  4028. // No suitable matmul mode found
  4029. GGML_LOG_DEBUG("ggml_vulkan: WARNING: No suitable matrix core mode found. Disabling matrix cores.\n");
  4030. device->coopmat_support = false;
  4031. }
  4032. if (getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4033. device->coopmat_bf16_support = false;
  4034. }
  4035. }
  4036. if (device->coopmat_support) {
  4037. device_extensions.push_back("VK_KHR_cooperative_matrix");
  4038. }
  4039. #if defined(VK_KHR_shader_bfloat16)
  4040. if (device->coopmat_bf16_support) {
  4041. device_extensions.push_back("VK_KHR_shader_bfloat16");
  4042. }
  4043. #endif
  4044. #endif
  4045. device->name = GGML_VK_NAME + std::to_string(idx);
  4046. device_create_info = {
  4047. vk::DeviceCreateFlags(),
  4048. device_queue_create_infos,
  4049. {},
  4050. device_extensions
  4051. };
  4052. device_create_info.setPNext(&device_features2);
  4053. device->device = device->physical_device.createDevice(device_create_info);
  4054. // Queues
  4055. ggml_vk_create_queue(device, device->compute_queue, compute_queue_family_index, 0, { vk::PipelineStageFlagBits::eComputeShader | vk::PipelineStageFlagBits::eTransfer }, false);
  4056. // Shaders
  4057. // Disable matmul tile sizes early if performance low or not supported
  4058. for (uint32_t i = 0; i < GGML_TYPE_COUNT; ++i) {
  4059. switch (device->vendor_id) {
  4060. #ifndef GGML_VULKAN_RUN_TESTS
  4061. case VK_VENDOR_ID_AMD:
  4062. case VK_VENDOR_ID_INTEL:
  4063. device->mul_mat_l[i] = false;
  4064. device->mul_mat_m[i] = true;
  4065. device->mul_mat_s[i] = true;
  4066. device->mul_mat_id_l[i] = false;
  4067. device->mul_mat_id_m[i] = true;
  4068. device->mul_mat_id_s[i] = true;
  4069. break;
  4070. case VK_VENDOR_ID_APPLE:
  4071. device->mul_mat_l[i] = false;
  4072. device->mul_mat_m[i] = true;
  4073. device->mul_mat_s[i] = false;
  4074. device->mul_mat_id_l[i] = false;
  4075. device->mul_mat_id_m[i] = true;
  4076. device->mul_mat_id_s[i] = false;
  4077. break;
  4078. #endif
  4079. default:
  4080. device->mul_mat_l[i] = true;
  4081. device->mul_mat_m[i] = true;
  4082. device->mul_mat_s[i] = true;
  4083. device->mul_mat_id_l[i] = true;
  4084. device->mul_mat_id_m[i] = true;
  4085. device->mul_mat_id_s[i] = true;
  4086. break;
  4087. }
  4088. }
  4089. std::vector<vk::DescriptorSetLayoutBinding> dsl_binding;
  4090. std::vector<vk::DescriptorBindingFlags> dsl_binding_flags;
  4091. for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) {
  4092. dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute});
  4093. dsl_binding_flags.push_back({});
  4094. }
  4095. vk::DescriptorSetLayoutBindingFlagsCreateInfo dslbfci = { dsl_binding_flags };
  4096. vk::DescriptorSetLayoutCreateInfo descriptor_set_layout_create_info(
  4097. {},
  4098. dsl_binding);
  4099. descriptor_set_layout_create_info.setPNext(&dslbfci);
  4100. device->dsl = device->device.createDescriptorSetLayout(descriptor_set_layout_create_info);
  4101. ggml_vk_load_shaders(device);
  4102. if (!device->single_queue) {
  4103. const uint32_t transfer_queue_index = compute_queue_family_index == transfer_queue_family_index ? 1 : 0;
  4104. ggml_vk_create_queue(device, device->transfer_queue, transfer_queue_family_index, transfer_queue_index, { vk::PipelineStageFlagBits::eTransfer }, true);
  4105. } else {
  4106. // TODO: Use pointer or reference to avoid copy
  4107. device->transfer_queue.copyFrom(device->compute_queue);
  4108. device->transfer_queue.cmd_pool.init(device, &device->transfer_queue);
  4109. }
  4110. device->buffer_type = {
  4111. /* .iface = */ ggml_backend_vk_buffer_type_interface,
  4112. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx),
  4113. /* .context = */ new ggml_backend_vk_buffer_type_context{ device->name, device },
  4114. };
  4115. device->fence = device->device.createFence({});
  4116. device->idx = idx;
  4117. device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr;
  4118. device->add_rms_fusion = !device->disable_fusion &&
  4119. device->subgroup_arithmetic &&
  4120. device->vendor_id != VK_VENDOR_ID_INTEL;
  4121. device->partials_binding_alignment =
  4122. std::max(4u, (uint32_t)device->properties.limits.minStorageBufferOffsetAlignment);
  4123. device->mmvq_mode = 0;
  4124. if (getenv("GGML_VK_DISABLE_MMVQ")) {
  4125. device->mmvq_mode = -1;
  4126. } else if (getenv("GGML_VK_FORCE_MMVQ")) {
  4127. device->mmvq_mode = 1;
  4128. }
  4129. return device;
  4130. }
  4131. return vk_instance.devices[idx];
  4132. }
  4133. static void ggml_vk_print_gpu_info(size_t idx) {
  4134. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4135. size_t dev_num = vk_instance.device_indices[idx];
  4136. VK_LOG_DEBUG("ggml_vk_print_gpu_info(" << dev_num << ")");
  4137. GGML_ASSERT(vk_instance_initialized);
  4138. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4139. if (dev_num >= devices.size()) {
  4140. std::cerr << "ggml_vulkan: Device with index " << dev_num << " does not exist." << std::endl;
  4141. throw std::runtime_error("Device not found");
  4142. }
  4143. vk::PhysicalDevice physical_device = devices[dev_num];
  4144. std::vector<vk::ExtensionProperties> ext_props = physical_device.enumerateDeviceExtensionProperties();
  4145. bool fp16_storage = false;
  4146. bool fp16_compute = false;
  4147. bool coopmat_support = false;
  4148. bool coopmat2_support = false;
  4149. bool integer_dot_product = false;
  4150. bool bfloat16_support = false;
  4151. for (auto properties : ext_props) {
  4152. if (strcmp("VK_KHR_16bit_storage", properties.extensionName) == 0) {
  4153. fp16_storage = true;
  4154. } else if (strcmp("VK_KHR_shader_float16_int8", properties.extensionName) == 0) {
  4155. fp16_compute = true;
  4156. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4157. } else if (strcmp("VK_KHR_cooperative_matrix", properties.extensionName) == 0 &&
  4158. !getenv("GGML_VK_DISABLE_COOPMAT")) {
  4159. coopmat_support = true;
  4160. #endif
  4161. #if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
  4162. } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 &&
  4163. !getenv("GGML_VK_DISABLE_COOPMAT2")) {
  4164. coopmat2_support = true;
  4165. #endif
  4166. #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
  4167. } else if (strcmp("VK_KHR_shader_integer_dot_product", properties.extensionName) == 0 &&
  4168. !getenv("GGML_VK_DISABLE_INTEGER_DOT_PRODUCT")) {
  4169. integer_dot_product = true;
  4170. #endif
  4171. #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
  4172. } else if (strcmp("VK_KHR_shader_bfloat16", properties.extensionName) == 0 &&
  4173. !getenv("GGML_VK_DISABLE_BFLOAT16")) {
  4174. bfloat16_support = true;
  4175. #endif
  4176. }
  4177. }
  4178. const vk_device_architecture device_architecture = get_device_architecture(physical_device);
  4179. const char* GGML_VK_DISABLE_F16 = getenv("GGML_VK_DISABLE_F16");
  4180. bool force_disable_f16 = GGML_VK_DISABLE_F16 != nullptr;
  4181. bool fp16 = !force_disable_f16 && fp16_storage && fp16_compute;
  4182. vk::PhysicalDeviceProperties2 props2;
  4183. vk::PhysicalDeviceMaintenance3Properties props3;
  4184. vk::PhysicalDeviceSubgroupProperties subgroup_props;
  4185. vk::PhysicalDeviceDriverProperties driver_props;
  4186. vk::PhysicalDeviceShaderIntegerDotProductPropertiesKHR shader_integer_dot_product_props;
  4187. props2.pNext = &props3;
  4188. props3.pNext = &subgroup_props;
  4189. subgroup_props.pNext = &driver_props;
  4190. // Pointer to the last chain element
  4191. VkBaseOutStructure * last_struct = (VkBaseOutStructure *)&driver_props;
  4192. if (integer_dot_product) {
  4193. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4194. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_props;
  4195. }
  4196. physical_device.getProperties2(&props2);
  4197. VkPhysicalDeviceFeatures2 device_features2;
  4198. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  4199. device_features2.pNext = nullptr;
  4200. VkPhysicalDeviceVulkan11Features vk11_features;
  4201. vk11_features.pNext = nullptr;
  4202. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  4203. device_features2.pNext = &vk11_features;
  4204. VkPhysicalDeviceVulkan12Features vk12_features;
  4205. vk12_features.pNext = nullptr;
  4206. vk12_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
  4207. vk11_features.pNext = &vk12_features;
  4208. // Pointer to the last chain element
  4209. last_struct = (VkBaseOutStructure *)&vk12_features;
  4210. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4211. VkPhysicalDeviceCooperativeMatrixFeaturesKHR coopmat_features;
  4212. coopmat_features.pNext = nullptr;
  4213. coopmat_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_FEATURES_KHR;
  4214. coopmat_features.cooperativeMatrix = VK_FALSE;
  4215. if (coopmat_support) {
  4216. last_struct->pNext = (VkBaseOutStructure *)&coopmat_features;
  4217. last_struct = (VkBaseOutStructure *)&coopmat_features;
  4218. }
  4219. #endif
  4220. VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {};
  4221. shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR;
  4222. if (integer_dot_product) {
  4223. last_struct->pNext = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4224. last_struct = (VkBaseOutStructure *)&shader_integer_dot_product_features;
  4225. }
  4226. #if defined(VK_KHR_shader_bfloat16)
  4227. VkPhysicalDeviceShaderBfloat16FeaturesKHR bfloat16_features {};
  4228. bfloat16_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_BFLOAT16_FEATURES_KHR;
  4229. if (bfloat16_support) {
  4230. last_struct->pNext = (VkBaseOutStructure *)&bfloat16_features;
  4231. last_struct = (VkBaseOutStructure *)&bfloat16_features;
  4232. }
  4233. #endif
  4234. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2);
  4235. fp16 = fp16 && vk12_features.shaderFloat16;
  4236. #if defined(VK_KHR_shader_bfloat16)
  4237. bool bf16 = bfloat16_support && bfloat16_features.shaderBFloat16Type;
  4238. #else
  4239. bool bf16 = false;
  4240. #endif
  4241. uint32_t default_subgroup_size = get_subgroup_size("", device_architecture);
  4242. const size_t subgroup_size = (default_subgroup_size != 0) ? default_subgroup_size : subgroup_props.subgroupSize;
  4243. const bool uma = props2.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  4244. integer_dot_product = integer_dot_product
  4245. && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated
  4246. && shader_integer_dot_product_features.shaderIntegerDotProduct;
  4247. coopmat_support = coopmat_support
  4248. #if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
  4249. && coopmat_features.cooperativeMatrix
  4250. #endif
  4251. && ggml_vk_khr_cooperative_matrix_support(props2.properties, driver_props, device_architecture);
  4252. std::string matrix_cores = coopmat2_support ? "NV_coopmat2" : coopmat_support ? "KHR_coopmat" : "none";
  4253. std::string device_name = props2.properties.deviceName.data();
  4254. 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",
  4255. idx, device_name.c_str(), driver_props.driverName.data(), uma, fp16, bf16, subgroup_size,
  4256. props2.properties.limits.maxComputeSharedMemorySize, integer_dot_product, matrix_cores.c_str());
  4257. if (props2.properties.deviceType == vk::PhysicalDeviceType::eCpu) {
  4258. GGML_LOG_DEBUG("ggml_vulkan: Warning: Device type is CPU. This is probably not the device you want.\n");
  4259. }
  4260. }
  4261. static bool ggml_vk_instance_validation_ext_available();
  4262. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions);
  4263. static bool ggml_vk_instance_debug_utils_ext_available(const std::vector<vk::ExtensionProperties> & instance_extensions);
  4264. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev);
  4265. static DispatchLoaderDynamic ggml_vk_default_dispatcher_instance;
  4266. DispatchLoaderDynamic & ggml_vk_default_dispatcher() {
  4267. return ggml_vk_default_dispatcher_instance;
  4268. }
  4269. static void ggml_vk_instance_init() {
  4270. if (vk_instance_initialized) {
  4271. return;
  4272. }
  4273. VK_LOG_DEBUG("ggml_vk_instance_init()");
  4274. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4275. ggml_vk_default_dispatcher_instance.init(vkGetInstanceProcAddr);
  4276. uint32_t api_version = vk::enumerateInstanceVersion();
  4277. if (api_version < VK_API_VERSION_1_2) {
  4278. std::cerr << "ggml_vulkan: Error: Vulkan 1.2 required." << std::endl;
  4279. throw vk::SystemError(vk::Result::eErrorFeatureNotPresent, "Vulkan 1.2 required");
  4280. }
  4281. vk::ApplicationInfo app_info{ "ggml-vulkan", 1, nullptr, 0, api_version };
  4282. const std::vector<vk::ExtensionProperties> instance_extensions = vk::enumerateInstanceExtensionProperties();
  4283. const bool validation_ext = ggml_vk_instance_validation_ext_available();
  4284. #ifdef __APPLE__
  4285. const bool portability_enumeration_ext = ggml_vk_instance_portability_enumeration_ext_available(instance_extensions);
  4286. #endif
  4287. const bool debug_utils_ext = ggml_vk_instance_debug_utils_ext_available(instance_extensions) && getenv("GGML_VK_DEBUG_MARKERS") != nullptr;
  4288. std::vector<const char*> layers;
  4289. if (validation_ext) {
  4290. layers.push_back("VK_LAYER_KHRONOS_validation");
  4291. }
  4292. std::vector<const char*> extensions;
  4293. if (validation_ext) {
  4294. extensions.push_back("VK_EXT_validation_features");
  4295. }
  4296. #ifdef __APPLE__
  4297. if (portability_enumeration_ext) {
  4298. extensions.push_back("VK_KHR_portability_enumeration");
  4299. }
  4300. #endif
  4301. if (debug_utils_ext) {
  4302. extensions.push_back("VK_EXT_debug_utils");
  4303. }
  4304. vk::InstanceCreateInfo instance_create_info(vk::InstanceCreateFlags{}, &app_info, layers, extensions);
  4305. #ifdef __APPLE__
  4306. if (portability_enumeration_ext) {
  4307. instance_create_info.flags |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
  4308. }
  4309. #endif
  4310. std::vector<vk::ValidationFeatureEnableEXT> features_enable;
  4311. vk::ValidationFeaturesEXT validation_features;
  4312. if (validation_ext) {
  4313. features_enable = { vk::ValidationFeatureEnableEXT::eBestPractices };
  4314. validation_features = {
  4315. features_enable,
  4316. {},
  4317. };
  4318. validation_features.setPNext(nullptr);
  4319. instance_create_info.setPNext(&validation_features);
  4320. GGML_LOG_DEBUG("ggml_vulkan: Validation layers enabled\n");
  4321. }
  4322. vk_instance.instance = vk::createInstance(instance_create_info);
  4323. vk_instance_initialized = true;
  4324. if (debug_utils_ext) {
  4325. vk_instance.debug_utils_support = true;
  4326. vk_instance.pfn_vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkSetDebugUtilsObjectNameEXT");
  4327. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueBeginDebugUtilsLabelEXT");
  4328. vk_instance.pfn_vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkQueueEndDebugUtilsLabelEXT");
  4329. vk_instance.pfn_vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdBeginDebugUtilsLabelEXT");
  4330. vk_instance.pfn_vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdEndDebugUtilsLabelEXT");
  4331. vk_instance.pfn_vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT) vkGetInstanceProcAddr(vk_instance.instance, "vkCmdInsertDebugUtilsLabelEXT");
  4332. }
  4333. vk_perf_logger_enabled = getenv("GGML_VK_PERF_LOGGER") != nullptr;
  4334. // See https://github.com/KhronosGroup/Vulkan-Hpp?tab=readme-ov-file#extensions--per-device-function-pointers-
  4335. VULKAN_HPP_DEFAULT_DISPATCHER.init(vk_instance.instance);
  4336. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  4337. // Emulate behavior of CUDA_VISIBLE_DEVICES for Vulkan
  4338. char * devices_env = getenv("GGML_VK_VISIBLE_DEVICES");
  4339. if (devices_env != nullptr) {
  4340. size_t num_available_devices = devices.size();
  4341. std::string devices(devices_env);
  4342. std::replace(devices.begin(), devices.end(), ',', ' ');
  4343. std::stringstream ss(devices);
  4344. size_t tmp;
  4345. while (ss >> tmp) {
  4346. if(tmp >= num_available_devices) {
  4347. std::cerr << "ggml_vulkan: Invalid device index " << tmp << " in GGML_VK_VISIBLE_DEVICES." << std::endl;
  4348. throw std::runtime_error("Invalid Vulkan device index");
  4349. }
  4350. vk_instance.device_indices.push_back(tmp);
  4351. }
  4352. } else {
  4353. // If no vulkan devices are found, return early
  4354. if (devices.empty()) {
  4355. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4356. return;
  4357. }
  4358. // Default to using all dedicated GPUs
  4359. for (size_t i = 0; i < devices.size(); i++) {
  4360. vk::PhysicalDeviceProperties2 new_props;
  4361. vk::PhysicalDeviceDriverProperties new_driver;
  4362. vk::PhysicalDeviceIDProperties new_id;
  4363. new_props.pNext = &new_driver;
  4364. new_driver.pNext = &new_id;
  4365. devices[i].getProperties2(&new_props);
  4366. if ((new_props.properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu || new_props.properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu) && ggml_vk_device_is_supported(devices[i])) {
  4367. // Check if there are two physical devices corresponding to the same GPU
  4368. auto old_device = std::find_if(
  4369. vk_instance.device_indices.begin(),
  4370. vk_instance.device_indices.end(),
  4371. [&devices, &new_id](const size_t k){
  4372. vk::PhysicalDeviceProperties2 old_props;
  4373. vk::PhysicalDeviceIDProperties old_id;
  4374. old_props.pNext = &old_id;
  4375. devices[k].getProperties2(&old_props);
  4376. bool equals = std::equal(std::begin(old_id.deviceUUID), std::end(old_id.deviceUUID), std::begin(new_id.deviceUUID));
  4377. equals = equals || (
  4378. old_id.deviceLUIDValid && new_id.deviceLUIDValid &&
  4379. std::equal(std::begin(old_id.deviceLUID), std::end(old_id.deviceLUID), std::begin(new_id.deviceLUID))
  4380. );
  4381. return equals;
  4382. }
  4383. );
  4384. if (old_device == vk_instance.device_indices.end()) {
  4385. vk_instance.device_indices.push_back(i);
  4386. } else {
  4387. // There can be two physical devices corresponding to the same GPU if there are 2 different drivers
  4388. // This can cause error when splitting layers aross the devices, need to keep only 1
  4389. VK_LOG_DEBUG("Device " << i << " and device " << *old_device << " have the same deviceUUID");
  4390. vk::PhysicalDeviceProperties2 old_props;
  4391. vk::PhysicalDeviceDriverProperties old_driver;
  4392. old_props.pNext = &old_driver;
  4393. devices[*old_device].getProperties2(&old_props);
  4394. std::map<vk::DriverId, int> driver_priorities {};
  4395. int old_priority = std::numeric_limits<int>::max();
  4396. int new_priority = std::numeric_limits<int>::max();
  4397. // Check https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkDriverId.html for the list of driver id
  4398. // Smaller number -> higher priority
  4399. switch (old_props.properties.vendorID) {
  4400. case VK_VENDOR_ID_AMD:
  4401. driver_priorities[vk::DriverId::eMesaRadv] = 1;
  4402. driver_priorities[vk::DriverId::eAmdOpenSource] = 2;
  4403. driver_priorities[vk::DriverId::eAmdProprietary] = 3;
  4404. break;
  4405. case VK_VENDOR_ID_INTEL:
  4406. driver_priorities[vk::DriverId::eIntelOpenSourceMESA] = 1;
  4407. driver_priorities[vk::DriverId::eIntelProprietaryWindows] = 2;
  4408. break;
  4409. case VK_VENDOR_ID_NVIDIA:
  4410. driver_priorities[vk::DriverId::eNvidiaProprietary] = 1;
  4411. #if defined(VK_API_VERSION_1_3) && VK_HEADER_VERSION >= 235
  4412. driver_priorities[vk::DriverId::eMesaNvk] = 2;
  4413. #endif
  4414. break;
  4415. }
  4416. driver_priorities[vk::DriverId::eMesaDozen] = 100;
  4417. if (driver_priorities.count(old_driver.driverID)) {
  4418. old_priority = driver_priorities[old_driver.driverID];
  4419. }
  4420. if (driver_priorities.count(new_driver.driverID)) {
  4421. new_priority = driver_priorities[new_driver.driverID];
  4422. }
  4423. if (new_priority < old_priority) {
  4424. auto r = std::remove(vk_instance.device_indices.begin(), vk_instance.device_indices.end(), *old_device);
  4425. vk_instance.device_indices.erase(r, vk_instance.device_indices.end());
  4426. vk_instance.device_indices.push_back(i);
  4427. VK_LOG_DEBUG("Prioritize device " << i << " driver " << new_driver.driverName << " over device " << *old_device << " driver " << old_driver.driverName);
  4428. }
  4429. else {
  4430. VK_LOG_DEBUG("Prioritize device " << *old_device << " driver " << old_driver.driverName << " over device " << i << " driver " << new_driver.driverName << std::endl);
  4431. }
  4432. }
  4433. }
  4434. }
  4435. // If no GPUs found, fall back to the first non-CPU device.
  4436. // If only CPU devices are available, return without devices.
  4437. if (vk_instance.device_indices.empty()) {
  4438. for (size_t i = 0; i < devices.size(); i++) {
  4439. if (devices[i].getProperties().deviceType != vk::PhysicalDeviceType::eCpu) {
  4440. vk_instance.device_indices.push_back(i);
  4441. break;
  4442. }
  4443. }
  4444. }
  4445. if (vk_instance.device_indices.empty()) {
  4446. GGML_LOG_INFO("ggml_vulkan: No devices found.\n");
  4447. return;
  4448. }
  4449. }
  4450. GGML_LOG_DEBUG("ggml_vulkan: Found %zu Vulkan devices:\n", vk_instance.device_indices.size());
  4451. for (size_t i = 0; i < vk_instance.device_indices.size(); i++) {
  4452. vk::PhysicalDevice vkdev = devices[vk_instance.device_indices[i]];
  4453. std::vector<vk::ExtensionProperties> extensionprops = vkdev.enumerateDeviceExtensionProperties();
  4454. bool membudget_supported = false;
  4455. for (const auto & ext : extensionprops) {
  4456. if (strcmp(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME, ext.extensionName) == 0) {
  4457. membudget_supported = true;
  4458. break;
  4459. }
  4460. }
  4461. vk_instance.device_supports_membudget.push_back(membudget_supported);
  4462. ggml_vk_print_gpu_info(i);
  4463. }
  4464. }
  4465. static void ggml_vk_init(ggml_backend_vk_context * ctx, size_t idx) {
  4466. VK_LOG_DEBUG("ggml_vk_init(" << ctx->name << ", " << idx << ")");
  4467. ggml_vk_instance_init();
  4468. GGML_ASSERT(idx < vk_instance.device_indices.size());
  4469. ctx->name = GGML_VK_NAME + std::to_string(idx);
  4470. ctx->device = ggml_vk_get_device(idx);
  4471. ctx->semaphore_idx = 0;
  4472. ctx->event_idx = 0;
  4473. ctx->prealloc_size_x = 0;
  4474. ctx->prealloc_size_y = 0;
  4475. ctx->prealloc_size_split_k = 0;
  4476. ctx->prealloc_size_add_rms_partials = 0;
  4477. ctx->fence = ctx->device->device.createFence({});
  4478. ctx->almost_ready_fence = ctx->device->device.createFence({});
  4479. ctx->compute_cmd_pool.init(ctx->device, &ctx->device->compute_queue);
  4480. ctx->transfer_cmd_pool.init(ctx->device, &ctx->device->transfer_queue);
  4481. #ifdef GGML_VULKAN_CHECK_RESULTS
  4482. const char* skip_checks = getenv("GGML_VULKAN_SKIP_CHECKS");
  4483. vk_skip_checks = (skip_checks == NULL ? 0 : atoi(skip_checks));
  4484. const char* output_tensor = getenv("GGML_VULKAN_OUTPUT_TENSOR");
  4485. vk_output_tensor = (output_tensor == NULL ? 0 : atoi(output_tensor));
  4486. #endif
  4487. }
  4488. static vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
  4489. VK_LOG_DEBUG("ggml_vk_get_to_fp16()");
  4490. switch (type) {
  4491. case GGML_TYPE_F32:
  4492. case GGML_TYPE_Q4_0:
  4493. case GGML_TYPE_Q4_1:
  4494. case GGML_TYPE_Q5_0:
  4495. case GGML_TYPE_Q5_1:
  4496. case GGML_TYPE_Q8_0:
  4497. case GGML_TYPE_Q2_K:
  4498. case GGML_TYPE_Q3_K:
  4499. case GGML_TYPE_Q4_K:
  4500. case GGML_TYPE_Q5_K:
  4501. case GGML_TYPE_Q6_K:
  4502. case GGML_TYPE_IQ1_S:
  4503. case GGML_TYPE_IQ1_M:
  4504. case GGML_TYPE_IQ2_XXS:
  4505. case GGML_TYPE_IQ2_XS:
  4506. case GGML_TYPE_IQ2_S:
  4507. case GGML_TYPE_IQ3_XXS:
  4508. case GGML_TYPE_IQ3_S:
  4509. case GGML_TYPE_IQ4_XS:
  4510. case GGML_TYPE_IQ4_NL:
  4511. case GGML_TYPE_MXFP4:
  4512. break;
  4513. default:
  4514. return nullptr;
  4515. }
  4516. return ctx->device->pipeline_dequant[type];
  4517. }
  4518. 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) {
  4519. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_pipeline(" << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ", " << prec << ")");
  4520. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4521. return ctx->device->pipeline_matmul_f32;
  4522. }
  4523. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F16) {
  4524. return ctx->device->pipeline_matmul_f32_f16;
  4525. }
  4526. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4527. return ctx->device->pipeline_matmul_bf16;
  4528. }
  4529. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4530. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4531. return ctx->device->pipeline_matmul_f16_f32.f16acc;
  4532. }
  4533. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4534. return ctx->device->pipeline_matmul_f16.f16acc;
  4535. }
  4536. } else {
  4537. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4538. return ctx->device->pipeline_matmul_f16_f32.f32acc;
  4539. }
  4540. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4541. return ctx->device->pipeline_matmul_f16.f32acc;
  4542. }
  4543. }
  4544. // MMQ
  4545. if (src1_type == GGML_TYPE_Q8_1) {
  4546. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1[src0_type].f32acc;
  4547. if (pipelines->is_empty()) {
  4548. return nullptr;
  4549. }
  4550. return pipelines;
  4551. }
  4552. if (src1_type != GGML_TYPE_F32 && !ctx->device->coopmat2) {
  4553. return nullptr;
  4554. }
  4555. switch (src0_type) {
  4556. case GGML_TYPE_Q4_0:
  4557. case GGML_TYPE_Q4_1:
  4558. case GGML_TYPE_Q5_0:
  4559. case GGML_TYPE_Q5_1:
  4560. case GGML_TYPE_Q8_0:
  4561. case GGML_TYPE_Q2_K:
  4562. case GGML_TYPE_Q3_K:
  4563. case GGML_TYPE_Q4_K:
  4564. case GGML_TYPE_Q5_K:
  4565. case GGML_TYPE_Q6_K:
  4566. case GGML_TYPE_IQ1_S:
  4567. case GGML_TYPE_IQ1_M:
  4568. case GGML_TYPE_IQ2_XXS:
  4569. case GGML_TYPE_IQ2_XS:
  4570. case GGML_TYPE_IQ2_S:
  4571. case GGML_TYPE_IQ3_XXS:
  4572. case GGML_TYPE_IQ3_S:
  4573. case GGML_TYPE_IQ4_XS:
  4574. case GGML_TYPE_IQ4_NL:
  4575. case GGML_TYPE_MXFP4:
  4576. break;
  4577. default:
  4578. return nullptr;
  4579. }
  4580. if (ctx->device->coopmat2) {
  4581. assert(src1_type == GGML_TYPE_F16);
  4582. 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;
  4583. }
  4584. if (ctx->device->coopmat_support) {
  4585. 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;
  4586. }
  4587. 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;
  4588. }
  4589. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type, uint32_t num_cols, uint32_t m, uint32_t k) {
  4590. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec()");
  4591. GGML_ASSERT(b_type == GGML_TYPE_F32 || b_type == GGML_TYPE_F16 || b_type == GGML_TYPE_Q8_1);
  4592. GGML_ASSERT(num_cols >= 1 && num_cols <= mul_mat_vec_max_cols);
  4593. if (b_type == GGML_TYPE_Q8_1) {
  4594. switch (a_type) {
  4595. case GGML_TYPE_Q4_0:
  4596. case GGML_TYPE_Q4_1:
  4597. case GGML_TYPE_Q5_0:
  4598. case GGML_TYPE_Q5_1:
  4599. case GGML_TYPE_Q8_0:
  4600. break;
  4601. default:
  4602. return nullptr;
  4603. }
  4604. }
  4605. switch (a_type) {
  4606. case GGML_TYPE_F32:
  4607. case GGML_TYPE_F16:
  4608. case GGML_TYPE_BF16:
  4609. case GGML_TYPE_Q4_0:
  4610. case GGML_TYPE_Q4_1:
  4611. case GGML_TYPE_Q5_0:
  4612. case GGML_TYPE_Q5_1:
  4613. case GGML_TYPE_Q8_0:
  4614. case GGML_TYPE_Q2_K:
  4615. case GGML_TYPE_Q3_K:
  4616. case GGML_TYPE_Q4_K:
  4617. case GGML_TYPE_Q5_K:
  4618. case GGML_TYPE_Q6_K:
  4619. case GGML_TYPE_IQ1_S:
  4620. case GGML_TYPE_IQ1_M:
  4621. case GGML_TYPE_IQ2_XXS:
  4622. case GGML_TYPE_IQ2_XS:
  4623. case GGML_TYPE_IQ2_S:
  4624. case GGML_TYPE_IQ3_XXS:
  4625. case GGML_TYPE_IQ3_S:
  4626. case GGML_TYPE_IQ4_XS:
  4627. case GGML_TYPE_IQ4_NL:
  4628. case GGML_TYPE_MXFP4:
  4629. break;
  4630. default:
  4631. return nullptr;
  4632. }
  4633. // heuristic to choose workgroup size
  4634. uint32_t dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4635. if ((ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA && ctx->device->architecture != vk_device_architecture::NVIDIA_PRE_TURING) || ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4636. // Prefer larger workgroups when M is small, to spread the work out more
  4637. // and keep more SMs busy.
  4638. // q6_k seems to prefer small workgroup size even for "medium" values of M.
  4639. if (a_type == GGML_TYPE_Q6_K) {
  4640. if (m < 4096 && k >= 1024) {
  4641. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4642. }
  4643. } else {
  4644. if (m <= 8192 && k >= 1024) {
  4645. dmmv_wg = DMMV_WG_SIZE_LARGE;
  4646. }
  4647. }
  4648. }
  4649. if (b_type == GGML_TYPE_Q8_1) {
  4650. if (ctx->device->vendor_id == VK_VENDOR_ID_INTEL) {
  4651. dmmv_wg = DMMV_WG_SIZE_SUBGROUP;
  4652. }
  4653. return ctx->device->pipeline_dequant_mul_mat_vec_q8_1_f32[dmmv_wg][a_type][num_cols-1];
  4654. }
  4655. return b_type == GGML_TYPE_F32 ? ctx->device->pipeline_dequant_mul_mat_vec_f32_f32[dmmv_wg][a_type][num_cols-1] : ctx->device->pipeline_dequant_mul_mat_vec_f16_f32[dmmv_wg][a_type][num_cols-1];
  4656. }
  4657. 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) {
  4658. VK_LOG_DEBUG("ggml_vk_get_mul_mat_mat_id_pipeline()");
  4659. if (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_F32) {
  4660. return ctx->device->pipeline_matmul_id_f32;
  4661. }
  4662. if (src0_type == GGML_TYPE_BF16 && src1_type == GGML_TYPE_BF16) {
  4663. return ctx->device->pipeline_matmul_id_bf16;
  4664. }
  4665. if (prec == GGML_PREC_DEFAULT && ctx->device->fp16 && !(ctx->device->coopmat_support && !ctx->device->coopmat_acc_f16_support)) {
  4666. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4667. return ctx->device->pipeline_matmul_id_f16_f32.f16acc;
  4668. }
  4669. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4670. return ctx->device->pipeline_matmul_id_f16.f16acc;
  4671. }
  4672. } else {
  4673. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F32) {
  4674. return ctx->device->pipeline_matmul_id_f16_f32.f32acc;
  4675. }
  4676. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  4677. return ctx->device->pipeline_matmul_id_f16.f32acc;
  4678. }
  4679. }
  4680. // MMQ
  4681. if (src1_type == GGML_TYPE_Q8_1) {
  4682. vk_matmul_pipeline pipelines = ctx->device->pipeline_dequant_mul_mat_mat_id_q8_1[src0_type].f32acc;
  4683. if (pipelines->is_empty()) {
  4684. return nullptr;
  4685. }
  4686. return pipelines;
  4687. }
  4688. GGML_ASSERT(src1_type == GGML_TYPE_F32 || (ctx->device->coopmat2 && src1_type == GGML_TYPE_F16));
  4689. switch (src0_type) {
  4690. case GGML_TYPE_Q4_0:
  4691. case GGML_TYPE_Q4_1:
  4692. case GGML_TYPE_Q5_0:
  4693. case GGML_TYPE_Q5_1:
  4694. case GGML_TYPE_Q8_0:
  4695. case GGML_TYPE_Q2_K:
  4696. case GGML_TYPE_Q3_K:
  4697. case GGML_TYPE_Q4_K:
  4698. case GGML_TYPE_Q5_K:
  4699. case GGML_TYPE_Q6_K:
  4700. case GGML_TYPE_IQ1_S:
  4701. case GGML_TYPE_IQ1_M:
  4702. case GGML_TYPE_IQ2_XXS:
  4703. case GGML_TYPE_IQ2_XS:
  4704. case GGML_TYPE_IQ2_S:
  4705. case GGML_TYPE_IQ3_XXS:
  4706. case GGML_TYPE_IQ3_S:
  4707. case GGML_TYPE_IQ4_XS:
  4708. case GGML_TYPE_IQ4_NL:
  4709. case GGML_TYPE_MXFP4:
  4710. break;
  4711. default:
  4712. return nullptr;
  4713. }
  4714. vk_matmul_pipeline2& mmp = ctx->device->pipeline_dequant_mul_mat_mat_id[src0_type];
  4715. // XXX TODO 'prec' is not actually allowed in mul_mat_id.
  4716. bool prefer_fp16acc = ctx->device->fp16 /*&& prec == GGML_PREC_DEFAULT*/;
  4717. bool support_fp16acc = !mmp.f16acc->is_empty();
  4718. bool support_fp32acc = !mmp.f32acc->is_empty();
  4719. if (support_fp16acc && (prefer_fp16acc || !support_fp32acc)) {
  4720. return mmp.f16acc;
  4721. } else {
  4722. GGML_ASSERT(support_fp32acc);
  4723. return mmp.f32acc;
  4724. }
  4725. }
  4726. static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context * ctx, ggml_type a_type, ggml_type b_type) {
  4727. VK_LOG_DEBUG("ggml_vk_get_dequantize_mul_mat_vec_id()");
  4728. GGML_ASSERT(b_type == GGML_TYPE_F32);
  4729. switch (a_type) {
  4730. case GGML_TYPE_F32:
  4731. case GGML_TYPE_F16:
  4732. case GGML_TYPE_BF16:
  4733. case GGML_TYPE_Q4_0:
  4734. case GGML_TYPE_Q4_1:
  4735. case GGML_TYPE_Q5_0:
  4736. case GGML_TYPE_Q5_1:
  4737. case GGML_TYPE_Q8_0:
  4738. case GGML_TYPE_Q2_K:
  4739. case GGML_TYPE_Q3_K:
  4740. case GGML_TYPE_Q4_K:
  4741. case GGML_TYPE_Q5_K:
  4742. case GGML_TYPE_Q6_K:
  4743. case GGML_TYPE_IQ1_S:
  4744. case GGML_TYPE_IQ1_M:
  4745. case GGML_TYPE_IQ2_XXS:
  4746. case GGML_TYPE_IQ2_XS:
  4747. case GGML_TYPE_IQ2_S:
  4748. case GGML_TYPE_IQ3_XXS:
  4749. case GGML_TYPE_IQ3_S:
  4750. case GGML_TYPE_IQ4_XS:
  4751. case GGML_TYPE_IQ4_NL:
  4752. case GGML_TYPE_MXFP4:
  4753. break;
  4754. default:
  4755. return nullptr;
  4756. }
  4757. return ctx->device->pipeline_dequant_mul_mat_vec_id_f32[a_type];
  4758. }
  4759. static void * ggml_vk_host_malloc(vk_device& device, size_t size) {
  4760. VK_LOG_MEMORY("ggml_vk_host_malloc(" << size << ")");
  4761. vk_buffer buf = ggml_vk_create_buffer(device, size,
  4762. {vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4763. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent});
  4764. if(!(buf->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible)) {
  4765. fprintf(stderr, "WARNING: failed to allocate %.2f MB of pinned memory\n",
  4766. size/1024.0/1024.0);
  4767. device->device.freeMemory(buf->device_memory);
  4768. device->device.destroyBuffer(buf->buffer);
  4769. return nullptr;
  4770. }
  4771. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4772. device->pinned_memory.push_back(std::make_tuple(buf->ptr, size, buf));
  4773. return buf->ptr;
  4774. }
  4775. static void ggml_vk_host_free(vk_device& device, void* ptr) {
  4776. if (ptr == nullptr) {
  4777. return;
  4778. }
  4779. VK_LOG_MEMORY("ggml_vk_host_free(" << ptr << ")");
  4780. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4781. vk_buffer buf;
  4782. size_t index;
  4783. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4784. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4785. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4786. if (ptr >= addr && ptr < endr) {
  4787. buf = std::get<2>(device->pinned_memory[i]);
  4788. index = i;
  4789. break;
  4790. }
  4791. }
  4792. if (buf == nullptr) {
  4793. fprintf(stderr, "WARNING: failed to free pinned memory: memory not in map\n");
  4794. return;
  4795. }
  4796. ggml_vk_destroy_buffer(buf);
  4797. device->pinned_memory.erase(device->pinned_memory.begin() + index);
  4798. }
  4799. static void ggml_vk_host_get(const vk_device& device, const void * ptr, vk_buffer& buf, size_t& buf_offset) {
  4800. std::lock_guard<std::recursive_mutex> guard(device->mutex);
  4801. buf = nullptr;
  4802. buf_offset = 0;
  4803. for (size_t i = 0; i < device->pinned_memory.size(); i++) {
  4804. const uint8_t* addr = (const uint8_t*) std::get<0>(device->pinned_memory[i]);
  4805. const uint8_t* endr = addr + std::get<1>(device->pinned_memory[i]);
  4806. if (ptr >= addr && ptr < endr) {
  4807. buf = std::get<2>(device->pinned_memory[i]);
  4808. buf_offset = ((const uint8_t *)ptr) - addr;
  4809. break;
  4810. }
  4811. }
  4812. }
  4813. static vk_subbuffer ggml_vk_tensor_subbuffer(
  4814. const ggml_backend_vk_context * ctx, const ggml_tensor * tensor, bool allow_misalign = false) {
  4815. vk_buffer buffer = nullptr;
  4816. size_t offset = 0;
  4817. if (ctx->device->uma) {
  4818. ggml_vk_host_get(ctx->device, tensor->data, buffer, offset);
  4819. }
  4820. if (!buffer) {
  4821. auto buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  4822. buffer = buf_ctx->dev_buffer;
  4823. offset = vk_tensor_offset(tensor) + tensor->view_offs;
  4824. }
  4825. GGML_ASSERT(buffer != nullptr);
  4826. size_t size = ggml_nbytes(tensor);
  4827. size_t misalign_bytes = offset & (ctx->device->properties.limits.minStorageBufferOffsetAlignment - 1);
  4828. // The shader must support misaligned offsets when indexing into the buffer
  4829. GGML_ASSERT(allow_misalign || misalign_bytes == 0);
  4830. offset &= ~misalign_bytes;
  4831. size += misalign_bytes;
  4832. return vk_subbuffer{buffer, offset, size};
  4833. }
  4834. static vk_submission ggml_vk_begin_submission(vk_device& device, vk_command_pool& p, bool one_time = true) {
  4835. vk_submission s;
  4836. s.buffer = ggml_vk_create_cmd_buffer(device, p);
  4837. if (one_time) {
  4838. s.buffer.begin({ vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
  4839. } else {
  4840. s.buffer.begin({ vk::CommandBufferUsageFlags{} });
  4841. }
  4842. return s;
  4843. }
  4844. template <typename T> size_t push_constant_size(const T &t) {
  4845. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4846. GGML_UNUSED(t);
  4847. return sizeof(T);
  4848. }
  4849. template <typename T> size_t push_constant_size(const std::vector<T> &t) {
  4850. GGML_UNUSED(t);
  4851. return sizeof(T) * t.size();
  4852. }
  4853. template <typename T, uint32_t N> size_t push_constant_size(const std::array<T, N> &t) {
  4854. GGML_UNUSED(t);
  4855. return sizeof(T) * N;
  4856. }
  4857. template <typename T> const T *push_constant_data(const T &t) {
  4858. static_assert(std::is_class<T>::value, "T must be a struct/class");
  4859. return &t;
  4860. }
  4861. template <typename T> const T *push_constant_data(const std::vector<T> &t) {
  4862. return t.data();
  4863. }
  4864. template <typename T, uint32_t N> const T *push_constant_data(const std::array<T, N> &t) {
  4865. return t.data();
  4866. }
  4867. template <typename T>
  4868. 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) {
  4869. const uint32_t wg0 = CEIL_DIV(elements[0], pipeline->wg_denoms[0]);
  4870. const uint32_t wg1 = CEIL_DIV(elements[1], pipeline->wg_denoms[1]);
  4871. const uint32_t wg2 = CEIL_DIV(elements[2], pipeline->wg_denoms[2]);
  4872. VK_LOG_DEBUG("ggml_vk_dispatch_pipeline(" << pipeline->name << ", {";
  4873. for (auto& buffer : descriptor_buffer_infos) {
  4874. std::cerr << "(" << buffer.buffer << ", " << buffer.offset << ", " << buffer.range << "), ";
  4875. }
  4876. std::cerr << "}, (" << wg0 << "," << wg1 << "," << wg2 << "))");
  4877. GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size());
  4878. GGML_ASSERT(descriptor_buffer_infos.size() <= MAX_PARAMETER_COUNT);
  4879. GGML_ASSERT(pipeline->parameter_count == descriptor_buffer_infos.size());
  4880. vk::DescriptorSet& descriptor_set = ctx->descriptor_sets[ctx->descriptor_set_idx++];
  4881. vk::WriteDescriptorSet write_descriptor_set{ descriptor_set, 0, 0, pipeline->parameter_count, vk::DescriptorType::eStorageBuffer, nullptr, descriptor_buffer_infos.begin() };
  4882. ctx->device->device.updateDescriptorSets({ write_descriptor_set }, {});
  4883. subctx->s->buffer.pushConstants(pipeline->layout, vk::ShaderStageFlagBits::eCompute, 0, push_constant_size(push_constants), push_constant_data(push_constants));
  4884. subctx->s->buffer.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline->pipeline);
  4885. subctx->s->buffer.bindDescriptorSets(vk::PipelineBindPoint::eCompute,
  4886. pipeline->layout,
  4887. 0,
  4888. { descriptor_set },
  4889. {});
  4890. subctx->s->buffer.dispatch(wg0, wg1, wg2);
  4891. }
  4892. static void ggml_vk_end_submission(vk_submission& s, std::vector<vk_semaphore> wait_semaphores, std::vector<vk_semaphore> signal_semaphores) {
  4893. s.buffer.end();
  4894. s.wait_semaphores = std::move(wait_semaphores);
  4895. s.signal_semaphores = std::move(signal_semaphores);
  4896. }
  4897. static void ggml_vk_ctx_end(vk_context& ctx) {
  4898. VK_LOG_DEBUG("ggml_vk_ctx_end(" << ctx << ", " << ctx->seqs.size() << ")");
  4899. if (ctx->s == nullptr) {
  4900. return;
  4901. }
  4902. ctx->s->buffer.end();
  4903. ctx->s = nullptr;
  4904. }
  4905. static void ggml_vk_ctx_begin(vk_device& device, vk_context& subctx) {
  4906. VK_LOG_DEBUG("ggml_vk_ctx_begin(" << device->name << ")");
  4907. if (subctx->s != nullptr) {
  4908. ggml_vk_ctx_end(subctx);
  4909. }
  4910. subctx->seqs.push_back({ ggml_vk_begin_submission(device, *subctx->p) });
  4911. subctx->s = subctx->seqs[subctx->seqs.size() - 1].data();
  4912. }
  4913. static size_t ggml_vk_align_size(size_t width, size_t align) {
  4914. VK_LOG_DEBUG("ggml_vk_align_size(" << width << ", " << align << ")");
  4915. return CEIL_DIV(width, align) * align;
  4916. }
  4917. static void deferred_memcpy(void * dst, const void * src, size_t size, std::vector<vk_staging_memcpy>* memcpys = nullptr) {
  4918. if (memcpys == nullptr) {
  4919. memcpy(dst, src, size);
  4920. } else {
  4921. memcpys->emplace_back(dst, src, size);
  4922. }
  4923. }
  4924. static void deferred_memset(void * dst, uint32_t val, size_t size, std::vector<vk_staging_memset>* memsets = nullptr) {
  4925. if (memsets == nullptr) {
  4926. memset(dst, val, size);
  4927. } else {
  4928. memsets->emplace_back(dst, val, size);
  4929. }
  4930. }
  4931. static void ggml_vk_ensure_sync_staging_buffer(vk_device& device, size_t size) {
  4932. if (device->sync_staging == nullptr || device->sync_staging->size < size) {
  4933. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  4934. ggml_vk_destroy_buffer(device->sync_staging);
  4935. device->sync_staging = ggml_vk_create_buffer_check(device, size,
  4936. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4937. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  4938. }
  4939. }
  4940. static void ggml_vk_ensure_sync_staging_buffer(ggml_backend_vk_context * ctx, size_t size) {
  4941. if (ctx->sync_staging == nullptr || ctx->sync_staging->size < size) {
  4942. VK_LOG_MEMORY("ggml_vk_ensure_sync_staging_buffer(" << size << ")");
  4943. ggml_vk_destroy_buffer(ctx->sync_staging);
  4944. ctx->sync_staging = ggml_vk_create_buffer_check(ctx->device, size,
  4945. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent | vk::MemoryPropertyFlagBits::eHostCached,
  4946. vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
  4947. }
  4948. }
  4949. 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) {
  4950. VK_LOG_DEBUG("ggml_vk_buffer_write_nc_async(" << tensor << ")");
  4951. GGML_ASSERT(!ggml_is_contiguous(tensor));
  4952. // Buffer is already mapped
  4953. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  4954. std::cerr << "ggml_vulkan: buffer_write_nc_async dst buffer is host_visible. Use synchronous write." << std::endl;
  4955. GGML_ABORT("fatal error");
  4956. }
  4957. // Check if src is pinned memory
  4958. vk_buffer buf = nullptr;
  4959. size_t buf_offset = 0;
  4960. ggml_vk_host_get(ctx->device, tensor->data, buf, buf_offset);
  4961. const uint64_t ne0 = tensor->ne[0];
  4962. const uint64_t ne1 = tensor->ne[1];
  4963. const uint64_t ne2 = tensor->ne[2];
  4964. const uint64_t ne3 = tensor->ne[3];
  4965. const uint64_t nb0 = tensor->nb[0];
  4966. const uint64_t nb1 = tensor->nb[1];
  4967. const uint64_t nb2 = tensor->nb[2];
  4968. const uint64_t nb3 = tensor->nb[3];
  4969. const ggml_type type = tensor->type;
  4970. const uint64_t ts = ggml_type_size(type);
  4971. const uint64_t bs = ggml_blck_size(type);
  4972. const uint64_t dstnb0 = ts;
  4973. const uint64_t dstnb1 = dstnb0*(ne0/bs);
  4974. const uint64_t dstnb2 = dstnb1*ne1;
  4975. const uint64_t dstnb3 = dstnb2*ne2;
  4976. const uint64_t ne = ggml_nelements(tensor);
  4977. if (buf != nullptr) {
  4978. // Memory is pinned, use as staging buffer
  4979. std::vector<vk::BufferCopy> slices;
  4980. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  4981. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  4982. // Find longest contiguous slice
  4983. if (ne1*nb1 == dstnb2) {
  4984. slices.push_back({ buf_offset + i3*nb3 + i2*nb2, offset + i3*dstnb3 + i2*dstnb2, dstnb2 });
  4985. } else {
  4986. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  4987. if (ne0*nb0/bs == dstnb1) {
  4988. slices.push_back({ buf_offset + i3*nb3 + i2*nb2 + i1*nb1, offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1, dstnb1 });
  4989. } else {
  4990. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  4991. const uint64_t d_off = offset + i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  4992. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  4993. slices.push_back({ s_off + i1*nb0, d_off + i0*dstnb0, dstnb0 });
  4994. }
  4995. }
  4996. }
  4997. }
  4998. }
  4999. }
  5000. ggml_vk_sync_buffers(ctx, subctx);
  5001. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  5002. return;
  5003. }
  5004. if (!sync_staging) {
  5005. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  5006. }
  5007. // Staging buffer required
  5008. vk_buffer& staging = ctx->device->sync_staging;
  5009. const uint64_t copy_size = ts*ne/bs;
  5010. ggml_vk_ensure_sync_staging_buffer(ctx->device, copy_size);
  5011. VkBufferCopy buf_copy{ 0, offset, copy_size };
  5012. ggml_vk_sync_buffers(ctx, subctx);
  5013. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  5014. for (uint64_t i3 = 0; i3 < ne3; i3++) {
  5015. for (uint64_t i2 = 0; i2 < ne2; i2++) {
  5016. // Find longest contiguous slice
  5017. if (ne1*nb1 == dstnb2) {
  5018. 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);
  5019. } else {
  5020. for (uint64_t i1 = 0; i1 < ne1; i1++) {
  5021. if (ne0*nb0/bs == dstnb1) {
  5022. 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);
  5023. } else {
  5024. const uint64_t s_off = buf_offset + i3*nb3 + i2*nb2 + i1*nb1;
  5025. const uint64_t d_off = i3*dstnb3 + i2*dstnb2 + i1*dstnb1;
  5026. for (uint64_t i0 = 0; i0 < ne0; i0++) {
  5027. deferred_memcpy((uint8_t *)staging->ptr + d_off + i0*dstnb0, (const uint8_t *) tensor->data + s_off + i0*nb0, dstnb0, &subctx->in_memcpys);
  5028. }
  5029. }
  5030. }
  5031. }
  5032. }
  5033. }
  5034. }
  5035. 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) {
  5036. VK_LOG_DEBUG("ggml_vk_buffer_write_2d_async(" << width << ", " << height << ")");
  5037. // Buffer is already mapped
  5038. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5039. std::cerr << "ggml_vulkan: buffer_write_async dst buffer is host_visible. Use synchronous write." << std::endl;
  5040. GGML_ABORT("fatal error");
  5041. }
  5042. // Check if src is pinned memory
  5043. vk_buffer buf = nullptr;
  5044. size_t buf_offset = 0;
  5045. ggml_vk_host_get(dst->device, src, buf, buf_offset);
  5046. if (buf != nullptr) {
  5047. // Memory is pinned, use as staging buffer
  5048. std::vector<vk::BufferCopy> slices(1);
  5049. if (width == spitch) {
  5050. // Only do single write if stride is equal
  5051. slices[0].srcOffset = buf_offset;
  5052. slices[0].dstOffset = offset;
  5053. slices[0].size = width * height;
  5054. } else {
  5055. slices.resize(height);
  5056. for (size_t i = 0; i < height; i++) {
  5057. slices[i].srcOffset = buf_offset + i * spitch;
  5058. slices[i].dstOffset = offset + i * width;
  5059. slices[i].size = width;
  5060. }
  5061. }
  5062. ggml_vk_sync_buffers(nullptr, subctx);
  5063. subctx->s->buffer.copyBuffer(buf->buffer, dst->buffer, slices);
  5064. return;
  5065. }
  5066. VK_LOG_DEBUG("STAGING");
  5067. if (!sync_staging) {
  5068. GGML_ABORT("Asynchronous write to non-pinned memory not supported");
  5069. }
  5070. // Staging buffer required
  5071. const size_t copy_size = width*height;
  5072. ggml_vk_ensure_sync_staging_buffer(dst->device, copy_size);
  5073. vk_buffer& staging_buffer = dst->device->sync_staging;
  5074. VkBufferCopy buf_copy = {
  5075. 0,
  5076. offset,
  5077. copy_size};
  5078. ggml_vk_sync_buffers(nullptr, subctx);
  5079. vkCmdCopyBuffer(subctx->s->buffer, (VkBuffer)staging_buffer->buffer, (VkBuffer)dst->buffer, 1, &buf_copy);
  5080. if (width == spitch) {
  5081. deferred_memcpy((uint8_t *)staging_buffer->ptr, src, width * height, &subctx->in_memcpys);
  5082. } else {
  5083. for (size_t i = 0; i < height; i++) {
  5084. deferred_memcpy((uint8_t *)staging_buffer->ptr + i * width, (const uint8_t *) src + i * spitch, width, &subctx->in_memcpys);
  5085. }
  5086. }
  5087. }
  5088. 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) {
  5089. VK_LOG_DEBUG("ggml_vk_buffer_write_async(" << size << ")");
  5090. return ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, size, size, 1, sync_staging);
  5091. }
  5092. 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) {
  5093. VK_LOG_DEBUG("ggml_vk_buffer_write_2d(" << width << ", " << height << ")");
  5094. // Buffer is already mapped
  5095. if(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible) {
  5096. GGML_ASSERT(dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5097. for (size_t i = 0; i < height; i++) {
  5098. memcpy((uint8_t *)dst->ptr + offset + i * width, (const uint8_t *) src + i * spitch, width);
  5099. }
  5100. } else {
  5101. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5102. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5103. ggml_vk_ctx_begin(dst->device, subctx);
  5104. ggml_vk_buffer_write_2d_async(subctx, dst, offset, src, spitch, width, height, true);
  5105. ggml_vk_ctx_end(subctx);
  5106. for (auto& cpy : subctx->in_memcpys) {
  5107. memcpy(cpy.dst, cpy.src, cpy.n);
  5108. }
  5109. for (auto& mset : subctx->memsets) {
  5110. memset(mset.dst, mset.val, mset.n);
  5111. }
  5112. ggml_vk_submit(subctx, dst->device->fence);
  5113. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_buffer_write_2d waitForFences");
  5114. dst->device->device.resetFences({ dst->device->fence });
  5115. ggml_vk_queue_command_pools_cleanup(dst->device);
  5116. }
  5117. }
  5118. static void ggml_vk_buffer_write(vk_buffer& dst, size_t offset, const void * src, size_t size) {
  5119. VK_LOG_DEBUG("ggml_vk_buffer_write(" << size << ")");
  5120. ggml_vk_buffer_write_2d(dst, offset, src, 0, size, 1);
  5121. }
  5122. static bool 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) {
  5123. VK_LOG_DEBUG("ggml_vk_buffer_read_2d_async(offset=" << offset << ", width=" << width << ", height=" << height << ")");
  5124. GGML_ASSERT(width > 0);
  5125. GGML_ASSERT(height > 0);
  5126. GGML_ASSERT(src != nullptr);
  5127. // TODO: staging_offset is not used
  5128. // Check if dst is pinned memory
  5129. vk_buffer buf = nullptr;
  5130. size_t buf_offset = 0;
  5131. ggml_vk_host_get(src->device, dst, buf, buf_offset);
  5132. std::vector<vk::BufferCopy> slices(1);
  5133. if (width == spitch && width == dpitch) {
  5134. // Only do single write if stride is equal
  5135. slices[0].srcOffset = offset;
  5136. slices[0].dstOffset = buf_offset;
  5137. slices[0].size = width * height;
  5138. } else {
  5139. slices.resize(height);
  5140. for (size_t i = 0; i < height; i++) {
  5141. slices[i].srcOffset = offset + i * spitch;
  5142. slices[i].dstOffset = buf_offset + i * dpitch;
  5143. slices[i].size = width;
  5144. }
  5145. }
  5146. if (buf != nullptr) {
  5147. // Memory is pinned, use as staging buffer
  5148. ggml_vk_sync_buffers(nullptr, subctx);
  5149. subctx->s->buffer.copyBuffer(src->buffer, buf->buffer, slices);
  5150. return true;
  5151. }
  5152. VK_LOG_DEBUG("STAGING");
  5153. if (!sync_staging) {
  5154. // copy was not handled caller needs to fall back
  5155. return false;
  5156. }
  5157. // Fall back to staging buffer
  5158. const size_t copy_size = dpitch * height;
  5159. ggml_vk_ensure_sync_staging_buffer(src->device, copy_size);
  5160. vk_buffer& staging_buffer = src->device->sync_staging;
  5161. ggml_vk_sync_buffers(nullptr, subctx);
  5162. subctx->s->buffer.copyBuffer(src->buffer, staging_buffer->buffer, slices);
  5163. deferred_memcpy(dst, staging_buffer->ptr, copy_size, &subctx->out_memcpys);
  5164. return true;
  5165. }
  5166. static bool ggml_vk_buffer_read_async(vk_context subctx, vk_buffer& src, size_t offset, void * dst, size_t size, bool sync_staging = false) {
  5167. return ggml_vk_buffer_read_2d_async(subctx, src, offset, dst, size, size, size, 1, sync_staging);
  5168. }
  5169. static void ggml_vk_buffer_read(vk_buffer& src, size_t offset, void * dst, size_t size) {
  5170. VK_LOG_DEBUG("ggml_vk_buffer_read(" << src->buffer << ", " << offset << ", " << size << ")");
  5171. // If the device is not an UMA device the memory is host-accessible through rebar. While writing
  5172. // through PCIe is sufficient fast reading back data from PCIe is slower than going through
  5173. // the HW device to host copy path.
  5174. if(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible && src->device->uma) {
  5175. GGML_ASSERT(src->memory_property_flags & vk::MemoryPropertyFlagBits::eHostCoherent);
  5176. memcpy(dst, (uint8_t *) src->ptr + offset, size);
  5177. } else {
  5178. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5179. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5180. ggml_vk_ctx_begin(src->device, subctx);
  5181. bool ret = ggml_vk_buffer_read_async(subctx, src, offset, dst, size, true);
  5182. GGML_ASSERT(ret);
  5183. ggml_vk_ctx_end(subctx);
  5184. ggml_vk_submit(subctx, src->device->fence);
  5185. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_read waitForFences");
  5186. src->device->device.resetFences({ src->device->fence });
  5187. ggml_vk_queue_command_pools_cleanup(src->device);
  5188. for (auto& cpy : subctx->out_memcpys) {
  5189. memcpy(cpy.dst, cpy.src, cpy.n);
  5190. }
  5191. }
  5192. }
  5193. 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) {
  5194. VK_LOG_DEBUG("ggml_vk_buffer_copy_async(" << size << ")");
  5195. // Make sure both buffers are on same device
  5196. GGML_ASSERT(src->device == dst->device);
  5197. VkBufferCopy bc{ src_offset, dst_offset, size };
  5198. vkCmdCopyBuffer(ctx->s->buffer, (VkBuffer)src->buffer, (VkBuffer)dst->buffer, 1, &bc);
  5199. }
  5200. static void ggml_vk_buffer_copy(vk_buffer& dst, size_t dst_offset, vk_buffer& src, size_t src_offset, size_t size) {
  5201. if (src->device == dst->device) {
  5202. std::lock_guard<std::recursive_mutex> guard(src->device->mutex);
  5203. VK_LOG_DEBUG("ggml_vk_buffer_copy(SINGLE_DEVICE, " << size << ")");
  5204. // Copy within the device
  5205. vk_context subctx = ggml_vk_create_temporary_context(src->device->transfer_queue.cmd_pool);
  5206. ggml_vk_ctx_begin(src->device, subctx);
  5207. ggml_vk_buffer_copy_async(subctx, dst, dst_offset, src, src_offset, size);
  5208. ggml_vk_ctx_end(subctx);
  5209. ggml_vk_submit(subctx, src->device->fence);
  5210. VK_CHECK(src->device->device.waitForFences({ src->device->fence }, true, UINT64_MAX), "vk_buffer_copy waitForFences");
  5211. src->device->device.resetFences({ src->device->fence });
  5212. ggml_vk_queue_command_pools_cleanup(src->device);
  5213. } else {
  5214. VK_LOG_DEBUG("ggml_vk_buffer_copy(MULTI_DEVICE, " << size << ")");
  5215. // Copy device to device
  5216. ggml_vk_ensure_sync_staging_buffer(src->device, size);
  5217. // Copy to src staging buffer
  5218. ggml_vk_buffer_copy(src->device->sync_staging, 0, src, src_offset, size);
  5219. // Copy to dst buffer
  5220. ggml_vk_buffer_write_2d(dst, dst_offset, src->device->sync_staging->ptr, 0, size, 1);
  5221. }
  5222. }
  5223. static void ggml_vk_buffer_memset_async(vk_context& ctx, vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5224. VK_LOG_DEBUG("ggml_vk_buffer_memset_async(" << offset << ", " << c << ", " << size << ")");
  5225. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5226. dst->device->uma) {
  5227. deferred_memset((uint8_t*)dst->ptr + offset, c, size, &ctx->memsets);
  5228. return;
  5229. }
  5230. // Fall back to GPU fillBuffer for non-UMA or non-host-visible buffers
  5231. ctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5232. }
  5233. static void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t size) {
  5234. VK_LOG_DEBUG("ggml_vk_buffer_memset(" << offset << ", " << c << ", " << size << ")");
  5235. if (dst->memory_property_flags & vk::MemoryPropertyFlagBits::eHostVisible &&
  5236. dst->device->uma) {
  5237. memset((uint8_t*)dst->ptr + offset, c, size);
  5238. return;
  5239. }
  5240. std::lock_guard<std::recursive_mutex> guard(dst->device->mutex);
  5241. vk_context subctx = ggml_vk_create_temporary_context(dst->device->transfer_queue.cmd_pool);
  5242. ggml_vk_ctx_begin(dst->device, subctx);
  5243. subctx->s->buffer.fillBuffer(dst->buffer, offset, size, c);
  5244. ggml_vk_ctx_end(subctx);
  5245. ggml_vk_submit(subctx, dst->device->fence);
  5246. VK_CHECK(dst->device->device.waitForFences({ dst->device->fence }, true, UINT64_MAX), "vk_memset waitForFences");
  5247. dst->device->device.resetFences({ dst->device->fence });
  5248. ggml_vk_queue_command_pools_cleanup(dst->device);
  5249. }
  5250. static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, uint32_t m, uint32_t n, uint32_t k, bool disable_split_k, const vk_pipeline& pipeline) {
  5251. VK_LOG_DEBUG("ggml_vk_guess_split_k(" << m << ", " << n << ", " << k << ", " << disable_split_k << ")");
  5252. if (disable_split_k) {
  5253. return 1;
  5254. }
  5255. uint32_t split_k = 1;
  5256. if (ctx->device->shader_core_count != 0 && m >= pipeline->wg_denoms[0] && n >= pipeline->wg_denoms[1]) {
  5257. // If k is 'large' and the SMs will fill less than halfway, use split_k.
  5258. uint32_t m_tiles = CEIL_DIV(m, pipeline->wg_denoms[0]);
  5259. uint32_t n_tiles = CEIL_DIV(n, pipeline->wg_denoms[1]);
  5260. if (k >= 2048) {
  5261. if (m_tiles * n_tiles <= ctx->device->shader_core_count / 2) {
  5262. split_k = ctx->device->shader_core_count / (m_tiles * n_tiles);
  5263. } else if (m_tiles * n_tiles <= ctx->device->shader_core_count * 2 / 3) {
  5264. split_k = 3;
  5265. }
  5266. // Cap the split at 8x. Unless k is huge this is a lot of overhead.
  5267. split_k = std::min(split_k, 8u);
  5268. // ggml_vk_matmul will align the splits to be a multiple of 256.
  5269. // If this rounded up size would cause the last split to be empty,
  5270. // then reduce the split count.
  5271. while (true) {
  5272. if (split_k == 1) {
  5273. break;
  5274. }
  5275. uint32_t k_split = CEIL_DIV(k, split_k);
  5276. k_split = ROUNDUP_POW2(k_split, 256);
  5277. if (k_split * (split_k - 1) < k) {
  5278. break;
  5279. }
  5280. split_k--;
  5281. }
  5282. }
  5283. }
  5284. return split_k;
  5285. }
  5286. 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) {
  5287. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5288. if (ctx->device->coopmat2) {
  5289. const uint32_t shader_core_count = ctx->device->shader_core_count;
  5290. const uint32_t tiles_l = CEIL_DIV(m, mmp->a_l->wg_denoms[0]) * CEIL_DIV(n, mmp->a_l->wg_denoms[1]);
  5291. const uint32_t tiles_m = CEIL_DIV(m, mmp->a_m->wg_denoms[0]) * CEIL_DIV(n, mmp->a_m->wg_denoms[1]);
  5292. // Use large shader when the N dimension is greater than the medium shader's tile size
  5293. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5294. // Prefer large over medium if either:
  5295. // - medium or large tiles would overfill the GPU
  5296. // - large tiles with a split_k==3 fits in the GPU and medium tiles with split_k==2 does not
  5297. // (medium with split_k==2 is probably better if it fits - more workgroups running and less split_k overhead)
  5298. bool prefer_large = tiles_m > shader_core_count || tiles_l > shader_core_count ||
  5299. // split_k==3 with large tiles likely better than medium tiles with no split_k.
  5300. (tiles_l <= shader_core_count / 3 && tiles_m > shader_core_count / 2);
  5301. 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])) {
  5302. return aligned ? mmp->a_l : mmp->l;
  5303. }
  5304. // Use medium shader when the N dimension is greater than the small shader's tile size
  5305. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5306. if ((ctx->device->mul_mat_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_s[src0_type]) {
  5307. return aligned ? mmp->a_m : mmp->m;
  5308. }
  5309. return aligned ? mmp->a_s : mmp->s;
  5310. }
  5311. 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])) {
  5312. return aligned ? mmp->a_s : mmp->s;
  5313. }
  5314. if ((ctx->device->mul_mat_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_l[src0_type]) {
  5315. return aligned ? mmp->a_m : mmp->m;
  5316. }
  5317. return aligned ? mmp->a_l : mmp->l;
  5318. GGML_UNUSED(src1_type);
  5319. }
  5320. 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) {
  5321. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ", " << ggml_type_name(src1_type) << ")");
  5322. return ggml_vk_guess_matmul_pipeline(ctx, mmp, m, n, true, src0_type, src1_type)->align;
  5323. }
  5324. static void ggml_vk_matmul(
  5325. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5326. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer,
  5327. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5328. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5329. uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3,
  5330. uint32_t padded_n) {
  5331. 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 << ")");
  5332. if (split_k == 1) {
  5333. 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 };
  5334. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d }, pc, { m, n, batch });
  5335. return;
  5336. }
  5337. if (ctx->prealloc_split_k_need_sync) {
  5338. ggml_vk_sync_buffers(ctx, subctx);
  5339. }
  5340. GGML_ASSERT(batch_stride_d == m * n);
  5341. // Round the split size up to a multiple of 256 (k-quant alignment)
  5342. uint32_t k_split = CEIL_DIV(k, split_k);
  5343. k_split = ROUNDUP_POW2(k_split, 256);
  5344. 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 };
  5345. // Make sure enough workgroups get assigned for split k to work
  5346. 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 });
  5347. ggml_vk_sync_buffers(ctx, subctx);
  5348. const std::array<uint32_t, 2> pc2 = { (uint32_t)(m * n * batch), split_k };
  5349. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_split_k_reduce, { split_k_buffer, d }, pc2, { m * n * batch, 1, 1 });
  5350. ctx->prealloc_split_k_need_sync = true;
  5351. }
  5352. 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) {
  5353. VK_LOG_DEBUG("ggml_vk_guess_matmul_id_pipeline(" << m << ", " << n << ", " << aligned << ", " << ggml_type_name(src0_type) << ")");
  5354. if (ctx->device->coopmat2) {
  5355. // Use large shader when the N dimension is greater than the medium shader's tile size
  5356. uint32_t crossover_large = mmp->m->wg_denoms[1];
  5357. 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])) {
  5358. return aligned ? mmp->a_l : mmp->l;
  5359. }
  5360. // Use medium shader when the N dimension is greater than the small shader's tile size
  5361. uint32_t crossover_medium = mmp->s->wg_denoms[1];
  5362. if ((ctx->device->mul_mat_id_m[src0_type] && (n > crossover_medium)) || !ctx->device->mul_mat_id_s[src0_type]) {
  5363. return aligned ? mmp->a_m : mmp->m;
  5364. }
  5365. return aligned ? mmp->a_s : mmp->s;
  5366. }
  5367. 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])) {
  5368. return aligned ? mmp->a_s : mmp->s;
  5369. }
  5370. if ((ctx->device->mul_mat_id_m[src0_type] && (m <= 64 || n <= 64)) || !ctx->device->mul_mat_id_l[src0_type]) {
  5371. return aligned ? mmp->a_m : mmp->m;
  5372. }
  5373. return aligned ? mmp->a_l : mmp->l;
  5374. }
  5375. 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) {
  5376. VK_LOG_DEBUG("ggml_vk_guess_matmul_pipeline_align(" << m << ", " << n << ", " << ggml_type_name(src0_type) << ")");
  5377. return ggml_vk_guess_matmul_id_pipeline(ctx, mmp, m, n, true, src0_type)->align;
  5378. }
  5379. static void ggml_vk_matmul_id(
  5380. ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline,
  5381. vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& ids,
  5382. uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d,
  5383. uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d,
  5384. uint32_t n_as, uint32_t nei0, uint32_t nei1, uint32_t nbi1, uint32_t ne11,
  5385. uint32_t padded_n) {
  5386. 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 << "), " <<
  5387. "m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", " <<
  5388. "batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", " <<
  5389. "n_as: " << n_as << ", nei0: " << nei0 << ", nei1: " << nei1 << ", nbi1: " << nbi1 << ", ne11: " << ne11 << ")");
  5390. 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,
  5391. nei0, nei1, nbi1, ne11, padded_n };
  5392. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, ids }, pc, { m, nei1, n_as });
  5393. }
  5394. static bool ggml_vk_dim01_contiguous(const ggml_tensor * tensor) {
  5395. return
  5396. tensor->nb[0] == ggml_type_size(tensor->type) &&
  5397. tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
  5398. (tensor->ne[3] == 1 || tensor->nb[3] == tensor->nb[2]*tensor->ne[2]);
  5399. }
  5400. static vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src, const ggml_tensor * dst, ggml_type to) {
  5401. // Choose "contiguous copy" shader if src/dst are contiguous
  5402. bool contig = ggml_is_contiguous(src) && (!dst || ggml_is_contiguous(dst));
  5403. // Use optimized "transpose" shader if src dim1 is the innermost dimension.
  5404. bool transpose = dst && src->nb[1] == ggml_type_size(to) && ggml_are_same_shape(dst, src);
  5405. if (transpose && src->type == to) {
  5406. if (ggml_type_size(to) == 4) {
  5407. return ctx->device->pipeline_cpy_transpose_32;
  5408. } else if (ggml_type_size(to) == 2) {
  5409. return ctx->device->pipeline_cpy_transpose_16;
  5410. }
  5411. }
  5412. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F32) {
  5413. if (contig) {
  5414. return ctx->device->pipeline_contig_cpy_f32_f32;
  5415. } else {
  5416. return ctx->device->pipeline_cpy_f32_f32;
  5417. }
  5418. }
  5419. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_F16) {
  5420. if (contig) {
  5421. return ctx->device->pipeline_contig_cpy_f32_f16;
  5422. } else {
  5423. return ctx->device->pipeline_cpy_f32_f16;
  5424. }
  5425. }
  5426. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F16) {
  5427. if (contig) {
  5428. return ctx->device->pipeline_contig_cpy_f16_f16;
  5429. } else {
  5430. return ctx->device->pipeline_cpy_f16_f16;
  5431. }
  5432. }
  5433. if (src->type == GGML_TYPE_F16 && to == GGML_TYPE_F32) {
  5434. if (contig) {
  5435. return ctx->device->pipeline_contig_cpy_f16_f32;
  5436. } else {
  5437. return ctx->device->pipeline_cpy_f16_f32;
  5438. }
  5439. }
  5440. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_BF16) {
  5441. if (contig) {
  5442. return ctx->device->pipeline_contig_cpy_f32_bf16;
  5443. } else {
  5444. return ctx->device->pipeline_cpy_f32_bf16;
  5445. }
  5446. }
  5447. if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
  5448. if (contig) {
  5449. return ctx->device->pipeline_contig_cpy_f32_i32;
  5450. } else {
  5451. return ctx->device->pipeline_cpy_f32_i32;
  5452. }
  5453. }
  5454. if (src->type == GGML_TYPE_I32 && to == GGML_TYPE_F32) {
  5455. if (contig) {
  5456. return ctx->device->pipeline_contig_cpy_i32_f32;
  5457. } else {
  5458. return ctx->device->pipeline_cpy_i32_f32;
  5459. }
  5460. }
  5461. if (src->type == GGML_TYPE_F32) {
  5462. switch (to) {
  5463. case GGML_TYPE_Q4_0:
  5464. case GGML_TYPE_Q4_1:
  5465. case GGML_TYPE_Q5_0:
  5466. case GGML_TYPE_Q5_1:
  5467. case GGML_TYPE_Q8_0:
  5468. case GGML_TYPE_IQ4_NL:
  5469. return ctx->device->pipeline_cpy_f32_quant[to];
  5470. default:
  5471. break;
  5472. }
  5473. }
  5474. if (to == GGML_TYPE_F32) {
  5475. switch (src->type) {
  5476. case GGML_TYPE_Q4_0:
  5477. case GGML_TYPE_Q4_1:
  5478. case GGML_TYPE_Q5_0:
  5479. case GGML_TYPE_Q5_1:
  5480. case GGML_TYPE_Q8_0:
  5481. case GGML_TYPE_IQ4_NL:
  5482. return ctx->device->pipeline_cpy_quant_f32[src->type];
  5483. default:
  5484. break;
  5485. }
  5486. }
  5487. if (src->type == to) {
  5488. // Copy two or four bytes at a time, depending on block size.
  5489. // For quantized types, we scale by block size/type size. But
  5490. // this path is also used for bf16->bf16 for example, where the
  5491. // type size must be exactly 2 or 4.
  5492. GGML_ASSERT(ggml_is_quantized(to) || ggml_type_size(src->type) == 2 || ggml_type_size(src->type) == 4);
  5493. if ((ggml_type_size(src->type) % 4) == 0) {
  5494. if (contig) {
  5495. return ctx->device->pipeline_contig_cpy_f32_f32;
  5496. } else {
  5497. return ctx->device->pipeline_cpy_f32_f32;
  5498. }
  5499. } else {
  5500. if (contig) {
  5501. return ctx->device->pipeline_contig_cpy_f16_f16;
  5502. } else {
  5503. return ctx->device->pipeline_cpy_f16_f16;
  5504. }
  5505. }
  5506. }
  5507. std::cerr << "Missing CPY op for types: " << ggml_type_name(src->type) << " " << ggml_type_name(to) << std::endl;
  5508. GGML_ABORT("fatal error");
  5509. }
  5510. static void ggml_vk_cpy_to_contiguous(ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline pipeline, const ggml_tensor * tensor, const vk_subbuffer & in, const vk_subbuffer & out) {
  5511. 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] << "), ";
  5512. std::cerr << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ")");
  5513. const int tensor_type_size = ggml_type_size(tensor->type);
  5514. const uint32_t ne = ggml_nelements(tensor);
  5515. std::array<uint32_t, 3> elements;
  5516. if (ne > 262144) {
  5517. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  5518. } else if (ne > 512) {
  5519. elements = { 512, CEIL_DIV(ne, 512), 1 };
  5520. } else {
  5521. elements = { ne, 1, 1 };
  5522. }
  5523. vk_op_unary_push_constants pc = {
  5524. (uint32_t)ne,
  5525. (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,
  5526. (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]),
  5527. 0,
  5528. 0.0f, 0.0f,
  5529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  5530. };
  5531. init_pushconst_fastdiv(pc);
  5532. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, pc, elements);
  5533. ggml_vk_sync_buffers(ctx, subctx);
  5534. }
  5535. static vk_pipeline ggml_vk_get_quantize_pipeline(ggml_backend_vk_context * ctx, ggml_type type) {
  5536. switch(type) {
  5537. case GGML_TYPE_Q8_1:
  5538. return ctx->device->pipeline_quantize_q8_1_x4;
  5539. default:
  5540. std::cerr << "Missing quantize pipeline for type: " << ggml_type_name(type) << std::endl;
  5541. GGML_ABORT("fatal error");
  5542. }
  5543. }
  5544. static void ggml_vk_quantize_q8_1(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_subbuffer & in, const vk_subbuffer & out, uint32_t ne) {
  5545. VK_LOG_DEBUG("ggml_vk_quantize_q8_1(" << "buffer in size=" << in.buffer->size << ", buffer out size=" << out.buffer->size << ", " << ne << ")");
  5546. vk_pipeline pipeline = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5547. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { in, out }, std::array<uint32_t, 1>{ne}, { ne, 1, 1 });
  5548. ggml_vk_sync_buffers(ctx, subctx);
  5549. }
  5550. static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool disable_split_k) {
  5551. 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];
  5552. 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];
  5553. 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];
  5554. std::cerr << "))");
  5555. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5556. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5557. const uint64_t ne00 = src0->ne[0];
  5558. const uint64_t ne01 = src0->ne[1];
  5559. const uint64_t ne02 = src0->ne[2];
  5560. const uint64_t ne03 = src0->ne[3];
  5561. const uint64_t ne10 = src1->ne[0];
  5562. const uint64_t ne11 = src1->ne[1];
  5563. const uint64_t ne12 = src1->ne[2];
  5564. const uint64_t ne13 = src1->ne[3];
  5565. const uint64_t ne21 = dst->ne[1];
  5566. const uint32_t stride_d = dst->nb[1] / ggml_type_size(dst->type);
  5567. const uint32_t stride_batch_d = stride_d*ne21;
  5568. const uint64_t r2 = ne12 / ne02;
  5569. const uint64_t r3 = ne13 / ne03;
  5570. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  5571. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  5572. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  5573. vk_buffer d_Qx = nullptr;
  5574. size_t qx_buf_offset = 0;
  5575. vk_buffer d_Qy = nullptr;
  5576. size_t qy_buf_offset = 0;
  5577. bool src0_uma = false;
  5578. bool src1_uma = false;
  5579. if (ctx->device->uma) {
  5580. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  5581. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  5582. src0_uma = d_Qx != nullptr;
  5583. src1_uma = d_Qy != nullptr;
  5584. }
  5585. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  5586. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  5587. !ggml_vk_dim01_contiguous(src0);
  5588. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  5589. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  5590. !ggml_vk_dim01_contiguous(src1);
  5591. // If src0 is BF16, try to use a BF16 x BF16 multiply
  5592. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  5593. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  5594. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  5595. // Check for mmq first
  5596. 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;
  5597. if (mmp == nullptr) {
  5598. // Fall back to f16 dequant mul mat
  5599. mmp = ggml_vk_get_mul_mat_mat_pipeline(ctx, src0->type, y_non_contig ? f16_type : src1->type, (ggml_prec)dst->op_params[0]);
  5600. quantize_y = false;
  5601. }
  5602. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  5603. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  5604. if (qx_needs_dequant) {
  5605. // Fall back to dequant + f16 mulmat
  5606. 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]);
  5607. }
  5608. // Not implemented
  5609. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5610. 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)));
  5611. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8;
  5612. 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));
  5613. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  5614. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) : ne11;
  5615. const uint64_t x_ne = ggml_nelements(src0);
  5616. // 128 elements per Q8_1 x4 block
  5617. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  5618. const uint64_t d_ne = ggml_nelements(dst);
  5619. const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline);
  5620. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  5621. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  5622. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  5623. const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * 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);
  5624. const uint64_t d_sz = sizeof(float) * d_ne;
  5625. vk_pipeline to_fp16_vk_0 = nullptr;
  5626. vk_pipeline to_fp16_vk_1 = nullptr;
  5627. vk_pipeline to_q8_1 = nullptr;
  5628. if (x_non_contig) {
  5629. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  5630. } else {
  5631. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  5632. }
  5633. if (y_non_contig) {
  5634. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  5635. } else {
  5636. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5637. }
  5638. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5639. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5640. if (quantize_y) {
  5641. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5642. }
  5643. {
  5644. const uint64_t split_k_size = split_k > 1 ? d_sz * split_k : 0;
  5645. if (
  5646. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  5647. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  5648. (split_k > 1 && split_k_size > ctx->device->properties.limits.maxStorageBufferRange)) {
  5649. GGML_ABORT("Requested preallocation size is too large");
  5650. }
  5651. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  5652. ctx->prealloc_size_x = x_sz;
  5653. ggml_vk_preallocate_buffers(ctx, subctx);
  5654. }
  5655. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  5656. ctx->prealloc_size_y = y_sz;
  5657. ggml_vk_preallocate_buffers(ctx, subctx);
  5658. }
  5659. if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) {
  5660. ctx->prealloc_size_split_k = split_k_size;
  5661. ggml_vk_preallocate_buffers(ctx, subctx);
  5662. }
  5663. // Request descriptor sets
  5664. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  5665. if (qx_needs_dequant) {
  5666. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5667. }
  5668. if (qy_needs_dequant) {
  5669. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5670. }
  5671. if (quantize_y) {
  5672. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5673. }
  5674. if (split_k > 1) {
  5675. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1);
  5676. }
  5677. }
  5678. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  5679. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  5680. GGML_ASSERT(d_D != nullptr);
  5681. GGML_ASSERT(d_D->size >= d_buf_offset + d_sz);
  5682. vk_buffer d_X;
  5683. uint64_t x_buf_offset = 0;
  5684. vk_buffer d_Y;
  5685. uint64_t y_buf_offset = 0;
  5686. if (!src0_uma) {
  5687. d_Qx = src0_buf_ctx->dev_buffer;
  5688. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  5689. GGML_ASSERT(d_Qx != nullptr);
  5690. }
  5691. if (!src1_uma) {
  5692. d_Qy = src1_buf_ctx->dev_buffer;
  5693. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  5694. GGML_ASSERT(d_Qy != nullptr);
  5695. }
  5696. if (qx_needs_dequant) {
  5697. d_X = ctx->prealloc_x;
  5698. GGML_ASSERT(d_X->size >= x_sz);
  5699. } else {
  5700. d_X = d_Qx;
  5701. x_buf_offset = qx_buf_offset;
  5702. GGML_ASSERT(qx_sz == x_sz);
  5703. }
  5704. if (qy_needs_dequant) {
  5705. d_Y = ctx->prealloc_y;
  5706. GGML_ASSERT(d_Y->size >= y_sz);
  5707. } else if (quantize_y) {
  5708. d_Y = ctx->prealloc_y;
  5709. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  5710. } else {
  5711. d_Y = d_Qy;
  5712. y_buf_offset = qy_buf_offset;
  5713. GGML_ASSERT(qy_sz == y_sz);
  5714. }
  5715. if (x_non_contig || qx_needs_dequant) {
  5716. if (ctx->prealloc_x_need_sync) {
  5717. ggml_vk_sync_buffers(ctx, subctx);
  5718. }
  5719. }
  5720. if (x_non_contig) {
  5721. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, ggml_vk_subbuffer(ctx, d_Qx, qx_buf_offset), ggml_vk_subbuffer(ctx, d_X, 0));
  5722. } else if (qx_needs_dequant) {
  5723. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  5724. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0, { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)(x_ne), 1, 1});
  5725. ggml_vk_sync_buffers(ctx, subctx);
  5726. }
  5727. if (y_non_contig) {
  5728. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5729. ctx->prealloc_y_last_tensor_used != src1) {
  5730. if (ctx->prealloc_y_need_sync) {
  5731. ggml_vk_sync_buffers(ctx, subctx);
  5732. }
  5733. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0));
  5734. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5735. ctx->prealloc_y_last_tensor_used = src1;
  5736. }
  5737. }
  5738. if (quantize_y) {
  5739. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5740. ctx->prealloc_y_last_tensor_used != src1) {
  5741. if (ctx->prealloc_y_need_sync) {
  5742. ggml_vk_sync_buffers(ctx, subctx);
  5743. }
  5744. ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0), y_ne);
  5745. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5746. ctx->prealloc_y_last_tensor_used = src1;
  5747. }
  5748. }
  5749. uint32_t stride_batch_x = ne00*ne01;
  5750. uint32_t stride_batch_y = ne10*ne11;
  5751. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5752. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5753. }
  5754. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  5755. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5756. }
  5757. // compute
  5758. ggml_vk_matmul(
  5759. ctx, subctx, pipeline,
  5760. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  5761. ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, d_sz * split_k },
  5762. ne01, ne11, ne10,
  5763. ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d,
  5764. split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n
  5765. ); // NOLINT
  5766. if (x_non_contig || qx_needs_dequant) {
  5767. ctx->prealloc_x_need_sync = true;
  5768. }
  5769. if (y_non_contig || quantize_y) {
  5770. ctx->prealloc_y_need_sync = true;
  5771. }
  5772. }
  5773. // Device tuning
  5774. static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_t n, uint32_t k, ggml_type src0_type) {
  5775. if (device->mmvq_mode == 1) {
  5776. return true;
  5777. } else if (device->mmvq_mode == -1) {
  5778. return false;
  5779. }
  5780. // MMVQ is generally good for batches
  5781. if (n > 1) {
  5782. return true;
  5783. }
  5784. switch (device->vendor_id) {
  5785. case VK_VENDOR_ID_NVIDIA:
  5786. switch (src0_type) {
  5787. case GGML_TYPE_Q8_0:
  5788. return device->architecture == vk_device_architecture::NVIDIA_PRE_TURING;
  5789. default:
  5790. return true;
  5791. }
  5792. case VK_VENDOR_ID_AMD:
  5793. switch (src0_type) {
  5794. case GGML_TYPE_Q8_0:
  5795. return device->architecture == vk_device_architecture::AMD_GCN;
  5796. default:
  5797. return true;
  5798. }
  5799. case VK_VENDOR_ID_INTEL:
  5800. switch (src0_type) {
  5801. // From tests on A770 Linux, may need more tuning
  5802. case GGML_TYPE_Q4_0:
  5803. case GGML_TYPE_Q5_1:
  5804. return false;
  5805. default:
  5806. return true;
  5807. }
  5808. default:
  5809. return true;
  5810. }
  5811. GGML_UNUSED(m);
  5812. GGML_UNUSED(k);
  5813. }
  5814. static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  5815. ggml_tensor * dst = cgraph->nodes[node_idx];
  5816. const ggml_tensor * src0 = dst->src[0];
  5817. const ggml_tensor * src1 = dst->src[1];
  5818. 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];
  5819. 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];
  5820. 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];
  5821. std::cerr << ")),)");
  5822. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  5823. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  5824. const uint64_t ne00 = src0->ne[0];
  5825. const uint64_t ne01 = src0->ne[1];
  5826. const uint64_t ne02 = src0->ne[2];
  5827. const uint64_t ne03 = src0->ne[3];
  5828. const uint64_t ne10 = src1->ne[0];
  5829. const uint64_t ne11 = src1->ne[1];
  5830. const uint64_t ne12 = src1->ne[2];
  5831. const uint64_t ne13 = src1->ne[3];
  5832. const uint64_t ne20 = dst->ne[0];
  5833. const uint64_t ne21 = dst->ne[1];
  5834. // const uint64_t ne22 = dst->ne[2];
  5835. // const uint64_t ne23 = dst->ne[3];
  5836. const uint64_t r2 = ne12 / ne02;
  5837. const uint64_t r3 = ne13 / ne03;
  5838. // batch_n indicates that we need to compute a few vector results, and this assumes
  5839. // ne12 and ne13 are 1. It overloads the batch_strides to hold the row strides.
  5840. GGML_ASSERT(ne11 == 1 || ne12 * ne13 == 1);
  5841. bool batch_n = ne11 > 1;
  5842. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  5843. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  5844. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  5845. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && ggml_vk_should_use_mmvq(ctx->device, ne01, ne11, ne10, src0->type);
  5846. vk_pipeline to_fp16_vk_0 = nullptr;
  5847. vk_pipeline to_fp16_vk_1 = nullptr;
  5848. if (x_non_contig) {
  5849. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  5850. }
  5851. if (y_non_contig) {
  5852. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  5853. } else {
  5854. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  5855. }
  5856. // Check for mmq first
  5857. vk_pipeline dmmv = quantize_y ? ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, GGML_TYPE_Q8_1, ne11, ne20, ne00) : nullptr;
  5858. vk_pipeline to_q8_1 = nullptr;
  5859. if (dmmv == nullptr) {
  5860. // Fall back to f16 dequant mul mat
  5861. dmmv = ggml_vk_get_dequantize_mul_mat_vec(ctx, src0->type, src1->type, ne11, ne20, ne00);
  5862. quantize_y = false;
  5863. }
  5864. if (quantize_y) {
  5865. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  5866. }
  5867. const bool qx_needs_dequant = x_non_contig;
  5868. const bool qy_needs_dequant = !quantize_y && ((src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig);
  5869. // Not implemented
  5870. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  5871. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  5872. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  5873. GGML_ASSERT(dmmv != nullptr);
  5874. const uint64_t x_ne = ggml_nelements(src0);
  5875. const uint64_t y_ne = ggml_nelements(src1);
  5876. 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);
  5877. 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;
  5878. const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * ggml_type_size(GGML_TYPE_Q8_1) / ggml_blck_size(GGML_TYPE_Q8_1)) :
  5879. (f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne);
  5880. {
  5881. if (
  5882. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  5883. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  5884. GGML_ABORT("Requested preallocation size is too large");
  5885. }
  5886. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  5887. ctx->prealloc_size_x = x_sz;
  5888. ggml_vk_preallocate_buffers(ctx, subctx);
  5889. }
  5890. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  5891. ctx->prealloc_size_y = y_sz;
  5892. ggml_vk_preallocate_buffers(ctx, subctx);
  5893. }
  5894. // Request descriptor sets
  5895. if (qx_needs_dequant) {
  5896. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  5897. }
  5898. if (qy_needs_dequant) {
  5899. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  5900. }
  5901. if (quantize_y) {
  5902. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  5903. }
  5904. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  5905. }
  5906. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  5907. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  5908. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  5909. vk_subbuffer d_X, d_Y;
  5910. if (qx_needs_dequant) {
  5911. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  5912. } else {
  5913. d_X = d_Qx;
  5914. GGML_ASSERT(qx_sz == x_sz);
  5915. }
  5916. if (qy_needs_dequant || quantize_y) {
  5917. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  5918. } else {
  5919. d_Y = d_Qy;
  5920. }
  5921. if (x_non_contig) {
  5922. if (ctx->prealloc_x_need_sync) {
  5923. ggml_vk_sync_buffers(ctx, subctx);
  5924. }
  5925. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  5926. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  5927. }
  5928. if (y_non_contig) {
  5929. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  5930. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  5931. ctx->prealloc_y_last_tensor_used != src1) {
  5932. if (ctx->prealloc_y_need_sync) {
  5933. ggml_vk_sync_buffers(ctx, subctx);
  5934. }
  5935. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  5936. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  5937. ctx->prealloc_y_last_tensor_used = src1;
  5938. }
  5939. }
  5940. if (quantize_y) {
  5941. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  5942. ctx->prealloc_y_last_tensor_used != src1) {
  5943. if (ctx->prealloc_y_need_sync) {
  5944. ggml_vk_sync_buffers(ctx, subctx);
  5945. }
  5946. ggml_vk_quantize_q8_1(ctx, subctx, d_Qy, d_Y, y_ne);
  5947. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  5948. ctx->prealloc_y_last_tensor_used = src1;
  5949. }
  5950. }
  5951. // For batch_n, the A matrix is the same for each batch, and B/D use the row stride as the batch stride
  5952. uint32_t stride_batch_x = batch_n ? 0 : ne00*ne01;
  5953. uint32_t stride_batch_y = batch_n ? ne10 : (ne10*ne11);
  5954. uint32_t stride_batch_d = batch_n ? ne20 : (ne20*ne21);
  5955. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  5956. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  5957. }
  5958. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  5959. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  5960. }
  5961. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  5962. uint32_t groups_x = ne01;
  5963. uint32_t groups_z = 1;
  5964. if (ne01 > max_groups_x) {
  5965. groups_z = 64;
  5966. groups_x = CEIL_DIV(groups_x, groups_z);
  5967. }
  5968. uint32_t fusion_flags = 0;
  5969. vk_subbuffer d_F0 = d_D;
  5970. if (ctx->num_additional_fused_ops > 0) {
  5971. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  5972. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  5973. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  5974. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  5975. }
  5976. vk_subbuffer d_F1 = d_D;
  5977. if (ctx->num_additional_fused_ops == 2) {
  5978. const ggml_tensor * add = cgraph->nodes[node_idx + 2];
  5979. const ggml_tensor * bias = add->src[0] == cgraph->nodes[node_idx + 1] ? add->src[1] : add->src[0];
  5980. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  5981. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  5982. }
  5983. // compute
  5984. const vk_mat_vec_push_constants pc = {
  5985. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  5986. stride_batch_x, stride_batch_y, stride_batch_d,
  5987. fusion_flags,
  5988. (uint32_t)ne02, (uint32_t)ne12, (uint32_t)r2, (uint32_t)r3,
  5989. };
  5990. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  5991. {
  5992. d_X,
  5993. d_Y,
  5994. d_D,
  5995. d_F0,
  5996. d_F1,
  5997. },
  5998. pc, { groups_x, (uint32_t)(ne12 * ne13), groups_z });
  5999. if (x_non_contig) {
  6000. ctx->prealloc_x_need_sync = true;
  6001. }
  6002. if (y_non_contig || quantize_y) {
  6003. ctx->prealloc_y_need_sync = true;
  6004. }
  6005. }
  6006. static void ggml_vk_mul_mat_vec_p021_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6007. ggml_tensor * dst = cgraph->nodes[node_idx];
  6008. const ggml_tensor * src0 = dst->src[0];
  6009. const ggml_tensor * src1 = dst->src[1];
  6010. 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];
  6011. 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];
  6012. 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];
  6013. std::cerr << "))");
  6014. GGML_ASSERT(ggml_is_permuted(src0) && ggml_is_permuted(src1));
  6015. GGML_ASSERT(src0->nb[0] <= src0->nb[1] && src0->nb[2] <= src0->nb[3]); // NOLINT
  6016. GGML_ASSERT(src1->nb[0] <= src1->nb[1] && src1->nb[2] <= src1->nb[3]); // NOLINT
  6017. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6018. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6019. const uint64_t ne00 = src0->ne[0];
  6020. const uint64_t ne01 = src0->ne[1];
  6021. const uint64_t ne02 = src0->ne[2];
  6022. // const uint64_t ne03 = src0->ne[3];
  6023. //const uint64_t ne10 = src1->ne[0];
  6024. const uint64_t ne11 = src1->ne[1];
  6025. const uint64_t ne12 = src1->ne[2];
  6026. // const uint64_t ne13 = src1->ne[3];
  6027. GGML_ASSERT(ne11 == 1);
  6028. // With grouped query attention there are > 1 Q matrices per K, V matrix.
  6029. uint32_t gqa_ratio = (uint32_t)ne12 / (uint32_t)ne02;
  6030. if (gqa_ratio > 8 || gqa_ratio == 0 || ne12 != ne02 * gqa_ratio) {
  6031. gqa_ratio = 1;
  6032. }
  6033. {
  6034. // Request descriptor sets
  6035. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1], 1);
  6036. }
  6037. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  6038. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6039. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  6040. vk_subbuffer d_F0 = d_D;
  6041. uint32_t fusion_flags = 0;
  6042. if (ctx->num_additional_fused_ops > 0) {
  6043. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6044. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6045. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6046. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6047. }
  6048. vk_subbuffer d_F1 = d_D;
  6049. if (ctx->num_additional_fused_ops > 1) {
  6050. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  6051. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6052. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6053. }
  6054. // compute
  6055. vk_mat_vec_p021_push_constants pc = {
  6056. (uint32_t)ne00, (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne12,
  6057. 0, 0, fusion_flags
  6058. };
  6059. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6060. uint32_t workgroups_z = (uint32_t)ne12;
  6061. // When gqa_ratio > 1, each invocation does multiple rows and we can launch fewer workgroups
  6062. if (gqa_ratio > 1) {
  6063. workgroups_z /= gqa_ratio;
  6064. }
  6065. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_p021_f16_f32[gqa_ratio - 1],
  6066. {
  6067. d_Qx,
  6068. d_Qy,
  6069. d_D,
  6070. d_F0,
  6071. d_F1,
  6072. }, pc, { 1, (uint32_t)ne01, workgroups_z });
  6073. }
  6074. static void ggml_vk_mul_mat_vec_nc_f16_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6075. ggml_tensor * dst = cgraph->nodes[node_idx];
  6076. const ggml_tensor * src0 = dst->src[0];
  6077. const ggml_tensor * src1 = dst->src[1];
  6078. 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];
  6079. 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];
  6080. 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];
  6081. std::cerr << "))");
  6082. GGML_ASSERT(!ggml_is_transposed(src0));
  6083. GGML_ASSERT(!ggml_is_transposed(src1));
  6084. GGML_ASSERT(!ggml_is_permuted(src0));
  6085. GGML_ASSERT(src0->type == GGML_TYPE_F16);
  6086. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  6087. const uint64_t ne00 = src0->ne[0];
  6088. const uint64_t ne01 = src0->ne[1];
  6089. const uint64_t ne02 = src0->ne[2];
  6090. const uint64_t ne03 = src0->ne[3];
  6091. const uint64_t nb01 = src0->nb[1];
  6092. const uint64_t nb02 = src0->nb[2];
  6093. const uint64_t nb12 = src1->nb[2];
  6094. // const uint64_t ne10 = src1->ne[0];
  6095. const uint64_t ne11 = src1->ne[1];
  6096. const uint64_t ne12 = src1->ne[2];
  6097. // const uint64_t ne13 = src1->ne[3];
  6098. const uint32_t nb03 = (uint32_t)(src0->nb[3] / sizeof(ggml_fp16_t));
  6099. const uint32_t nb13 = (uint32_t)(src1->nb[3] / sizeof(float));
  6100. const uint32_t nb23 = (uint32_t)(dst->nb[3] / sizeof(float));
  6101. GGML_ASSERT(ne11 == 1);
  6102. GGML_ASSERT(src0->ne[3] == src1->ne[3]); // checked in supports_op
  6103. const uint32_t row_stride_x = nb01 / sizeof(ggml_fp16_t);
  6104. const uint32_t channel_stride_x = nb02 / sizeof(ggml_fp16_t);
  6105. const uint32_t channel_stride_y = nb12 / sizeof(float);
  6106. {
  6107. // Request descriptor sets
  6108. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32, 1);
  6109. }
  6110. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops], true);
  6111. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6112. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1, true);
  6113. vk_subbuffer d_F0 = d_D;
  6114. uint32_t fusion_flags = 0;
  6115. if (ctx->num_additional_fused_ops > 0) {
  6116. const ggml_tensor * add = cgraph->nodes[node_idx + 1];
  6117. const ggml_tensor * bias = add->src[0] == dst ? add->src[1] : add->src[0];
  6118. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6119. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6120. }
  6121. vk_subbuffer d_F1 = d_D;
  6122. if (ctx->num_additional_fused_ops > 1) {
  6123. const ggml_tensor * bias = cgraph->nodes[node_idx + 2]->src[1];
  6124. d_F1 = ggml_vk_tensor_subbuffer(ctx, bias);
  6125. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
  6126. }
  6127. // compute
  6128. vk_mat_vec_nc_push_constants pc = {
  6129. (uint32_t)ne00, (uint32_t)ne01,
  6130. row_stride_x, channel_stride_x, channel_stride_y,
  6131. (uint32_t)(ne12 / ne02), (uint32_t)ne12,
  6132. 0, 0,
  6133. nb03, nb13, nb23, fusion_flags
  6134. };
  6135. init_pushconst_tensor_offsets(ctx, pc, src0, src1, nullptr, nullptr, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6136. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_mul_mat_vec_nc_f16_f32,
  6137. {
  6138. d_Qx,
  6139. d_Qy,
  6140. d_D,
  6141. d_F0,
  6142. d_F1,
  6143. }, pc, { (uint32_t)ne03, (uint32_t)ne01, (uint32_t)ne12 });
  6144. }
  6145. static void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6146. ggml_tensor * dst = cgraph->nodes[node_idx];
  6147. ggml_tensor * src0 = dst->src[0];
  6148. ggml_tensor * src1 = dst->src[1];
  6149. VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
  6150. // Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases
  6151. // where the M dimension is very large.
  6152. // Split_k doesn't work with M splitting.
  6153. const size_t nbytes = ggml_nbytes(src0);
  6154. const bool needs_split = nbytes > ctx->device->properties.limits.maxStorageBufferRange;
  6155. if (needs_split) {
  6156. // Choose the number of rows that can fit (and divide by two, to allow for any additional offsets)
  6157. const uint32_t M_split = ctx->device->properties.limits.maxStorageBufferRange / (2 * src0->nb[1]);
  6158. uint32_t m_offset = 0;
  6159. while (m_offset < dst->ne[0]) {
  6160. const uint32_t cur_M_size = std::min(M_split, (uint32_t)(dst->ne[0] - m_offset));
  6161. ggml_tensor dst2 = *dst;
  6162. ggml_tensor src02 = *src0;
  6163. dst2.view_src = dst->view_src ? dst->view_src : dst;
  6164. src02.view_src = src0->view_src ? src0->view_src : src0;
  6165. dst2.view_offs += m_offset * dst->nb[0];
  6166. src02.view_offs += m_offset * src0->nb[1];
  6167. dst2.ne[0] = cur_M_size;
  6168. src02.ne[1] = cur_M_size;
  6169. ggml_vk_mul_mat_q_f16(ctx, subctx, &src02, src1, &dst2, true);
  6170. m_offset += cur_M_size;
  6171. }
  6172. } else if (src0->type == GGML_TYPE_F16 && ggml_is_permuted(src0) && ggml_is_permuted(src1) && dst->ne[1] == 1 &&
  6173. // detect 0213 permutation, and batch size of 1
  6174. src0->nb[0] <= src0->nb[2] &&
  6175. src0->nb[2] <= src0->nb[1] &&
  6176. src0->nb[1] <= src0->nb[3] &&
  6177. src1->nb[0] <= src1->nb[2] &&
  6178. src1->nb[2] <= src1->nb[1] &&
  6179. src1->nb[1] <= src1->nb[3] &&
  6180. src0->ne[3] == 1 &&
  6181. src1->ne[3] == 1) {
  6182. ggml_vk_mul_mat_vec_p021_f16_f32(ctx, subctx, cgraph, node_idx);
  6183. } else if (src0->type == GGML_TYPE_F16 && !ggml_is_contiguous(src0) && !ggml_is_transposed(src1) && dst->ne[1] == 1 &&
  6184. !ggml_is_permuted(src0) && !ggml_is_permuted(src1)) {
  6185. ggml_vk_mul_mat_vec_nc_f16_f32(ctx, subctx, cgraph, node_idx);
  6186. // mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
  6187. // when ne12 and ne13 are one.
  6188. } else if ((dst->ne[1] == 1 || (dst->ne[1] <= mul_mat_vec_max_cols && src1->ne[2] * src1->ne[3] == 1)) &&
  6189. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
  6190. ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx);
  6191. } else {
  6192. ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false);
  6193. }
  6194. }
  6195. 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) {
  6196. 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];
  6197. 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];
  6198. 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];
  6199. 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] << "),)");
  6200. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6201. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6202. const uint64_t ne00 = src0->ne[0];
  6203. const uint64_t ne01 = src0->ne[1];
  6204. const uint64_t ne02 = src0->ne[2];
  6205. // const uint64_t ne03 = src0->ne[3];
  6206. const uint64_t ne10 = src1->ne[0];
  6207. const uint64_t ne11 = src1->ne[1];
  6208. const uint64_t ne12 = src1->ne[2];
  6209. const uint64_t ne13 = src1->ne[3];
  6210. const uint64_t nei0 = ids->ne[0];
  6211. const uint64_t nei1 = ids->ne[1];
  6212. const uint32_t nbi1 = ids->nb[1];
  6213. const uint32_t nbi2 = ids->nb[2];
  6214. const uint64_t ne20 = dst->ne[0];
  6215. const uint64_t ne21 = dst->ne[1];
  6216. // const uint64_t ne22 = dst->ne[2];
  6217. // const uint64_t ne23 = dst->ne[3];
  6218. const uint64_t n_as = ne02;
  6219. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  6220. ggml_backend_vk_buffer_context * src0_buf_ctx = (ggml_backend_vk_buffer_context *)src0->buffer->context;
  6221. ggml_backend_vk_buffer_context * src1_buf_ctx = (ggml_backend_vk_buffer_context *)src1->buffer->context;
  6222. ggml_backend_vk_buffer_context * ids_buf_ctx = (ggml_backend_vk_buffer_context *)ids->buffer->context;
  6223. vk_buffer d_Qx = nullptr;
  6224. size_t qx_buf_offset = 0;
  6225. vk_buffer d_Qy = nullptr;
  6226. size_t qy_buf_offset = 0;
  6227. vk_buffer d_ids = nullptr;
  6228. size_t ids_buf_offset = 0;
  6229. bool src0_uma = false;
  6230. bool src1_uma = false;
  6231. bool ids_uma = false;
  6232. if (ctx->device->uma) {
  6233. ggml_vk_host_get(ctx->device, src0->data, d_Qx, qx_buf_offset);
  6234. ggml_vk_host_get(ctx->device, src1->data, d_Qy, qy_buf_offset);
  6235. ggml_vk_host_get(ctx->device, ids->data, d_ids, ids_buf_offset);
  6236. src0_uma = d_Qx != nullptr;
  6237. src1_uma = d_Qy != nullptr;
  6238. ids_uma = d_ids != nullptr;
  6239. }
  6240. // Reformat and convert to fp16 if non-contiguous, or for coopmat2 for better perf
  6241. const bool x_non_contig = (ctx->device->coopmat2 && src0->type == GGML_TYPE_F32) ||
  6242. !ggml_vk_dim01_contiguous(src0);
  6243. const bool y_non_contig = (ctx->device->coopmat2 && src1->type == GGML_TYPE_F32) ||
  6244. (src0->type == GGML_TYPE_BF16 && src1->type != GGML_TYPE_BF16) ||
  6245. !ggml_vk_dim01_contiguous(src1);
  6246. // If src0 is BF16, try to use a BF16 x BF16 multiply
  6247. ggml_type f16_type = src0->type == GGML_TYPE_BF16 ? GGML_TYPE_BF16 : GGML_TYPE_F16;
  6248. const bool y_f32_kernel = src1->type == GGML_TYPE_F32 && !y_non_contig;
  6249. bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0;
  6250. // Check for mmq first
  6251. vk_matmul_pipeline mmp = quantize_y ? ggml_vk_get_mul_mat_mat_id_pipeline(ctx, src0->type, GGML_TYPE_Q8_1, (ggml_prec)dst->op_params[0]) : nullptr;
  6252. if (mmp == nullptr) {
  6253. // Fall back to f16 dequant mul mat
  6254. 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]);
  6255. quantize_y = false;
  6256. }
  6257. const bool qx_needs_dequant = mmp == nullptr || x_non_contig;
  6258. const bool qy_needs_dequant = !quantize_y && ((src1->type != f16_type && !y_f32_kernel) || y_non_contig);
  6259. if (qx_needs_dequant) {
  6260. // Fall back to dequant + f16 mulmat
  6261. 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]);
  6262. }
  6263. // Not implemented
  6264. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6265. const uint32_t kpad = quantize_y ? 0 : ggml_vk_align_size(ne10, ggml_vk_guess_matmul_id_pipeline_align(ctx, mmp, ne01, nei1, qx_needs_dequant ? f16_type : src0->type));
  6266. const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && nei1 > 8;
  6267. vk_pipeline pipeline = ggml_vk_guess_matmul_id_pipeline(ctx, mmp, ne01, nei1, aligned, qx_needs_dequant ? f16_type : src0->type);
  6268. // Reserve extra storage in the N dimension for the Y matrix, so we can avoid bounds-checking
  6269. uint32_t padded_n = qy_needs_dequant ? ROUNDUP_POW2(ne11, pipeline->wg_denoms[1]) :ne11;
  6270. const uint64_t x_ne = ggml_nelements(src0);
  6271. const uint64_t y_ne = padded_n * ne10 * ne12 * ne13;
  6272. const uint64_t d_ne = ggml_nelements(dst);
  6273. const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type);
  6274. const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type);
  6275. const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne;
  6276. const uint64_t y_sz = quantize_y ? (ggml_vk_align_size(y_ne, 128) * 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);
  6277. const uint64_t ids_sz = nbi2;
  6278. const uint64_t d_sz = sizeof(float) * d_ne;
  6279. vk_pipeline to_fp16_vk_0 = nullptr;
  6280. vk_pipeline to_fp16_vk_1 = nullptr;
  6281. vk_pipeline to_q8_1 = nullptr;
  6282. if (x_non_contig) {
  6283. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, f16_type);
  6284. } else {
  6285. to_fp16_vk_0 = ggml_vk_get_to_fp16(ctx, src0->type);
  6286. }
  6287. if (y_non_contig) {
  6288. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, f16_type);
  6289. } else {
  6290. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6291. }
  6292. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6293. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6294. if (quantize_y) {
  6295. to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1);
  6296. }
  6297. {
  6298. if (
  6299. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6300. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6301. GGML_ABORT("Requested preallocation size is too large");
  6302. }
  6303. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6304. ctx->prealloc_size_x = x_sz;
  6305. ggml_vk_preallocate_buffers(ctx, subctx);
  6306. }
  6307. if ((qy_needs_dequant || quantize_y) && ctx->prealloc_size_y < y_sz) {
  6308. ctx->prealloc_size_y = y_sz;
  6309. ggml_vk_preallocate_buffers(ctx, subctx);
  6310. }
  6311. // Request descriptor sets
  6312. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6313. if (qx_needs_dequant) {
  6314. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6315. }
  6316. if (qy_needs_dequant) {
  6317. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6318. }
  6319. if (quantize_y) {
  6320. ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1);
  6321. }
  6322. }
  6323. vk_buffer d_D = dst_buf_ctx->dev_buffer;
  6324. const uint64_t d_buf_offset = vk_tensor_offset(dst) + dst->view_offs;
  6325. GGML_ASSERT(d_D != nullptr);
  6326. vk_buffer d_X;
  6327. uint64_t x_buf_offset = 0;
  6328. vk_buffer d_Y;
  6329. uint64_t y_buf_offset = 0;
  6330. if (!src0_uma) {
  6331. d_Qx = src0_buf_ctx->dev_buffer;
  6332. qx_buf_offset = vk_tensor_offset(src0) + src0->view_offs;
  6333. GGML_ASSERT(d_Qx != nullptr);
  6334. }
  6335. if (!src1_uma) {
  6336. d_Qy = src1_buf_ctx->dev_buffer;
  6337. qy_buf_offset = vk_tensor_offset(src1) + src1->view_offs;
  6338. GGML_ASSERT(d_Qy != nullptr);
  6339. }
  6340. if (!ids_uma) {
  6341. d_ids = ids_buf_ctx->dev_buffer;
  6342. ids_buf_offset = vk_tensor_offset(ids) + ids->view_offs;
  6343. GGML_ASSERT(d_ids != nullptr);
  6344. }
  6345. if (qx_needs_dequant) {
  6346. d_X = ctx->prealloc_x;
  6347. GGML_ASSERT(d_X->size >= x_sz);
  6348. } else {
  6349. d_X = d_Qx;
  6350. x_buf_offset = qx_buf_offset;
  6351. GGML_ASSERT(qx_sz == x_sz);
  6352. }
  6353. if (qy_needs_dequant) {
  6354. d_Y = ctx->prealloc_y;
  6355. GGML_ASSERT(d_Y->size >= y_sz);
  6356. } else if (quantize_y) {
  6357. d_Y = ctx->prealloc_y;
  6358. GGML_ASSERT(d_Y->size >= CEIL_DIV(y_sz, 144) * 144);
  6359. } else {
  6360. d_Y = d_Qy;
  6361. y_buf_offset = qy_buf_offset;
  6362. GGML_ASSERT(qy_sz == y_sz);
  6363. }
  6364. if (x_non_contig || qx_needs_dequant) {
  6365. if (ctx->prealloc_x_need_sync) {
  6366. ggml_vk_sync_buffers(ctx, subctx);
  6367. }
  6368. }
  6369. if (x_non_contig) {
  6370. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, ggml_vk_subbuffer(ctx, d_Qx, qx_buf_offset), ggml_vk_subbuffer(ctx, d_X, 0));
  6371. } else if (qx_needs_dequant) {
  6372. const std::vector<uint32_t> pc = { (uint32_t)ne01, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)(ggml_nelements(src0)) };
  6373. ggml_vk_dispatch_pipeline(ctx, subctx, to_fp16_vk_0,
  6374. { vk_subbuffer{ d_Qx, qx_buf_offset, qx_sz }, vk_subbuffer{ d_X, 0, x_sz } }, pc, { (uint32_t)x_ne, 1, 1});
  6375. ggml_vk_sync_buffers(ctx, subctx);
  6376. }
  6377. if (y_non_contig) {
  6378. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6379. ctx->prealloc_y_last_tensor_used != src1) {
  6380. if (ctx->prealloc_y_need_sync) {
  6381. ggml_vk_sync_buffers(ctx, subctx);
  6382. }
  6383. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0));
  6384. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6385. ctx->prealloc_y_last_tensor_used = src1;
  6386. }
  6387. }
  6388. if (quantize_y) {
  6389. if (ctx->prealloc_y_last_pipeline_used != to_q8_1.get() ||
  6390. ctx->prealloc_y_last_tensor_used != src1) {
  6391. if (ctx->prealloc_y_need_sync) {
  6392. ggml_vk_sync_buffers(ctx, subctx);
  6393. }
  6394. ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, d_Qy, qy_buf_offset), ggml_vk_subbuffer(ctx, d_Y, 0), y_ne);
  6395. ctx->prealloc_y_last_pipeline_used = to_q8_1.get();
  6396. ctx->prealloc_y_last_tensor_used = src1;
  6397. }
  6398. }
  6399. uint32_t stride_batch_x = ne00*ne01;
  6400. uint32_t stride_batch_y = ne10*ne11;
  6401. if (!ggml_vk_dim01_contiguous(src0) && !qx_needs_dequant) {
  6402. stride_batch_x = src0->nb[0] / ggml_type_size(src0->type);
  6403. }
  6404. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant && !quantize_y) {
  6405. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6406. }
  6407. // compute
  6408. ggml_vk_matmul_id(
  6409. ctx, subctx, pipeline,
  6410. { d_X, x_buf_offset, x_sz }, { d_Y, y_buf_offset, y_sz },
  6411. { d_D, d_buf_offset, d_sz }, { d_ids, ids_buf_offset, ids_sz },
  6412. ne01, ne21, ne10, ne10, ne10, ne01,
  6413. stride_batch_x, stride_batch_y, ne20*ne21,
  6414. n_as, nei0, nei1, nbi1 / ggml_type_size(ids->type), ne11, padded_n
  6415. ); // NOLINT
  6416. if (x_non_contig || qx_needs_dequant) {
  6417. ctx->prealloc_x_need_sync = true;
  6418. }
  6419. if (y_non_contig) {
  6420. ctx->prealloc_y_need_sync = true;
  6421. }
  6422. }
  6423. static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6424. ggml_tensor * dst = cgraph->nodes[node_idx];
  6425. ggml_tensor * src0 = dst->src[0];
  6426. ggml_tensor * src1 = dst->src[1];
  6427. ggml_tensor * ids = dst->src[2];
  6428. 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];
  6429. 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];
  6430. 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];
  6431. 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];
  6432. std::cerr << "))");
  6433. GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
  6434. GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
  6435. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  6436. const uint64_t ne00 = src0->ne[0];
  6437. const uint64_t ne01 = src0->ne[1];
  6438. // const uint64_t ne02 = src0->ne[2];
  6439. // const uint64_t ne03 = src0->ne[3];
  6440. const uint64_t ne10 = src1->ne[0];
  6441. const uint64_t ne11 = src1->ne[1];
  6442. // const uint64_t ne12 = src1->ne[2];
  6443. // const uint64_t ne13 = src1->ne[3];
  6444. const uint64_t nei0 = ids->ne[0];
  6445. const uint64_t nei1 = ids->ne[1];
  6446. GGML_ASSERT(nei1 == 1);
  6447. const uint64_t ne20 = dst->ne[0];
  6448. const uint64_t ne21 = dst->ne[1];
  6449. // const uint64_t ne22 = dst->ne[2];
  6450. // const uint64_t ne23 = dst->ne[3];
  6451. const bool x_non_contig = !ggml_vk_dim01_contiguous(src0);
  6452. const bool y_non_contig = !ggml_vk_dim01_contiguous(src1);
  6453. const bool f16_f32_kernel = src1->type == GGML_TYPE_F32;
  6454. const bool qx_needs_dequant = x_non_contig;
  6455. const bool qy_needs_dequant = (src1->type != GGML_TYPE_F16 && !f16_f32_kernel) || y_non_contig;
  6456. // Not implemented
  6457. GGML_ASSERT(y_non_contig || !qy_needs_dequant); // NOLINT
  6458. const uint64_t x_ne = ggml_nelements(src0);
  6459. const uint64_t y_ne = ggml_nelements(src1);
  6460. 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);
  6461. 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;
  6462. const uint64_t y_sz = f16_f32_kernel ? sizeof(float) * y_ne : sizeof(ggml_fp16_t) * y_ne;
  6463. vk_pipeline to_fp16_vk_0 = nullptr;
  6464. vk_pipeline to_fp16_vk_1 = nullptr;
  6465. if (x_non_contig) {
  6466. to_fp16_vk_0 = ggml_vk_get_cpy_pipeline(ctx, src0, nullptr, src0->type);
  6467. }
  6468. if (y_non_contig) {
  6469. to_fp16_vk_1 = ggml_vk_get_cpy_pipeline(ctx, src1, nullptr, src1->type);
  6470. } else {
  6471. to_fp16_vk_1 = ggml_vk_get_to_fp16(ctx, src1->type);
  6472. }
  6473. vk_pipeline dmmv = ggml_vk_get_dequantize_mul_mat_vec_id(ctx, src0->type, src1->type);
  6474. GGML_ASSERT(!qx_needs_dequant || to_fp16_vk_0 != nullptr); // NOLINT
  6475. GGML_ASSERT(!qy_needs_dequant || to_fp16_vk_1 != nullptr); // NOLINT
  6476. GGML_ASSERT(dmmv != nullptr);
  6477. {
  6478. if (
  6479. (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) ||
  6480. (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange)) {
  6481. GGML_ABORT("Requested preallocation size is too large");
  6482. }
  6483. if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) {
  6484. ctx->prealloc_size_x = x_sz;
  6485. ggml_vk_preallocate_buffers(ctx, subctx);
  6486. }
  6487. if (qy_needs_dequant && ctx->prealloc_size_y < y_sz) {
  6488. ctx->prealloc_size_y = y_sz;
  6489. ggml_vk_preallocate_buffers(ctx, subctx);
  6490. }
  6491. // Request descriptor sets
  6492. if (qx_needs_dequant) {
  6493. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_0, 1);
  6494. }
  6495. if (qy_needs_dequant) {
  6496. ggml_pipeline_request_descriptor_sets(ctx, to_fp16_vk_1, 1);
  6497. }
  6498. ggml_pipeline_request_descriptor_sets(ctx, dmmv, 1);
  6499. }
  6500. vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, cgraph->nodes[node_idx + ctx->num_additional_fused_ops]);
  6501. vk_subbuffer d_Qx = ggml_vk_tensor_subbuffer(ctx, src0);
  6502. vk_subbuffer d_Qy = ggml_vk_tensor_subbuffer(ctx, src1);
  6503. vk_subbuffer d_ids = ggml_vk_tensor_subbuffer(ctx, ids);
  6504. vk_subbuffer d_F0 = d_D;
  6505. vk_subbuffer d_X, d_Y;
  6506. if (qx_needs_dequant) {
  6507. d_X = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  6508. } else {
  6509. d_X = d_Qx;
  6510. }
  6511. if (qy_needs_dequant) {
  6512. d_Y = { ctx->prealloc_y, 0, ctx->prealloc_y->size };
  6513. } else {
  6514. d_Y = d_Qy;
  6515. }
  6516. if (x_non_contig) {
  6517. if (ctx->prealloc_x_need_sync) {
  6518. ggml_vk_sync_buffers(ctx, subctx);
  6519. }
  6520. }
  6521. if (x_non_contig) {
  6522. GGML_ASSERT(x_sz == ggml_vk_align_size(ggml_type_size(src0->type) * x_ne, ctx->device->properties.limits.minStorageBufferOffsetAlignment));
  6523. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_0, src0, d_Qx, d_X);
  6524. }
  6525. if (y_non_contig) {
  6526. GGML_ASSERT(y_sz == ggml_type_size(src1->type) * y_ne);
  6527. if (ctx->prealloc_y_last_pipeline_used != to_fp16_vk_1.get() ||
  6528. ctx->prealloc_y_last_tensor_used != src1) {
  6529. if (ctx->prealloc_y_need_sync) {
  6530. ggml_vk_sync_buffers(ctx, subctx);
  6531. }
  6532. ggml_vk_cpy_to_contiguous(ctx, subctx, to_fp16_vk_1, src1, d_Qy, d_Y);
  6533. ctx->prealloc_y_last_pipeline_used = to_fp16_vk_1.get();
  6534. ctx->prealloc_y_last_tensor_used = src1;
  6535. }
  6536. }
  6537. uint32_t stride_batch_y = ne10*ne11;
  6538. if (!ggml_vk_dim01_contiguous(src1) && !qy_needs_dequant) {
  6539. stride_batch_y = src1->nb[0] / ggml_type_size(src1->type);
  6540. }
  6541. const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0];
  6542. uint32_t groups_x = ne01;
  6543. uint32_t groups_z = 1;
  6544. if (ne01 > max_groups_x) {
  6545. groups_z = 64;
  6546. groups_x = CEIL_DIV(groups_x, groups_z);
  6547. }
  6548. uint32_t fusion_flags = 0;
  6549. if (ctx->num_additional_fused_ops > 0) {
  6550. const ggml_tensor * bias = cgraph->nodes[node_idx + 1]->src[1];
  6551. d_F0 = ggml_vk_tensor_subbuffer(ctx, bias);
  6552. if (cgraph->nodes[node_idx + 1]->op == GGML_OP_MUL) {
  6553. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE0;
  6554. } else {
  6555. GGML_ASSERT(cgraph->nodes[node_idx + 1]->op == GGML_OP_ADD_ID);
  6556. fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS0;
  6557. }
  6558. }
  6559. vk_subbuffer d_F1 = d_D;
  6560. if (ctx->num_additional_fused_ops > 1) {
  6561. const ggml_tensor * scale = cgraph->nodes[node_idx + 2]->src[1];
  6562. d_F1 = ggml_vk_tensor_subbuffer(ctx, scale);
  6563. fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE1;
  6564. }
  6565. // compute
  6566. const vk_mat_vec_id_push_constants pc = {
  6567. (uint32_t)ne00, (uint32_t)ne10, (uint32_t)ne10, (uint32_t)ne01,
  6568. (uint32_t)(ne00 * ne01), stride_batch_y, (uint32_t)(ne20 * ne21),
  6569. fusion_flags,
  6570. (uint32_t)nei0, (uint32_t)ne11,
  6571. };
  6572. ggml_vk_dispatch_pipeline(ctx, subctx, dmmv,
  6573. {
  6574. d_X,
  6575. d_Y,
  6576. d_D,
  6577. d_F0,
  6578. d_F1,
  6579. d_ids,
  6580. },
  6581. pc, { groups_x, (uint32_t)nei0, groups_z });
  6582. if (x_non_contig) {
  6583. ctx->prealloc_x_need_sync = true;
  6584. }
  6585. if (y_non_contig) {
  6586. ctx->prealloc_y_need_sync = true;
  6587. }
  6588. }
  6589. static bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx) {
  6590. ggml_tensor * dst = cgraph->nodes[node_idx];
  6591. ggml_tensor * src0 = dst->src[0];
  6592. ggml_tensor * src2 = dst->src[2];
  6593. return src2->ne[1] == 1 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type));
  6594. }
  6595. static void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx) {
  6596. ggml_tensor * dst = cgraph->nodes[node_idx];
  6597. ggml_tensor * src0 = dst->src[0];
  6598. ggml_tensor * src1 = dst->src[1];
  6599. ggml_tensor * src2 = dst->src[2];
  6600. VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
  6601. if (ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  6602. ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, cgraph, node_idx);
  6603. } else {
  6604. ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst);
  6605. }
  6606. }
  6607. static bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv) {
  6608. // Needs to be kept up to date on shader changes
  6609. GGML_UNUSED(hsv);
  6610. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6611. const uint32_t Br = get_fa_scalar_num_large_rows(hsv);
  6612. const uint32_t Bc = scalar_flash_attention_Bc;
  6613. const uint32_t tmpsh = wg_size * sizeof(float);
  6614. const uint32_t tmpshv4 = wg_size * 4 * sizeof(float);
  6615. const uint32_t masksh = Bc * Br * sizeof(float);
  6616. const uint32_t Qf = Br * (hsk / 4 + 2) * 4 * sizeof(float);
  6617. const uint32_t total_size = tmpsh + tmpshv4 + masksh + Qf;
  6618. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6619. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", total_size=" << total_size << ", supported=" << supported);
  6620. return supported;
  6621. }
  6622. static bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const uint32_t hsk, uint32_t hsv, bool f32acc) {
  6623. // Needs to be kept up to date on shader changes
  6624. GGML_UNUSED(hsv);
  6625. const uint32_t wg_size = scalar_flash_attention_workgroup_size;
  6626. const uint32_t Br = coopmat1_flash_attention_num_large_rows;
  6627. const uint32_t Bc = scalar_flash_attention_Bc;
  6628. const uint32_t hsk_pad = ROUNDUP_POW2(hsk, 16);
  6629. const uint32_t acctype = f32acc ? 4 : 2;
  6630. const uint32_t f16vec4 = 8;
  6631. const uint32_t tmpsh = wg_size * sizeof(float);
  6632. const uint32_t tmpshv4 = wg_size * 4 * acctype;
  6633. const uint32_t qstride = hsk_pad / 4 + 2;
  6634. const uint32_t Qf = Br * qstride * f16vec4;
  6635. const uint32_t sfshstride = (hsk <= 128) ? (Br + 8) : Br;
  6636. const uint32_t sfsh = Bc * sfshstride * acctype;
  6637. const uint32_t kshstride = hsk_pad / 4 + 2;
  6638. const uint32_t ksh = Bc * kshstride * f16vec4;
  6639. const uint32_t slope = Br * sizeof(float);
  6640. const uint32_t total_size = tmpsh + tmpshv4 + Qf + sfsh + ksh + slope;
  6641. const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize;
  6642. VK_LOG_DEBUG("ggml_vk_flash_attn_coopmat_shmem_support(HSK=" << hsk << ", HSV=" << hsv << ", f32acc=" << f32acc << ", total_size=" << total_size << ", supported=" << supported);
  6643. return supported;
  6644. }
  6645. 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) {
  6646. 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];
  6647. 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];
  6648. 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];
  6649. 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];
  6650. if (sinks) {
  6651. 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];
  6652. }
  6653. std::cerr << "))");
  6654. GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
  6655. GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
  6656. GGML_TENSOR_LOCALS(int64_t, nek, k, ne)
  6657. GGML_TENSOR_LOCALS(size_t, nbk, k, nb)
  6658. GGML_TENSOR_LOCALS(int64_t, nev, v, ne)
  6659. GGML_TENSOR_LOCALS(size_t, nbv, v, nb)
  6660. GGML_TENSOR_LOCALS(int64_t, ne, dst, ne)
  6661. GGML_TENSOR_LOCALS(size_t, nb, dst, nb)
  6662. const uint32_t nem1 = mask ? mask->ne[1] : 0;
  6663. const uint32_t nem2 = mask ? mask->ne[2] : 0;
  6664. const uint32_t nem3 = mask ? mask->ne[3] : 0;
  6665. const uint32_t HSK = nek0;
  6666. const uint32_t HSV = nev0;
  6667. uint32_t N = neq1;
  6668. const uint32_t KV = nek1;
  6669. GGML_ASSERT(ne0 == HSV);
  6670. GGML_ASSERT(ne2 == N);
  6671. // input tensor rows must be contiguous
  6672. GGML_ASSERT(nbq0 == ggml_type_size(q->type));
  6673. GGML_ASSERT(nbk0 == ggml_type_size(k->type));
  6674. GGML_ASSERT(nbv0 == ggml_type_size(v->type));
  6675. GGML_ASSERT(neq0 == HSK);
  6676. GGML_ASSERT(neq1 == N);
  6677. GGML_ASSERT(nev1 == nek1);
  6678. // dst cannot be transposed or permuted
  6679. GGML_ASSERT(nb0 == sizeof(float));
  6680. GGML_ASSERT(nb0 <= nb1);
  6681. GGML_ASSERT(nb1 <= nb2);
  6682. GGML_ASSERT(nb2 <= nb3);
  6683. assert(dst->type == GGML_TYPE_F32);
  6684. assert(q->type == GGML_TYPE_F32);
  6685. assert(k->type == v->type);
  6686. FaCodePath path = ctx->device->coopmat2 ? FA_COOPMAT2 :
  6687. ctx->device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR;
  6688. if (path == FA_COOPMAT1) {
  6689. const bool coopmat_shape_supported = (dst->op_params[3] == GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f32acc) ||
  6690. (dst->op_params[3] != GGML_PREC_F32 && ctx->device->coopmat_support_16x16x16_f16acc);
  6691. const bool coopmat_shmem_supported = ggml_vk_flash_attn_coopmat_shmem_support(ctx->device, HSK, HSV, dst->op_params[3] == GGML_PREC_F32);
  6692. if (!coopmat_shape_supported || !coopmat_shmem_supported) {
  6693. path = FA_SCALAR;
  6694. }
  6695. }
  6696. uint32_t gqa_ratio = 1;
  6697. uint32_t qk_ratio = neq2 / nek2;
  6698. uint32_t workgroups_x = (uint32_t)neq1;
  6699. uint32_t workgroups_y = (uint32_t)neq2;
  6700. uint32_t workgroups_z = (uint32_t)neq3;
  6701. // For scalar/coopmat1 FA, we can use the "large" size to accommodate qga.
  6702. // For coopmat2 FA, we always use the small size (which is still pretty large for gqa).
  6703. uint32_t max_gqa;
  6704. switch (path) {
  6705. case FA_SCALAR:
  6706. case FA_COOPMAT1:
  6707. // We may switch from coopmat1 to scalar, so use the scalar limit for both
  6708. max_gqa = get_fa_scalar_num_large_rows(HSV);
  6709. break;
  6710. case FA_COOPMAT2:
  6711. max_gqa = get_fa_num_small_rows(FA_COOPMAT2);
  6712. break;
  6713. default:
  6714. GGML_ASSERT(0);
  6715. }
  6716. if (N == 1 && qk_ratio > 1 && qk_ratio <= max_gqa &&
  6717. qk_ratio * nek2 == neq2 && nek2 == nev2 && nem2 <= 1) {
  6718. // grouped query attention - make the N dimension equal to gqa_ratio, reduce
  6719. // workgroups proportionally in y dimension. The shader will detect gqa_ratio > 1
  6720. // and change addressing calculations to index Q's dimension 2.
  6721. gqa_ratio = qk_ratio;
  6722. N = gqa_ratio;
  6723. workgroups_y /= N;
  6724. }
  6725. bool small_rows = N <= get_fa_num_small_rows(path);
  6726. // coopmat1 does not actually support "small rows" (it needs 16 rows).
  6727. // So use scalar instead.
  6728. if (small_rows && path == FA_COOPMAT1) {
  6729. path = FA_SCALAR;
  6730. }
  6731. // scalar is faster than coopmat2 when N==1
  6732. if (N == 1 && path == FA_COOPMAT2) {
  6733. path = FA_SCALAR;
  6734. }
  6735. // with large hsk/hsv, scalar path may need to use small_rows to fit in shared memory
  6736. if (path == FA_SCALAR &&
  6737. !ggml_vk_flash_attn_scalar_shmem_support(ctx->device, HSK, HSV)) {
  6738. small_rows = true;
  6739. }
  6740. const uint32_t q_stride = (uint32_t)(nbq1 / ggml_type_size(q->type));
  6741. uint32_t k_stride = (uint32_t)(nbk1 / ggml_type_size(k->type));
  6742. uint32_t v_stride = (uint32_t)(nbv1 / ggml_type_size(v->type));
  6743. // For F32, the shader treats it as a block of size 4 (for vec4 loads)
  6744. if (k->type == GGML_TYPE_F32) {
  6745. k_stride /= 4;
  6746. }
  6747. if (v->type == GGML_TYPE_F32) {
  6748. v_stride /= 4;
  6749. }
  6750. uint32_t alignment = fa_align(path, HSK, HSV, k->type, small_rows);
  6751. bool aligned = (KV % alignment) == 0 &&
  6752. // the "aligned" shader variant will forcibly align strides, for performance
  6753. (q_stride & 7) == 0 && (k_stride & 7) == 0 && (v_stride & 7) == 0;
  6754. // Need to use the coopmat2 variant that clamps loads when HSK/HSV aren't sufficiently aligned.
  6755. if (((HSK | HSV) % 16) != 0 && path == FA_COOPMAT2) {
  6756. aligned = false;
  6757. }
  6758. bool f32acc = path == FA_SCALAR || dst->op_params[3] == GGML_PREC_F32;
  6759. vk_fa_pipeline_state fa_pipeline_state(HSK, HSV, small_rows, path, aligned, f32acc);
  6760. vk_pipeline pipeline = nullptr;
  6761. {
  6762. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  6763. auto &pipelines = ctx->device->pipeline_flash_attn_f32_f16[k->type];
  6764. auto it = pipelines.find(fa_pipeline_state);
  6765. if (it != pipelines.end()) {
  6766. pipeline = it->second;
  6767. } else {
  6768. pipelines[fa_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  6769. }
  6770. }
  6771. assert(pipeline);
  6772. uint32_t split_kv = KV;
  6773. uint32_t split_k = 1;
  6774. // Use a placeholder core count if one isn't available. split_k is a big help for perf.
  6775. const uint32_t shader_core_count = ctx->device->shader_core_count ? ctx->device->shader_core_count : 16;
  6776. // Try to use split_k when KV is large enough to be worth the overhead
  6777. if (workgroups_x == 1 && shader_core_count > 0) {
  6778. // Try to run two workgroups per SM.
  6779. split_k = shader_core_count * 2 / (workgroups_y * workgroups_z);
  6780. if (split_k > 1) {
  6781. // Try to evenly split KV into split_k chunks, but it needs to be a multiple
  6782. // of "align", so recompute split_k based on that.
  6783. split_kv = ROUNDUP_POW2(std::max(1u, KV / split_k), alignment);
  6784. split_k = CEIL_DIV(KV, split_kv);
  6785. workgroups_x = split_k;
  6786. }
  6787. }
  6788. // Reserve space for split_k temporaries. For each split x batch, we need to store the O matrix (D x ne1)
  6789. // and the per-row m and L values (ne1 rows). We store all the matrices first, followed by the rows.
  6790. const uint64_t split_k_size = split_k > 1 ? (HSV * ne1 * sizeof(float) + ne1 * sizeof(float) * 2) * split_k * ne3 : 0;
  6791. if (split_k_size > ctx->device->properties.limits.maxStorageBufferRange) {
  6792. GGML_ABORT("Requested preallocation size is too large");
  6793. }
  6794. if (ctx->prealloc_size_split_k < split_k_size) {
  6795. ctx->prealloc_size_split_k = split_k_size;
  6796. ggml_vk_preallocate_buffers(ctx, subctx);
  6797. }
  6798. {
  6799. // Request descriptor sets
  6800. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  6801. if (split_k > 1) {
  6802. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_flash_attn_split_k_reduce, 1);
  6803. }
  6804. }
  6805. float scale = 1.0f;
  6806. float max_bias = 0.0f;
  6807. float logit_softcap = 0.0f;
  6808. memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float));
  6809. memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
  6810. memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));
  6811. if (logit_softcap != 0) {
  6812. scale /= logit_softcap;
  6813. }
  6814. const uint32_t n_head_kv = neq2;
  6815. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  6816. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  6817. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  6818. vk_subbuffer q_buf = ggml_vk_tensor_subbuffer(ctx, q);
  6819. vk_subbuffer k_buf = ggml_vk_tensor_subbuffer(ctx, k);
  6820. vk_subbuffer v_buf = ggml_vk_tensor_subbuffer(ctx, v);
  6821. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  6822. vk_subbuffer mask_buf = mask ? ggml_vk_tensor_subbuffer(ctx, mask) : q_buf;
  6823. vk_subbuffer sinks_buf = sinks ? ggml_vk_tensor_subbuffer(ctx, sinks) : q_buf;
  6824. uint32_t mask_n_head_log2 = ((sinks != nullptr) << 24) | ((mask != nullptr) << 16) | n_head_log2;
  6825. const vk_flash_attn_push_constants pc = { N, KV,
  6826. (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  6827. (uint32_t)neq2, (uint32_t)neq3,
  6828. (uint32_t)nek2, (uint32_t)nek3,
  6829. (uint32_t)nev2, (uint32_t)nev3,
  6830. nem1, nem2, nem3,
  6831. q_stride, (uint32_t)nbq2, (uint32_t)nbq3,
  6832. k_stride, (uint32_t)nbk2, (uint32_t)nbk3,
  6833. v_stride, (uint32_t)nbv2, (uint32_t)nbv3,
  6834. scale, max_bias, logit_softcap,
  6835. mask_n_head_log2, m0, m1,
  6836. gqa_ratio, split_kv, split_k };
  6837. if (split_k > 1) {
  6838. if (ctx->prealloc_split_k_need_sync) {
  6839. ggml_vk_sync_buffers(ctx, subctx);
  6840. }
  6841. vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
  6842. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6843. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf},
  6844. // We only use split_k when group query attention is enabled, which means
  6845. // there's no more than one tile of rows (i.e. workgroups_x would have been
  6846. // one). We reuse workgroups_x to mean the number of splits, so we need to
  6847. // cancel out the divide by wg_denoms[0].
  6848. pc, { workgroups_x * pipeline->wg_denoms[0], workgroups_y, workgroups_z });
  6849. ggml_vk_sync_buffers(ctx, subctx);
  6850. const std::array<uint32_t, 5> pc2 = { HSV, (uint32_t)ne1, (uint32_t)ne3, split_k, (sinks != nullptr) };
  6851. ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_flash_attn_split_k_reduce,
  6852. {split_k_buf, sinks_buf, dst_buf},
  6853. pc2, { (uint32_t)ne1, HSV, (uint32_t)ne3 });
  6854. ctx->prealloc_split_k_need_sync = true;
  6855. } else {
  6856. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  6857. {q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf},
  6858. pc, { workgroups_x, workgroups_y, workgroups_z });
  6859. }
  6860. }
  6861. static std::array<uint32_t, 3> ggml_vk_get_conv_elements(const ggml_tensor *dst) {
  6862. const ggml_tensor *src0 = dst->src[0];
  6863. const ggml_tensor *src1 = dst->src[1];
  6864. // src0 - kernel: [KW, KH, Cin, Cout]
  6865. // src1 - input: [W, H, Cin, N]
  6866. // dst - result: [OW, OH, Cout, N]
  6867. // Copied from ggml.c: int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d)
  6868. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6869. return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
  6870. };
  6871. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6872. int64_t W = src1->ne[0];
  6873. int64_t H = src1->ne[1];
  6874. int64_t KW = src0->ne[0];
  6875. int64_t KH = src0->ne[1];
  6876. int64_t Cout = src0->ne[3];
  6877. int64_t N = src1->ne[3];
  6878. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[1], dst->op_params[3], dst->op_params[5]);
  6879. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], dst->op_params[2], dst->op_params[4]);
  6880. int64_t NPQ = N * OW * OH;
  6881. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6882. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6883. return elements;
  6884. }
  6885. static std::array<uint32_t, 3> ggml_vk_get_conv_transpose_2d_elements(const ggml_tensor *dst) {
  6886. const ggml_tensor *src0 = dst->src[0];
  6887. const ggml_tensor *src1 = dst->src[1];
  6888. // src0 - kernel: [KW, KH, Cout, Cin]
  6889. // src1 - input: [W, H, Cin, N]
  6890. // dst - result: [OW, OH, Cout, N]
  6891. auto calc_conv_output_size = [](int64_t ins, int64_t ks, int s, int p, int d) -> int64_t {
  6892. return (ins - 1) * s - 2 * p + (ks - 1) * d + 1;
  6893. };
  6894. // parallelize in {OW/BS_K, OH/BS_NPQ, 1}
  6895. int64_t W = src1->ne[0];
  6896. int64_t H = src1->ne[1];
  6897. int64_t KW = src0->ne[0];
  6898. int64_t KH = src0->ne[1];
  6899. int64_t Cout = src0->ne[2];
  6900. int64_t N = src1->ne[3];
  6901. int64_t OH = calc_conv_output_size(H, KH, dst->op_params[0], 0, 1);
  6902. int64_t OW = calc_conv_output_size(W, KW, dst->op_params[0], 0, 1);
  6903. int64_t NPQ = N * OW * OH;
  6904. // Tile output matrix to (K/NB_K, NPQ/NB_NPQ, 1) workgroups
  6905. std::array<uint32_t, 3> elements = { static_cast<uint32_t>(Cout), static_cast<uint32_t>(NPQ), 1 };
  6906. return elements;
  6907. }
  6908. static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * dst, ggml_op op) {
  6909. switch (op) {
  6910. case GGML_OP_GET_ROWS:
  6911. GGML_ASSERT(src1->type == GGML_TYPE_I32);
  6912. if (dst->type == GGML_TYPE_F16) {
  6913. return ctx->device->pipeline_get_rows[src0->type];
  6914. }
  6915. if (dst->type == GGML_TYPE_F32) {
  6916. return ctx->device->pipeline_get_rows_f32[src0->type];
  6917. }
  6918. return nullptr;
  6919. case GGML_OP_ACC:
  6920. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6921. return ctx->device->pipeline_acc_f32;
  6922. }
  6923. return nullptr;
  6924. case GGML_OP_ADD:
  6925. case GGML_OP_SUB:
  6926. case GGML_OP_MUL:
  6927. case GGML_OP_DIV:
  6928. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  6929. (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) ||
  6930. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) {
  6931. return nullptr;
  6932. }
  6933. switch (op) {
  6934. case GGML_OP_ADD:
  6935. {
  6936. if (ctx->num_additional_fused_ops > 0) {
  6937. if (ctx->do_add_rms_partials) {
  6938. return ctx->device->pipeline_multi_add_rms[ctx->num_additional_fused_ops];
  6939. } else {
  6940. return ctx->device->pipeline_multi_add[ctx->num_additional_fused_ops];
  6941. }
  6942. }
  6943. if (ctx->do_add_rms_partials) {
  6944. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_rms_norepeat : ctx->device->pipeline_add_rms;
  6945. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6946. } else {
  6947. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_add_norepeat : ctx->device->pipeline_add;
  6948. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6949. }
  6950. }
  6951. case GGML_OP_SUB:
  6952. {
  6953. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_sub_norepeat : ctx->device->pipeline_sub;
  6954. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6955. }
  6956. case GGML_OP_MUL:
  6957. {
  6958. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_mul_norepeat : ctx->device->pipeline_mul;
  6959. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6960. }
  6961. case GGML_OP_DIV:
  6962. {
  6963. auto pipelines = ggml_are_same_shape(src0, src1) ? ctx->device->pipeline_div_norepeat : ctx->device->pipeline_div;
  6964. return pipelines[src0->type == GGML_TYPE_F16][src1->type == GGML_TYPE_F16][dst->type == GGML_TYPE_F16];
  6965. }
  6966. default:
  6967. break;
  6968. }
  6969. return nullptr;
  6970. case GGML_OP_ADD_ID:
  6971. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_F32) {
  6972. return ctx->device->pipeline_add_id_f32;
  6973. }
  6974. return nullptr;
  6975. case GGML_OP_CONCAT:
  6976. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6977. return ctx->device->pipeline_concat_f32;
  6978. }
  6979. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  6980. return ctx->device->pipeline_concat_f16;
  6981. }
  6982. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) {
  6983. return ctx->device->pipeline_concat_i32;
  6984. }
  6985. return nullptr;
  6986. case GGML_OP_UPSCALE:
  6987. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  6988. ggml_scale_mode mode = (ggml_scale_mode)(ggml_get_op_params_i32(dst, 0) & 0xFF);
  6989. switch (mode) {
  6990. case GGML_SCALE_MODE_NEAREST:
  6991. return ctx->device->pipeline_upscale_nearest_f32;
  6992. case GGML_SCALE_MODE_BILINEAR:
  6993. return ctx->device->pipeline_upscale_bilinear_f32;
  6994. case GGML_SCALE_MODE_BICUBIC:
  6995. return ctx->device->pipeline_upscale_bicubic_f32;
  6996. default:
  6997. return nullptr;
  6998. }
  6999. }
  7000. return nullptr;
  7001. case GGML_OP_SCALE:
  7002. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7003. return ctx->device->pipeline_scale_f32;
  7004. }
  7005. return nullptr;
  7006. case GGML_OP_SQR:
  7007. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7008. return ctx->device->pipeline_sqr_f32;
  7009. }
  7010. return nullptr;
  7011. case GGML_OP_SQRT:
  7012. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7013. return ctx->device->pipeline_sqrt_f32;
  7014. }
  7015. return nullptr;
  7016. case GGML_OP_SIN:
  7017. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7018. return ctx->device->pipeline_sin_f32;
  7019. }
  7020. return nullptr;
  7021. case GGML_OP_COS:
  7022. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7023. return ctx->device->pipeline_cos_f32;
  7024. }
  7025. return nullptr;
  7026. case GGML_OP_LOG:
  7027. if (src0->type == dst->type &&
  7028. (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16)) {
  7029. return ctx->device->pipeline_log[dst->type == GGML_TYPE_F16];
  7030. }
  7031. return nullptr;
  7032. case GGML_OP_CLAMP:
  7033. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7034. return ctx->device->pipeline_clamp_f32;
  7035. }
  7036. return nullptr;
  7037. case GGML_OP_PAD:
  7038. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7039. return ctx->device->pipeline_pad_f32;
  7040. }
  7041. return nullptr;
  7042. case GGML_OP_ROLL:
  7043. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7044. return ctx->device->pipeline_roll_f32;
  7045. }
  7046. return nullptr;
  7047. case GGML_OP_REPEAT:
  7048. if (ggml_type_size(src0->type) == sizeof(float) && ggml_type_size(dst->type) == sizeof(float)) {
  7049. return ctx->device->pipeline_repeat_f32;
  7050. }
  7051. return nullptr;
  7052. case GGML_OP_REPEAT_BACK:
  7053. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7054. return ctx->device->pipeline_repeat_back_f32;
  7055. }
  7056. return nullptr;
  7057. case GGML_OP_CPY:
  7058. case GGML_OP_CONT:
  7059. case GGML_OP_DUP:
  7060. return ggml_vk_get_cpy_pipeline(ctx, src0, dst, dst->type);
  7061. case GGML_OP_SET_ROWS:
  7062. if (src1->type == GGML_TYPE_I64) {
  7063. return ctx->device->pipeline_set_rows_i64[dst->type];
  7064. } else {
  7065. return ctx->device->pipeline_set_rows_i32[dst->type];
  7066. }
  7067. case GGML_OP_SILU_BACK:
  7068. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7069. return ctx->device->pipeline_silu_back_f32;
  7070. }
  7071. return nullptr;
  7072. case GGML_OP_NORM:
  7073. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7074. return ctx->device->pipeline_norm_f32;
  7075. }
  7076. return nullptr;
  7077. case GGML_OP_GROUP_NORM:
  7078. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7079. return ctx->device->pipeline_group_norm_f32;
  7080. }
  7081. return nullptr;
  7082. case GGML_OP_RMS_NORM:
  7083. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7084. if (ctx->do_add_rms_partials) {
  7085. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_partials_f32 : ctx->device->pipeline_rms_norm_partials_f32;
  7086. } else {
  7087. return ctx->num_additional_fused_ops > 0 ? ctx->device->pipeline_rms_norm_mul_f32 : ctx->device->pipeline_rms_norm_f32;
  7088. }
  7089. }
  7090. return nullptr;
  7091. case GGML_OP_RMS_NORM_BACK:
  7092. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7093. return ctx->device->pipeline_rms_norm_back_f32;
  7094. }
  7095. return nullptr;
  7096. case GGML_OP_L2_NORM:
  7097. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7098. return ctx->device->pipeline_l2_norm_f32;
  7099. }
  7100. return nullptr;
  7101. case GGML_OP_UNARY:
  7102. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7103. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7104. (src0->type != dst->type)) {
  7105. return nullptr;
  7106. }
  7107. switch (ggml_get_unary_op(dst)) {
  7108. case GGML_UNARY_OP_EXP:
  7109. return ctx->device->pipeline_exp[dst->type == GGML_TYPE_F16];
  7110. case GGML_UNARY_OP_SILU:
  7111. return ctx->device->pipeline_silu[dst->type == GGML_TYPE_F16];
  7112. case GGML_UNARY_OP_GELU:
  7113. return ctx->device->pipeline_gelu[dst->type == GGML_TYPE_F16];
  7114. case GGML_UNARY_OP_GELU_ERF:
  7115. return ctx->device->pipeline_gelu_erf[dst->type == GGML_TYPE_F16];
  7116. case GGML_UNARY_OP_GELU_QUICK:
  7117. return ctx->device->pipeline_gelu_quick[dst->type == GGML_TYPE_F16];
  7118. case GGML_UNARY_OP_RELU:
  7119. return ctx->device->pipeline_relu[dst->type == GGML_TYPE_F16];
  7120. case GGML_UNARY_OP_NEG:
  7121. return ctx->device->pipeline_neg[dst->type == GGML_TYPE_F16];
  7122. case GGML_UNARY_OP_TANH:
  7123. return ctx->device->pipeline_tanh[dst->type == GGML_TYPE_F16];
  7124. case GGML_UNARY_OP_SIGMOID:
  7125. return ctx->device->pipeline_sigmoid[dst->type == GGML_TYPE_F16];
  7126. case GGML_UNARY_OP_HARDSIGMOID:
  7127. return ctx->device->pipeline_hardsigmoid[dst->type == GGML_TYPE_F16];
  7128. case GGML_UNARY_OP_HARDSWISH:
  7129. return ctx->device->pipeline_hardswish[dst->type == GGML_TYPE_F16];
  7130. case GGML_UNARY_OP_ABS:
  7131. return ctx->device->pipeline_abs[dst->type == GGML_TYPE_F16];
  7132. case GGML_UNARY_OP_SOFTPLUS:
  7133. return ctx->device->pipeline_softplus[dst->type == GGML_TYPE_F16];
  7134. case GGML_UNARY_OP_STEP:
  7135. return ctx->device->pipeline_step[dst->type == GGML_TYPE_F16];
  7136. case GGML_UNARY_OP_ROUND:
  7137. return ctx->device->pipeline_round[dst->type == GGML_TYPE_F16];
  7138. case GGML_UNARY_OP_CEIL:
  7139. return ctx->device->pipeline_ceil[dst->type == GGML_TYPE_F16];
  7140. case GGML_UNARY_OP_FLOOR:
  7141. return ctx->device->pipeline_floor[dst->type == GGML_TYPE_F16];
  7142. case GGML_UNARY_OP_TRUNC:
  7143. return ctx->device->pipeline_trunc[dst->type == GGML_TYPE_F16];
  7144. default:
  7145. break;
  7146. }
  7147. return nullptr;
  7148. case GGML_OP_GLU:
  7149. if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) ||
  7150. (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) ||
  7151. (src0->type != dst->type)) {
  7152. return nullptr;
  7153. }
  7154. switch (ggml_get_glu_op(dst)) {
  7155. case GGML_GLU_OP_GEGLU:
  7156. return ctx->device->pipeline_geglu[dst->type == GGML_TYPE_F16];
  7157. case GGML_GLU_OP_REGLU:
  7158. return ctx->device->pipeline_reglu[dst->type == GGML_TYPE_F16];
  7159. case GGML_GLU_OP_SWIGLU:
  7160. return ctx->device->pipeline_swiglu[dst->type == GGML_TYPE_F16];
  7161. case GGML_GLU_OP_SWIGLU_OAI:
  7162. return ctx->device->pipeline_swiglu_oai[dst->type == GGML_TYPE_F16];
  7163. case GGML_GLU_OP_GEGLU_ERF:
  7164. return ctx->device->pipeline_geglu_erf[dst->type == GGML_TYPE_F16];
  7165. case GGML_GLU_OP_GEGLU_QUICK:
  7166. return ctx->device->pipeline_geglu_quick[dst->type == GGML_TYPE_F16];
  7167. default:
  7168. break;
  7169. }
  7170. return nullptr;
  7171. case GGML_OP_DIAG_MASK_INF:
  7172. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7173. return ctx->device->pipeline_diag_mask_inf_f32;
  7174. }
  7175. return nullptr;
  7176. case GGML_OP_SOFT_MAX:
  7177. GGML_ASSERT(!src1 || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16);
  7178. GGML_ASSERT(!src2 || src2->type == GGML_TYPE_F32);
  7179. if (ctx->num_additional_fused_ops) {
  7180. uint32_t idx = (uint32_t)ceilf(log2f(float(dst->ne[0])));
  7181. GGML_ASSERT(idx < num_topk_moe_pipelines);
  7182. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  7183. return ctx->device->pipeline_topk_moe[idx][mode];
  7184. }
  7185. if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) {
  7186. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32;
  7187. }
  7188. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7189. return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16;
  7190. }
  7191. return nullptr;
  7192. case GGML_OP_SOFT_MAX_BACK:
  7193. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7194. return ctx->device->pipeline_soft_max_back_f32;
  7195. }
  7196. return nullptr;
  7197. case GGML_OP_ROPE:
  7198. case GGML_OP_ROPE_BACK:
  7199. {
  7200. const ggml_tensor *rope = ctx->num_additional_fused_ops == 2 ? dst->src[0]->src[0] : dst;
  7201. const int mode = ((const int32_t *) rope->op_params)[2];
  7202. const bool is_neox = mode & GGML_ROPE_TYPE_NEOX;
  7203. const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE;
  7204. const bool is_vision = mode == GGML_ROPE_TYPE_VISION;
  7205. if (is_neox) {
  7206. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7207. return ctx->device->pipeline_rope_neox_f32;
  7208. }
  7209. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7210. return ctx->device->pipeline_rope_neox_f32_f16;
  7211. }
  7212. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7213. return ctx->device->pipeline_rope_neox_f16;
  7214. }
  7215. } else if (is_mrope && !is_vision) {
  7216. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7217. return ctx->device->pipeline_rope_multi_f32;
  7218. }
  7219. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7220. return ctx->device->pipeline_rope_multi_f16;
  7221. }
  7222. } else if (is_vision) {
  7223. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7224. return ctx->device->pipeline_rope_vision_f32;
  7225. }
  7226. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7227. return ctx->device->pipeline_rope_vision_f16;
  7228. }
  7229. } else {
  7230. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7231. return ctx->device->pipeline_rope_norm_f32;
  7232. }
  7233. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7234. return ctx->device->pipeline_rope_norm_f32_f16;
  7235. }
  7236. if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7237. return ctx->device->pipeline_rope_norm_f16;
  7238. }
  7239. }
  7240. return nullptr;
  7241. }
  7242. case GGML_OP_SUM:
  7243. case GGML_OP_SUM_ROWS:
  7244. case GGML_OP_MEAN:
  7245. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7246. return ctx->device->pipeline_sum_rows_f32;
  7247. }
  7248. return nullptr;
  7249. case GGML_OP_ARGMAX:
  7250. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_I32) {
  7251. return ctx->device->pipeline_argmax_f32;
  7252. }
  7253. return nullptr;
  7254. case GGML_OP_COUNT_EQUAL:
  7255. if (src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I64) {
  7256. return ctx->device->pipeline_count_equal_i32;
  7257. }
  7258. return nullptr;
  7259. case GGML_OP_IM2COL:
  7260. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7261. return ctx->device->pipeline_im2col_f32;
  7262. }
  7263. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7264. return ctx->device->pipeline_im2col_f32_f16;
  7265. }
  7266. return nullptr;
  7267. case GGML_OP_IM2COL_3D:
  7268. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7269. return ctx->device->pipeline_im2col_3d_f32;
  7270. }
  7271. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7272. return ctx->device->pipeline_im2col_3d_f32_f16;
  7273. }
  7274. return nullptr;
  7275. case GGML_OP_TIMESTEP_EMBEDDING:
  7276. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7277. return ctx->device->pipeline_timestep_embedding_f32;
  7278. }
  7279. return nullptr;
  7280. case GGML_OP_CONV_TRANSPOSE_1D:
  7281. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7282. return ctx->device->pipeline_conv_transpose_1d_f32;
  7283. }
  7284. return nullptr;
  7285. case GGML_OP_POOL_2D:
  7286. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7287. return ctx->device->pipeline_pool2d_f32;
  7288. }
  7289. return nullptr;
  7290. case GGML_OP_RWKV_WKV6:
  7291. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7292. return ctx->device->pipeline_rwkv_wkv6_f32;
  7293. }
  7294. return nullptr;
  7295. case GGML_OP_RWKV_WKV7:
  7296. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7297. return ctx->device->pipeline_rwkv_wkv7_f32;
  7298. }
  7299. return nullptr;
  7300. case GGML_OP_SSM_SCAN:
  7301. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7302. const uint32_t d_state = src0->ne[0];
  7303. if (d_state == 128) {
  7304. return ctx->device->pipeline_ssm_scan_f32_d128;
  7305. } else if (d_state == 256) {
  7306. return ctx->device->pipeline_ssm_scan_f32_d256;
  7307. }
  7308. }
  7309. return nullptr;
  7310. case GGML_OP_SSM_CONV:
  7311. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7312. return ctx->device->pipeline_ssm_conv_f32;
  7313. }
  7314. return nullptr;
  7315. case GGML_OP_OPT_STEP_ADAMW:
  7316. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7317. return ctx->device->pipeline_opt_step_adamw_f32;
  7318. }
  7319. return nullptr;
  7320. case GGML_OP_OPT_STEP_SGD:
  7321. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7322. return ctx->device->pipeline_opt_step_sgd_f32;
  7323. }
  7324. return nullptr;
  7325. case GGML_OP_LEAKY_RELU:
  7326. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7327. return ctx->device->pipeline_leaky_relu_f32;
  7328. }
  7329. return nullptr;
  7330. case GGML_OP_CONV_2D:
  7331. case GGML_OP_CONV_TRANSPOSE_2D:
  7332. if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 &&
  7333. ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst)) {
  7334. std::array<uint32_t, 3> elements{};
  7335. if (op == GGML_OP_CONV_2D) elements = ggml_vk_get_conv_elements(dst);
  7336. else if (op == GGML_OP_CONV_TRANSPOSE_2D) elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  7337. vk_conv_shapes shape;
  7338. uint32_t tiles[CONV_SHAPE_COUNT];
  7339. for (uint32_t i = 0; i < CONV_SHAPE_COUNT; ++i) {
  7340. tiles[i] = CEIL_DIV(elements[0], conv_shapes_wg_denoms[i][0]) * CEIL_DIV(elements[1], conv_shapes_wg_denoms[i][1]);
  7341. }
  7342. // We can't query number of shader cores on Intel, use 32 as a placeholder
  7343. // so small convolutions will still choose a smaller tile.
  7344. const uint32_t shader_core_count = ctx->device->shader_core_count > 0 ? ctx->device->shader_core_count : 32;
  7345. if (elements[0] > 64 && tiles[CONV_SHAPE_128x128] >= shader_core_count * 2) {
  7346. shape = CONV_SHAPE_128x128;
  7347. } else if (elements[0] <= 32 && tiles[CONV_SHAPE_32x256] >= shader_core_count * 2) {
  7348. shape = CONV_SHAPE_32x256;
  7349. } else {
  7350. shape = CONV_SHAPE_64x32;
  7351. }
  7352. uint32_t KW = static_cast<uint32_t>(src0->ne[0]);
  7353. uint32_t KH = static_cast<uint32_t>(src0->ne[1]);
  7354. uint32_t s0 = static_cast<uint32_t>(dst->op_params[0]);
  7355. uint32_t s1 = op == GGML_OP_CONV_2D ? static_cast<uint32_t>(dst->op_params[1]) : static_cast<uint32_t>(dst->op_params[0]);
  7356. uint32_t p0 = op == GGML_OP_CONV_2D ? static_cast<uint32_t>(dst->op_params[2]) : 0;
  7357. uint32_t p1 = op == GGML_OP_CONV_2D ? static_cast<uint32_t>(dst->op_params[3]) : 0;
  7358. uint32_t d0 = op == GGML_OP_CONV_2D ? static_cast<uint32_t>(dst->op_params[4]) : 1;
  7359. uint32_t d1 = op == GGML_OP_CONV_2D ? static_cast<uint32_t>(dst->op_params[5]) : 1;
  7360. vk_conv2d_pipeline_state conv2d_pipeline_state(s0, s1, p0, p1, d0, d1, KW, KH);
  7361. std::map<vk_conv2d_pipeline_state, vk_pipeline> *pipelines = nullptr;
  7362. if (op == GGML_OP_CONV_2D) {
  7363. if (src0->type == GGML_TYPE_F32) {
  7364. pipelines = &ctx->device->pipeline_conv2d_f32[shape];
  7365. } else if (src0->type == GGML_TYPE_F16) {
  7366. pipelines = &ctx->device->pipeline_conv2d_f16_f32[shape];
  7367. }
  7368. } else if (op == GGML_OP_CONV_TRANSPOSE_2D) {
  7369. if (src0->type == GGML_TYPE_F32) {
  7370. pipelines = &ctx->device->pipeline_conv_transpose_2d_f32[shape];
  7371. } else if (src0->type == GGML_TYPE_F16) {
  7372. pipelines = &ctx->device->pipeline_conv_transpose_2d_f16_f32[shape];
  7373. }
  7374. }
  7375. vk_pipeline pipeline = nullptr;
  7376. {
  7377. std::lock_guard<std::recursive_mutex> guard(ctx->device->mutex);
  7378. auto it = pipelines->find(conv2d_pipeline_state);
  7379. if (it != pipelines->end()) {
  7380. pipeline = it->second;
  7381. } else {
  7382. (*pipelines)[conv2d_pipeline_state] = pipeline = std::make_shared<vk_pipeline_struct>();
  7383. }
  7384. }
  7385. return pipeline;
  7386. }
  7387. return nullptr;
  7388. case GGML_OP_CONV_2D_DW:
  7389. if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7390. if (ggml_is_contiguous(src1)) {
  7391. return ctx->device->pipeline_conv2d_dw_whcn_f32;
  7392. } else if (ggml_is_contiguous_channels(src1)) {
  7393. return ctx->device->pipeline_conv2d_dw_cwhn_f32;
  7394. }
  7395. } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) {
  7396. if (ggml_is_contiguous(src1)) {
  7397. return ctx->device->pipeline_conv2d_dw_whcn_f16_f32;
  7398. } else if (ggml_is_contiguous_channels(src1)) {
  7399. return ctx->device->pipeline_conv2d_dw_cwhn_f16_f32;
  7400. }
  7401. }
  7402. return nullptr;
  7403. case GGML_OP_ADD1:
  7404. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) {
  7405. return ctx->device->pipeline_add1_f16_f16;
  7406. }
  7407. if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16) {
  7408. return ctx->device->pipeline_add1_f16_f32;
  7409. }
  7410. if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) {
  7411. return ctx->device->pipeline_add1_f32_f32;
  7412. }
  7413. return nullptr;
  7414. case GGML_OP_ARANGE:
  7415. if (dst->type == GGML_TYPE_F32) {
  7416. return ctx->device->pipeline_arange_f32;
  7417. }
  7418. return nullptr;
  7419. case GGML_OP_FILL:
  7420. if (dst->type == GGML_TYPE_F32) {
  7421. return ctx->device->pipeline_fill_f32;
  7422. }
  7423. return nullptr;
  7424. default:
  7425. return nullptr;
  7426. }
  7427. GGML_UNUSED(src2);
  7428. }
  7429. static bool ggml_vk_op_supports_incontiguous(ggml_op op) {
  7430. switch (op) {
  7431. case GGML_OP_CPY:
  7432. case GGML_OP_GET_ROWS:
  7433. case GGML_OP_ADD:
  7434. case GGML_OP_SUB:
  7435. case GGML_OP_MUL:
  7436. case GGML_OP_DIV:
  7437. case GGML_OP_ADD_ID:
  7438. case GGML_OP_CONCAT:
  7439. case GGML_OP_UPSCALE:
  7440. case GGML_OP_SQR:
  7441. case GGML_OP_SQRT:
  7442. case GGML_OP_SIN:
  7443. case GGML_OP_COS:
  7444. case GGML_OP_LOG:
  7445. case GGML_OP_CLAMP:
  7446. case GGML_OP_PAD:
  7447. case GGML_OP_REPEAT:
  7448. case GGML_OP_REPEAT_BACK:
  7449. case GGML_OP_ROPE:
  7450. case GGML_OP_RMS_NORM:
  7451. case GGML_OP_CONV_2D_DW:
  7452. case GGML_OP_IM2COL:
  7453. case GGML_OP_IM2COL_3D:
  7454. case GGML_OP_SET_ROWS:
  7455. case GGML_OP_SUM:
  7456. case GGML_OP_SUM_ROWS:
  7457. case GGML_OP_MEAN:
  7458. return true;
  7459. default:
  7460. return false;
  7461. }
  7462. }
  7463. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_unary_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7464. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7465. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7466. p.misalign_offsets = (a_offset << 16) | d_offset;
  7467. GGML_UNUSED(src1);
  7468. GGML_UNUSED(src2);
  7469. GGML_UNUSED(src3);
  7470. }
  7471. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_sum_rows_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7472. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7473. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7474. p.misalign_offsets = (a_offset << 16) | d_offset;
  7475. GGML_UNUSED(src1);
  7476. GGML_UNUSED(src2);
  7477. GGML_UNUSED(src3);
  7478. }
  7479. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_pad_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7480. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7481. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7482. p.misalign_offsets = (a_offset << 16) | d_offset;
  7483. GGML_UNUSED(src1);
  7484. GGML_UNUSED(src2);
  7485. GGML_UNUSED(src3);
  7486. }
  7487. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_im2col_3d_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7488. const uint32_t a_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7489. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7490. p.misalign_offsets = (a_offset << 16) | d_offset;
  7491. GGML_UNUSED(src0);
  7492. GGML_UNUSED(src2);
  7493. GGML_UNUSED(src3);
  7494. }
  7495. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_binary_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7496. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7497. const uint32_t b_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type);
  7498. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7499. GGML_ASSERT(dst->op != GGML_OP_GET_ROWS || (a_offset == 0 && b_offset == 0 && d_offset == 0));
  7500. p.misalign_offsets = (a_offset << 16) | (b_offset << 8) | d_offset;
  7501. GGML_UNUSED(src2);
  7502. GGML_UNUSED(src3);
  7503. }
  7504. template <> void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_upscale_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) {
  7505. const uint32_t a_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type);
  7506. const uint32_t d_offset = get_misalign_bytes(ctx, dst) / ggml_type_size(dst->type);
  7507. p.a_offset = a_offset;
  7508. p.d_offset = d_offset;
  7509. GGML_UNUSED(src1);
  7510. GGML_UNUSED(src2);
  7511. GGML_UNUSED(src3);
  7512. }
  7513. template<typename PC>
  7514. static void ggml_vk_op_f32(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst, ggml_op op, PC&& pc) {
  7515. 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];
  7516. if (src1 != nullptr) {
  7517. 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];
  7518. }
  7519. if (src2 != nullptr) {
  7520. 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];
  7521. }
  7522. if (src3 != nullptr) {
  7523. std::cerr << "), (" << src3 << ", name=" << src3->name << ", type=" << src3->type << ", ne0=" << src3->ne[0] << ", ne1=" << src3->ne[1] << ", ne2=" << src3->ne[2] << ", ne3=" << src3->ne[3] << ", nb0=" << src3->nb[0] << ", nb1=" << src3->nb[1] << ", nb2=" << src3->nb[2] << ", nb3=" << src3->nb[3];
  7524. }
  7525. 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];
  7526. std::cerr << "), " << ggml_op_name(op) << ")");
  7527. GGML_ASSERT(op == GGML_OP_GET_ROWS || op == GGML_OP_CPY || (!ggml_is_quantized(src0->type) && (src1 == nullptr || !ggml_is_quantized(src1->type)))); // NOLINT
  7528. GGML_ASSERT(ggml_vk_op_supports_incontiguous(op) || ggml_vk_dim01_contiguous(src0)); // NOLINT
  7529. GGML_ASSERT(dst->buffer != nullptr);
  7530. const uint64_t ne00 = src0->ne[0];
  7531. const uint64_t ne01 = src0->ne[1];
  7532. const uint64_t ne02 = src0->ne[2];
  7533. const uint64_t ne03 = src0->ne[3];
  7534. const bool use_src1 = src1 != nullptr;
  7535. const uint64_t ne10 = use_src1 ? src1->ne[0] : 0;
  7536. const uint64_t ne11 = use_src1 ? src1->ne[1] : 0;
  7537. const uint64_t ne12 = use_src1 ? src1->ne[2] : 0;
  7538. const uint64_t ne13 = use_src1 ? src1->ne[3] : 0;
  7539. const bool use_src2 = src2 != nullptr;
  7540. const bool use_src3 = src3 != nullptr;
  7541. init_pushconst_fastdiv(pc);
  7542. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, op);
  7543. if (pipeline == nullptr) {
  7544. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(op) << " for " << ggml_type_name(src0->type);
  7545. if (src1 != nullptr) {
  7546. std::cerr << " and " << ggml_type_name(src1->type);
  7547. }
  7548. std::cerr << " to " << ggml_type_name(dst->type) << std::endl;
  7549. GGML_ABORT("fatal error");
  7550. }
  7551. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7552. const bool op_supports_incontiguous = ggml_vk_op_supports_incontiguous(op);
  7553. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0, op_supports_incontiguous);
  7554. vk_subbuffer src1_buf = use_src1 ? ggml_vk_tensor_subbuffer(ctx, src1, op_supports_incontiguous) : vk_subbuffer{};
  7555. vk_subbuffer src2_buf = use_src2 ? ggml_vk_tensor_subbuffer(ctx, src2, op_supports_incontiguous) : vk_subbuffer{};
  7556. vk_subbuffer src3_buf = use_src3 ? ggml_vk_tensor_subbuffer(ctx, src3, op_supports_incontiguous) : vk_subbuffer{};
  7557. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, op_supports_incontiguous);
  7558. // Compute misalignment offset for descriptors and store it in in push constants.
  7559. init_pushconst_tensor_offsets(ctx, pc, src0, src1, src2, src3, dst);
  7560. std::array<uint32_t, 3> elements;
  7561. // Single call if dimension 2 is contiguous
  7562. GGML_ASSERT(op_supports_incontiguous || (ggml_is_contiguous(src0) && (src1 == nullptr || ggml_is_contiguous(src1))));
  7563. switch (op) {
  7564. case GGML_OP_NORM:
  7565. case GGML_OP_RMS_NORM_BACK:
  7566. case GGML_OP_L2_NORM:
  7567. case GGML_OP_SOFT_MAX:
  7568. case GGML_OP_SOFT_MAX_BACK:
  7569. case GGML_OP_SUM_ROWS:
  7570. case GGML_OP_MEAN:
  7571. case GGML_OP_ARGMAX:
  7572. {
  7573. const uint32_t nr = ggml_nrows(src0);
  7574. if (nr > 262144) {
  7575. elements = { 512, 512, CEIL_DIV(nr, 262144) };
  7576. } else if (nr > 512) {
  7577. elements = { 512, CEIL_DIV(nr, 512), 1 };
  7578. } else {
  7579. elements = { nr, 1, 1 };
  7580. }
  7581. } break;
  7582. case GGML_OP_RMS_NORM:
  7583. if (ctx->do_add_rms_partials) {
  7584. // Run one element per thread, 128 threads per workgroup
  7585. elements = { (uint32_t)CEIL_DIV(ne00, 128), 1, 1 };
  7586. } else {
  7587. elements = { (uint32_t)ne01, (uint32_t)ne02, (uint32_t)ne03 };
  7588. }
  7589. break;
  7590. case GGML_OP_SUM:
  7591. // We use GGML_OP_SUM_ROWS with 1 row.
  7592. elements = { 1, 1, 1 };
  7593. break;
  7594. case GGML_OP_GROUP_NORM:
  7595. {
  7596. const uint32_t num_groups = dst->op_params[0];
  7597. elements = { num_groups * (uint32_t)src0->ne[3], 1, 1 };
  7598. } break;
  7599. case GGML_OP_DIAG_MASK_INF:
  7600. case GGML_OP_ROPE:
  7601. case GGML_OP_ROPE_BACK:
  7602. elements = { (uint32_t)ggml_nrows(src0), (uint32_t)ne00, 1 };
  7603. break;
  7604. case GGML_OP_GET_ROWS:
  7605. elements = { (uint32_t)ne00, (uint32_t)ne10, (uint32_t)(ne11 * ne12) };
  7606. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7607. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7608. break;
  7609. case GGML_OP_ARGSORT:
  7610. GGML_ASSERT(0);
  7611. break;
  7612. case GGML_OP_IM2COL:
  7613. {
  7614. const bool is_2D = dst->op_params[6] == 1;
  7615. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  7616. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  7617. const uint32_t KW = src0->ne[0];
  7618. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  7619. const uint32_t OW = dst->ne[1];
  7620. const uint32_t batch = src1->ne[is_2D ? 3 : 2];
  7621. elements = { OW * KW * KH, OH, batch * IC };
  7622. } break;
  7623. case GGML_OP_IM2COL_3D:
  7624. {
  7625. const uint32_t IC = ((const uint32_t *)(dst->op_params))[9];
  7626. const uint32_t N = ne13 / IC;
  7627. const uint32_t KD = ne02;
  7628. const uint32_t KH = ne01;
  7629. const uint32_t KW = ne00;
  7630. const uint32_t OD = dst->ne[3] / N;
  7631. const uint32_t OH = dst->ne[2];
  7632. const uint32_t OW = dst->ne[1];
  7633. const uint32_t IC_KD_KH_KW = IC*KD*KH*KW;
  7634. const uint32_t N_OD_OH = N*OD*OH;
  7635. elements = { IC_KD_KH_KW, OW, N_OD_OH };
  7636. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7637. } break;
  7638. case GGML_OP_TIMESTEP_EMBEDDING:
  7639. {
  7640. const uint32_t dim = dst->op_params[0];
  7641. uint32_t half_ceil = (dim + 1) / 2;
  7642. elements = { half_ceil, (uint32_t)src0->ne[0], 1 };
  7643. } break;
  7644. case GGML_OP_CONV_TRANSPOSE_1D:
  7645. {
  7646. elements = {uint32_t(src0->ne[1]), 1, 1}; // parallelize in {Cout, 1, 1}
  7647. } break;
  7648. case GGML_OP_POOL_2D:
  7649. {
  7650. const uint32_t N = dst->ne[3];
  7651. const uint32_t OC = dst->ne[2];
  7652. const uint32_t OH = dst->ne[1];
  7653. const uint32_t OW = dst->ne[0];
  7654. elements = { N * OC * OH * OW, 1, 1};
  7655. } break;
  7656. case GGML_OP_CONV_2D:
  7657. {
  7658. elements = ggml_vk_get_conv_elements(dst);
  7659. } break;
  7660. case GGML_OP_CONV_TRANSPOSE_2D:
  7661. {
  7662. elements = ggml_vk_get_conv_transpose_2d_elements(dst);
  7663. } break;
  7664. case GGML_OP_ADD:
  7665. case GGML_OP_SUB:
  7666. case GGML_OP_DIV:
  7667. case GGML_OP_MUL:
  7668. case GGML_OP_ADD1:
  7669. case GGML_OP_ARANGE:
  7670. case GGML_OP_FILL:
  7671. case GGML_OP_SCALE:
  7672. case GGML_OP_SQR:
  7673. case GGML_OP_SQRT:
  7674. case GGML_OP_SIN:
  7675. case GGML_OP_COS:
  7676. case GGML_OP_LOG:
  7677. case GGML_OP_CLAMP:
  7678. case GGML_OP_PAD:
  7679. case GGML_OP_ROLL:
  7680. case GGML_OP_REPEAT:
  7681. case GGML_OP_REPEAT_BACK:
  7682. case GGML_OP_CPY:
  7683. case GGML_OP_CONCAT:
  7684. case GGML_OP_UPSCALE:
  7685. case GGML_OP_UNARY:
  7686. case GGML_OP_GLU:
  7687. case GGML_OP_CONV_2D_DW:
  7688. {
  7689. uint32_t ne = ggml_nelements(dst);
  7690. if (op == GGML_OP_CPY && ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7691. // Convert from number of logical elements to 2- or 4-byte units.
  7692. ne /= ggml_blck_size(src0->type);
  7693. if ((ggml_type_size(src0->type) % 4) == 0) {
  7694. ne *= ggml_type_size(src0->type) / 4;
  7695. } else {
  7696. ne *= ggml_type_size(src0->type) / 2;
  7697. }
  7698. }
  7699. // copy_to_quant has block size of 32, and each thread does QUANT_K elements.
  7700. // Splitting into 512x512xZ wouldn't work well since each workgroup does 1024 elements.
  7701. // So divide by block size here before splitting into 512x512 groups.
  7702. if (op == GGML_OP_CPY && !ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  7703. ne = CEIL_DIV(ne, ggml_blck_size(dst->type));
  7704. }
  7705. if (ne > 262144) {
  7706. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7707. } else if (ne > 512) {
  7708. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7709. } else {
  7710. elements = { ne, 1, 1 };
  7711. }
  7712. if (pipeline == ctx->device->pipeline_cpy_transpose_32 ||
  7713. pipeline == ctx->device->pipeline_cpy_transpose_16) {
  7714. // 32x32 tiles
  7715. elements[0] = (uint32_t)CEIL_DIV(dst->ne[0], 32);
  7716. elements[1] = (uint32_t)CEIL_DIV(dst->ne[1], 32);
  7717. elements[2] = (uint32_t)(dst->ne[2]*dst->ne[3]);
  7718. elements[0] = std::min(elements[0], ctx->device->properties.limits.maxComputeWorkGroupCount[0]);
  7719. elements[1] = std::min(elements[1], ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  7720. elements[2] = std::min(elements[2], ctx->device->properties.limits.maxComputeWorkGroupCount[2]);
  7721. }
  7722. } break;
  7723. case GGML_OP_ADD_ID:
  7724. {
  7725. elements = { (uint32_t)ne01, (uint32_t)ne02, 1 };
  7726. } break;
  7727. case GGML_OP_SET_ROWS:
  7728. {
  7729. uint32_t ne = ggml_nelements(src0);
  7730. if (ggml_is_quantized(dst->type)) {
  7731. // quants run 32 threads each doing QUANT_K elements
  7732. ne = CEIL_DIV(ne, 32 * ggml_blck_size(dst->type));
  7733. } else {
  7734. // scalar types do one element per thread, running 512 threads
  7735. ne = CEIL_DIV(ne, 512);
  7736. }
  7737. if (ne > 262144) {
  7738. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7739. } else if (ne > 512) {
  7740. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7741. } else {
  7742. elements = { ne, 1, 1 };
  7743. }
  7744. }
  7745. break;
  7746. case GGML_OP_SSM_CONV:
  7747. {
  7748. const uint32_t nr = src0->ne[1];
  7749. const uint32_t n_t = dst->ne[1];
  7750. const uint32_t n_s = dst->ne[2];
  7751. elements = { nr, n_t, n_s };
  7752. }
  7753. break;
  7754. default:
  7755. elements = { (uint32_t)ggml_nelements(src0), 1, 1 };
  7756. break;
  7757. }
  7758. if (op == GGML_OP_ADD || op == GGML_OP_RMS_NORM) {
  7759. vk_subbuffer a_buf = src0_buf;
  7760. if (ctx->do_add_rms_partials) {
  7761. a_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset);
  7762. }
  7763. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7764. { src0_buf, src1_buf, dst_buf, a_buf }, pc, elements);
  7765. } else if (op == GGML_OP_GLU) {
  7766. // Empty src1 is possible in glu, but the shader needs a buffer
  7767. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  7768. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc, elements);
  7769. } else if (op == GGML_OP_SOFT_MAX) {
  7770. // Empty src1 and src2 is possible in soft_max, but the shader needs a buffer
  7771. vk_subbuffer subbuf1 = use_src1 ? src1_buf : src0_buf;
  7772. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  7773. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, subbuf2, dst_buf }, pc, elements);
  7774. } else if (op == GGML_OP_ROPE || op == GGML_OP_ROPE_BACK) {
  7775. // Empty src2 and src3 is possible in rope, but the shader needs a buffer
  7776. vk_subbuffer subbuf2 = use_src2 ? src2_buf : src0_buf;
  7777. vk_subbuffer subbuf3 = use_src3 ? src3_buf : src0_buf;
  7778. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, subbuf2, dst_buf, subbuf3 }, pc, elements);
  7779. } else if (op == GGML_OP_IM2COL || op == GGML_OP_IM2COL_3D) {
  7780. if (ctx->device->shader_int64 && ctx->device->buffer_device_address) {
  7781. // buffer device address path doesn't use dst buffer
  7782. dst_buf.size = 1;
  7783. }
  7784. // im2col uses only src1 and dst buffers
  7785. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src1_buf, dst_buf }, pc, elements);
  7786. } else if (op == GGML_OP_COUNT_EQUAL) {
  7787. // count_equal assumes that destination buffer is initialized with zeroes
  7788. ggml_vk_buffer_memset_async(subctx, dst_buf.buffer, dst_buf.offset, 0, dst_buf.size);
  7789. ggml_vk_sync_buffers(ctx, subctx);
  7790. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  7791. } else if (op == GGML_OP_OPT_STEP_SGD) {
  7792. // OPT_STEP_SGD works on src0, it does not need dst
  7793. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf }, pc, elements);
  7794. } else if (use_src3) {
  7795. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, src3_buf, dst_buf }, pc, elements);
  7796. } else if (use_src2) {
  7797. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, src2_buf, dst_buf }, pc, elements);
  7798. } else if (use_src1) {
  7799. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, src1_buf, dst_buf }, pc, elements);
  7800. } else {
  7801. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, dst_buf }, pc, elements);
  7802. }
  7803. }
  7804. 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) {
  7805. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7806. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7807. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7808. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GET_ROWS, {
  7809. (uint32_t)ggml_nelements(src0),
  7810. (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,
  7811. (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,
  7812. (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,
  7813. 0,
  7814. 0.0f, 0.0f, 0,
  7815. });
  7816. }
  7817. static void ggml_vk_acc(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7818. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7819. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7820. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7821. int nb1 = dst->op_params[0] / 4; // 4 bytes of float32
  7822. int nb2 = dst->op_params[1] / 4; // 4 bytes of float32
  7823. // int nb3 = dst->op_params[2] / 4; // 4 bytes of float32 - unused
  7824. int offset = dst->op_params[3] / 4; // offset in bytes
  7825. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ACC, {
  7826. (uint32_t)ggml_nelements(src0),
  7827. (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,
  7828. (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,
  7829. (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,
  7830. 0,
  7831. 0.0f, 0.0f, offset,
  7832. });
  7833. }
  7834. static void ggml_vk_multi_add(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  7835. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  7836. const ggml_tensor *dst = cgraph->nodes[node_idx + ctx->num_additional_fused_ops];
  7837. // Make a list of all the tensors used by the op.
  7838. // Last element of the list is the dest tensor.
  7839. const ggml_tensor *tensors[MAX_PARAMETER_COUNT];
  7840. uint32_t num_srcs = ctx->num_additional_fused_ops + 2;
  7841. uint32_t num_tensors = num_srcs + 1;
  7842. GGML_ASSERT(num_tensors + ctx->do_add_rms_partials <= MAX_PARAMETER_COUNT);
  7843. tensors[0] = first_node->src[0];
  7844. tensors[1] = first_node->src[1];
  7845. for (int32_t i = 0; i < ctx->num_additional_fused_ops; ++i) {
  7846. // check whether the previous result is src[0] or src[1]
  7847. if (cgraph->nodes[node_idx + i] == cgraph->nodes[node_idx + i + 1]->src[0]) {
  7848. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[1];
  7849. } else {
  7850. tensors[i+2] = cgraph->nodes[node_idx + i + 1]->src[0];
  7851. }
  7852. }
  7853. tensors[num_srcs] = dst;
  7854. vk_op_multi_add_push_constants pc;
  7855. pc.ne20 = (uint32_t)dst->ne[0];
  7856. pc.ne21 = (uint32_t)dst->ne[1];
  7857. pc.ne22 = (uint32_t)dst->ne[2];
  7858. pc.ne23 = (uint32_t)dst->ne[3];
  7859. for (uint32_t i = 0; i < num_tensors; ++i) {
  7860. const ggml_tensor *t = tensors[i];
  7861. pc.nb[i][0] = (uint32_t)t->nb[0] / sizeof(float);
  7862. pc.nb[i][1] = (uint32_t)t->nb[1] / sizeof(float);
  7863. pc.nb[i][2] = (uint32_t)t->nb[2] / sizeof(float);
  7864. pc.nb[i][3] = (uint32_t)t->nb[3] / sizeof(float);
  7865. }
  7866. pc.rms_partials = ctx->do_add_rms_partials;
  7867. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, tensors[0], tensors[1], nullptr, dst, dst->op);
  7868. if (pipeline == nullptr) {
  7869. std::cerr << "ggml_vulkan: Error: Missing multi_add";
  7870. GGML_ABORT("fatal error");
  7871. }
  7872. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  7873. ggml_backend_vk_buffer_context * buf_ctx[MAX_PARAMETER_COUNT];
  7874. vk_buffer buf[MAX_PARAMETER_COUNT];
  7875. size_t offset[MAX_PARAMETER_COUNT];
  7876. bool uma[MAX_PARAMETER_COUNT];
  7877. for (uint32_t i = 0; i < num_tensors; ++i) {
  7878. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  7879. buf[i] = nullptr;
  7880. offset[i] = 0;
  7881. uma[i] = false;
  7882. if (ctx->device->uma) {
  7883. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  7884. uma[i] = buf[i] != nullptr;
  7885. }
  7886. if (!uma[i]) {
  7887. buf[i] = buf_ctx[i]->dev_buffer;
  7888. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  7889. }
  7890. GGML_ASSERT(buf[i] != nullptr);
  7891. }
  7892. // If any remaining descriptors are unused, just point them at src[0]
  7893. for (uint32_t i = num_tensors; i < MAX_PARAMETER_COUNT; ++i) {
  7894. buf[i] = buf[0];
  7895. offset[i] = 0;
  7896. }
  7897. if (ctx->do_add_rms_partials) {
  7898. buf[num_tensors] = ctx->prealloc_add_rms_partials;
  7899. offset[num_tensors] = ctx->prealloc_size_add_rms_partials_offset;
  7900. }
  7901. std::array<uint32_t, 3> elements;
  7902. uint32_t ne = ggml_nelements(dst);
  7903. if (ne > 262144) {
  7904. elements = { 512, 512, CEIL_DIV(ne, 262144) };
  7905. } else if (ne > 512) {
  7906. elements = { 512, CEIL_DIV(ne, 512), 1 };
  7907. } else {
  7908. elements = { ne, 1, 1 };
  7909. }
  7910. static_assert(MAX_PARAMETER_COUNT == 12);
  7911. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  7912. {
  7913. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  7914. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  7915. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  7916. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  7917. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  7918. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  7919. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  7920. ggml_vk_subbuffer(ctx, buf[7], offset[7]),
  7921. ggml_vk_subbuffer(ctx, buf[8], offset[8]),
  7922. ggml_vk_subbuffer(ctx, buf[9], offset[9]),
  7923. ggml_vk_subbuffer(ctx, buf[10], offset[10]),
  7924. ggml_vk_subbuffer(ctx, buf[11], offset[11]),
  7925. }, pc, elements);
  7926. }
  7927. static void ggml_vk_add(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7928. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7929. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7930. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7931. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD, {
  7932. (uint32_t)ggml_nelements(src0),
  7933. (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,
  7934. (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,
  7935. (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,
  7936. 0,
  7937. 0.0f, 0.0f, ctx->do_add_rms_partials,
  7938. });
  7939. }
  7940. static void ggml_vk_sub(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7941. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7942. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7943. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7944. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SUB, {
  7945. (uint32_t)ggml_nelements(src0),
  7946. (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,
  7947. (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,
  7948. (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,
  7949. 0,
  7950. 0.0f, 0.0f, 0,
  7951. });
  7952. }
  7953. static void ggml_vk_mul(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7954. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7955. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7956. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7957. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_MUL, {
  7958. (uint32_t)ggml_nelements(src0),
  7959. (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,
  7960. (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,
  7961. (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,
  7962. 0,
  7963. 0.0f, 0.0f, 0,
  7964. });
  7965. }
  7966. static void ggml_vk_div(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  7967. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7968. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7969. const uint32_t dst_type_size = ggml_type_size(dst->type);
  7970. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_DIV, {
  7971. (uint32_t)ggml_nelements(src0),
  7972. (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,
  7973. (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,
  7974. (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,
  7975. 0,
  7976. 0.0f, 0.0f, 0,
  7977. });
  7978. }
  7979. 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) {
  7980. const uint32_t src0_type_size = ggml_type_size(src0->type);
  7981. const uint32_t src1_type_size = ggml_type_size(src1->type);
  7982. const uint32_t src2_type_size = ggml_type_size(src2->type);
  7983. ggml_vk_op_f32<vk_op_add_id_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_ADD_ID, {
  7984. (uint32_t)dst->ne[0],
  7985. (uint32_t)dst->ne[1],
  7986. (uint32_t)src0->nb[1] / src0_type_size,
  7987. (uint32_t)src0->nb[2] / src0_type_size,
  7988. (uint32_t)src1->nb[1] / src1_type_size,
  7989. (uint32_t)src2->nb[1] / src2_type_size,
  7990. });
  7991. }
  7992. 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) {
  7993. GGML_ASSERT(version == 6 || version == 7);
  7994. int num_srcs = version == 6 ? 6 : 7;
  7995. for (int i = 0; i < num_srcs; i++) {
  7996. GGML_ASSERT(!ggml_is_quantized(dst->src[i]->type));
  7997. }
  7998. GGML_ASSERT(dst->buffer != nullptr);
  7999. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op);
  8000. GGML_ASSERT(pipeline != nullptr);
  8001. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8002. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8003. vk_subbuffer src_buf[7] = {};
  8004. for (int i = 0; i < num_srcs; i++) {
  8005. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8006. }
  8007. std::array<uint32_t, 3> elements = {
  8008. (uint32_t)(pc.B * pc.H),
  8009. 1,
  8010. 1
  8011. };
  8012. if (version == 6) {
  8013. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8014. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf},
  8015. pc, elements);
  8016. } else if (version == 7) {
  8017. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8018. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8019. pc, elements);
  8020. } else {
  8021. // shouldn't happen
  8022. GGML_ASSERT(false);
  8023. }
  8024. }
  8025. static void ggml_vk_rwkv_wkv6(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8026. const size_t seq_length = dst->src[0]->ne[2];
  8027. const size_t n_embed = dst->ne[0];
  8028. const size_t n_heads = dst->src[0]->ne[1];
  8029. const size_t n_seqs = dst->src[5]->ne[1];
  8030. ggml_vk_op_f32_wkv(
  8031. ctx, subctx, dst,
  8032. {
  8033. (uint32_t)n_seqs,
  8034. (uint32_t)seq_length,
  8035. (uint32_t)n_embed,
  8036. (uint32_t)n_heads,
  8037. },
  8038. 6
  8039. );
  8040. }
  8041. static void ggml_vk_rwkv_wkv7(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8042. const size_t seq_length = dst->src[0]->ne[2];
  8043. const size_t n_embed = dst->ne[0];
  8044. const size_t n_heads = dst->src[0]->ne[1];
  8045. const size_t n_seqs = dst->src[6]->ne[1];
  8046. ggml_vk_op_f32_wkv(
  8047. ctx, subctx, dst,
  8048. {
  8049. (uint32_t)n_seqs,
  8050. (uint32_t)seq_length,
  8051. (uint32_t)n_embed,
  8052. (uint32_t)n_heads,
  8053. },
  8054. 7
  8055. );
  8056. }
  8057. static void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8058. const ggml_tensor * src0 = dst->src[0];
  8059. const ggml_tensor * src1 = dst->src[1];
  8060. const ggml_tensor * src2 = dst->src[2];
  8061. const ggml_tensor * src3 = dst->src[3];
  8062. const ggml_tensor * src4 = dst->src[4];
  8063. const ggml_tensor * src5 = dst->src[5];
  8064. GGML_ASSERT(dst->buffer != nullptr);
  8065. const uint32_t head_dim = src0->ne[1];
  8066. const uint32_t n_head = src1->ne[1];
  8067. const uint32_t n_group = src4->ne[1];
  8068. const uint32_t n_tok = src1->ne[2];
  8069. const uint32_t n_seq = src1->ne[3];
  8070. bool is_mamba2 = (src3->nb[1] == sizeof(float));
  8071. GGML_ASSERT(is_mamba2);
  8072. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op);
  8073. GGML_ASSERT(pipeline != nullptr);
  8074. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8075. const int64_t s_off = ggml_nelements(src1) * sizeof(float);
  8076. const vk_op_ssm_scan_push_constants pc = {
  8077. (uint32_t)src0->nb[2], (uint32_t)src0->nb[3],
  8078. (uint32_t)src1->nb[2], (uint32_t)src1->nb[3],
  8079. (uint32_t)src2->nb[1], (uint32_t)src2->nb[2],
  8080. (uint32_t)src3->nb[1],
  8081. (uint32_t)src4->nb[2], (uint32_t)src4->nb[3],
  8082. (uint32_t)src5->nb[2], (uint32_t)src5->nb[3],
  8083. (uint32_t)s_off,
  8084. n_head, head_dim, n_group, n_tok
  8085. };
  8086. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8087. vk_subbuffer src_buf[7] = {};
  8088. for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
  8089. src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
  8090. }
  8091. std::array<uint32_t, 3> elements;
  8092. const int splitH = 16;
  8093. const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, splitH);
  8094. const uint32_t num_workgroups_y = n_seq;
  8095. elements = { num_workgroups_x, num_workgroups_y, 1 };
  8096. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8097. {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
  8098. pc, elements);
  8099. }
  8100. static void ggml_vk_ssm_conv(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8101. const ggml_tensor * src0 = dst->src[0];
  8102. const ggml_tensor * src1 = dst->src[1];
  8103. ggml_vk_op_f32<vk_op_ssm_conv_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SSM_CONV, {
  8104. (uint32_t)src0->nb[1], (uint32_t)src0->nb[2],
  8105. (uint32_t)src1->nb[1],
  8106. (uint32_t)dst->nb[0], (uint32_t)dst->nb[1], (uint32_t)dst->nb[2],
  8107. (uint32_t)src1->ne[0],
  8108. (uint32_t)src0->ne[0],
  8109. (uint32_t)src0->ne[1],
  8110. (uint32_t)dst->ne[1],
  8111. (uint32_t)dst->ne[2],
  8112. });
  8113. }
  8114. 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) {
  8115. const ggml_tensor * x = dst->src[0];
  8116. const ggml_tensor * g = dst->src[1];
  8117. const ggml_tensor * gm = dst->src[2];
  8118. const ggml_tensor * gv = dst->src[3];
  8119. const ggml_tensor * p = dst->src[4];
  8120. GGML_ASSERT(x->type == GGML_TYPE_F32);
  8121. GGML_ASSERT(g->type == GGML_TYPE_F32);
  8122. GGML_ASSERT(gm->type == GGML_TYPE_F32);
  8123. GGML_ASSERT(gv->type == GGML_TYPE_F32);
  8124. GGML_ASSERT(p->type == GGML_TYPE_F32);
  8125. GGML_ASSERT(dst->buffer != nullptr);
  8126. GGML_ASSERT(ggml_is_contiguous(x));
  8127. GGML_ASSERT(ggml_is_contiguous(g));
  8128. GGML_ASSERT(ggml_is_contiguous(gm));
  8129. GGML_ASSERT(ggml_is_contiguous(gv));
  8130. GGML_ASSERT(ggml_is_contiguous(p));
  8131. GGML_ASSERT(ggml_are_same_shape(x, g));
  8132. GGML_ASSERT(ggml_are_same_shape(x, gm));
  8133. GGML_ASSERT(ggml_are_same_shape(x, gv));
  8134. GGML_ASSERT(ggml_nelements(p) == 7);
  8135. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, g, gm, gv, dst, GGML_OP_OPT_STEP_ADAMW);
  8136. GGML_ASSERT(pipeline != nullptr);
  8137. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8138. vk_subbuffer x_buf = ggml_vk_tensor_subbuffer(ctx, x);
  8139. vk_subbuffer g_buf = ggml_vk_tensor_subbuffer(ctx, g);
  8140. vk_subbuffer gm_buf = ggml_vk_tensor_subbuffer(ctx, gm);
  8141. vk_subbuffer gv_buf = ggml_vk_tensor_subbuffer(ctx, gv);
  8142. vk_subbuffer p_buf = ggml_vk_tensor_subbuffer(ctx, p);
  8143. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(x), 1, 1 };
  8144. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8145. {x_buf, g_buf, gm_buf, gv_buf, p_buf},
  8146. pc, elements);
  8147. }
  8148. static void ggml_vk_opt_step_adamw(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8149. const size_t n = ggml_nelements(dst->src[0]);
  8150. ggml_vk_op_f32_opt_step_adamw(
  8151. ctx, subctx, dst,
  8152. { (uint32_t)n, 0, 0.0f, 0.0f }
  8153. );
  8154. }
  8155. 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) {
  8156. const size_t n = ggml_nelements(dst->src[0]);
  8157. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_OPT_STEP_SGD, { (uint32_t)n, 0, 0.0f, 0.0f });
  8158. }
  8159. static void ggml_vk_concat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8160. int * op_params = (int *)dst->op_params;
  8161. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8162. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8163. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8164. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONCAT, {
  8165. (uint32_t)ggml_nelements(dst),
  8166. (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,
  8167. (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,
  8168. (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,
  8169. 0,
  8170. 0.0f, 0.0f, op_params[0],
  8171. });
  8172. }
  8173. static void ggml_vk_upscale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8174. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8175. const uint32_t mode = (uint32_t)ggml_get_op_params_i32(dst, 0);
  8176. GGML_TENSOR_UNARY_OP_LOCALS
  8177. float sf0 = (float)ne0 / ne00;
  8178. float sf1 = (float)ne1 / ne01;
  8179. float sf2 = (float)ne2 / ne02;
  8180. float sf3 = (float)ne3 / ne03;
  8181. float pixel_offset = 0.5f;
  8182. if (mode & GGML_SCALE_FLAG_ALIGN_CORNERS) {
  8183. sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0;
  8184. sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1;
  8185. pixel_offset = 0.0f;
  8186. }
  8187. ggml_vk_op_f32<vk_op_upscale_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UPSCALE, {
  8188. (uint32_t)ggml_nelements(dst), 0, 0,
  8189. (uint32_t)ne00, (uint32_t)ne01,
  8190. (uint32_t)nb00 / src0_type_size, (uint32_t)nb01 / src0_type_size, (uint32_t)nb02 / src0_type_size, (uint32_t)nb03 / src0_type_size,
  8191. (uint32_t)ne0, (uint32_t)ne1, (uint32_t)ne2, (uint32_t)ne3,
  8192. sf0, sf1, sf2, sf3, pixel_offset
  8193. });
  8194. }
  8195. static void ggml_vk_scale(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8196. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8197. p.param1 = ggml_get_op_params_f32(dst, 0);
  8198. p.param2 = ggml_get_op_params_f32(dst, 1);
  8199. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SCALE, std::move(p));
  8200. }
  8201. static void ggml_vk_sqr(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8202. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQR, vk_op_unary_push_constants_init(src0, dst));
  8203. }
  8204. static void ggml_vk_sqrt(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8205. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SQRT, vk_op_unary_push_constants_init(src0, dst));
  8206. }
  8207. static void ggml_vk_add1(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8208. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8209. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8210. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8211. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_ADD1, {
  8212. (uint32_t)ggml_nelements(src0),
  8213. (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,
  8214. (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,
  8215. (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,
  8216. 0,
  8217. 0.0f, 0.0f, 0,
  8218. });
  8219. }
  8220. static void ggml_vk_arange(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8221. VK_LOG_DEBUG("ggml_vk_arange(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")");
  8222. vk_op_push_constants pc = {
  8223. (uint32_t)ggml_nelements(dst),
  8224. 1,
  8225. ggml_get_op_params_f32(dst, 0),
  8226. ggml_get_op_params_f32(dst, 2),
  8227. };
  8228. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_ARANGE);
  8229. GGML_ASSERT(pipeline != nullptr);
  8230. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8231. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
  8232. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(dst), 1, 1 };
  8233. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
  8234. }
  8235. static void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
  8236. VK_LOG_DEBUG("ggml_vk_fill(dst=" << dst << ", ne=" << ggml_nelements(dst) << ")");
  8237. vk_op_push_constants pc = {
  8238. (uint32_t)ggml_nelements(dst),
  8239. 1,
  8240. ggml_get_op_params_f32(dst, 0),
  8241. 0.0f,
  8242. };
  8243. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_FILL);
  8244. GGML_ASSERT(pipeline != nullptr);
  8245. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8246. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false);
  8247. std::array<uint32_t, 3> elements = { (uint32_t)ggml_nelements(dst), 1, 1 };
  8248. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements);
  8249. }
  8250. static void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8251. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst));
  8252. }
  8253. static void ggml_vk_cos(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8254. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_COS, vk_op_unary_push_constants_init(src0, dst));
  8255. }
  8256. static void ggml_vk_log(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8257. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_LOG, vk_op_unary_push_constants_init(src0, dst));
  8258. }
  8259. static void ggml_vk_clamp(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8260. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8261. p.param1 = ggml_get_op_params_f32(dst, 0);
  8262. p.param2 = ggml_get_op_params_f32(dst, 1);
  8263. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CLAMP, std::move(p));
  8264. }
  8265. static void ggml_vk_pad(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8266. vk_op_pad_push_constants p = vk_op_pad_push_constants_init(src0, dst);
  8267. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_PAD, std::move(p));
  8268. }
  8269. static void ggml_vk_roll(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8270. const int32_t s0 = ggml_get_op_params_i32(dst, 0);
  8271. const int32_t s1 = ggml_get_op_params_i32(dst, 1);
  8272. const int32_t s2 = ggml_get_op_params_i32(dst, 2);
  8273. const int32_t s3 = ggml_get_op_params_i32(dst, 3);
  8274. const uint32_t s01_packed = ((s0 + 0x8000) << 16) | (s1 + 0x8000);
  8275. const uint32_t s23_packed = ((s2 + 0x8000) << 16) | (s3 + 0x8000);
  8276. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst);
  8277. memcpy(&p.param1, &s01_packed, sizeof(float));
  8278. memcpy(&p.param2, &s23_packed, sizeof(float));
  8279. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ROLL, std::move(p));
  8280. }
  8281. static void ggml_vk_repeat(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8282. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8283. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT, std::move(p));
  8284. }
  8285. static void ggml_vk_repeat_back(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8286. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ggml_nelements(dst));
  8287. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_REPEAT_BACK, std::move(p));
  8288. }
  8289. static void ggml_vk_cpy(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8290. uint32_t ne = (uint32_t)ggml_nelements(src0);
  8291. if (ggml_is_quantized(src0->type) && ggml_is_quantized(dst->type)) {
  8292. // Convert from number of logical elements to 2- or 4-byte units.
  8293. ne /= ggml_blck_size(src0->type);
  8294. if ((ggml_type_size(src0->type) % 4) == 0) {
  8295. ne *= ggml_type_size(src0->type) / 4;
  8296. } else {
  8297. ne *= ggml_type_size(src0->type) / 2;
  8298. }
  8299. }
  8300. vk_op_unary_push_constants p = vk_op_unary_push_constants_init(src0, dst, ne);
  8301. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_CPY, std::move(p));
  8302. }
  8303. 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) {
  8304. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8305. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8306. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8307. // Skip empty skip_rows operations. For most ops the empty check at the start
  8308. // of ggml_vk_build_graph is sufficient, but set_rows can have a nonempty dst
  8309. // with empty srcs.
  8310. if (ggml_is_empty(src0) || ggml_is_empty(src1)) {
  8311. return;
  8312. }
  8313. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SET_ROWS, {
  8314. (uint32_t)ggml_nelements(src0),
  8315. (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,
  8316. (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,
  8317. (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,
  8318. 0,
  8319. 0.0f, 0.0f, 0,
  8320. });
  8321. }
  8322. 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) {
  8323. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SILU_BACK, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f });
  8324. }
  8325. static void ggml_vk_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8326. float * op_params = (float *)dst->op_params;
  8327. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f });
  8328. }
  8329. static void ggml_vk_group_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8330. const int * int_op_params = (const int *)dst->op_params;
  8331. const float * float_op_params = (const float *)dst->op_params;
  8332. const uint32_t num_groups = int_op_params[0];
  8333. const float eps = float_op_params[1];
  8334. const uint32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + num_groups - 1) / num_groups);
  8335. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_GROUP_NORM, { group_size, 0, eps, 0.0f });
  8336. }
  8337. static uint32_t ggml_vk_rms_num_partials(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8338. const uint32_t ne = (uint32_t)node->ne[0];
  8339. const uint32_t denom = ctx->device->pipeline_add_rms[0][0][0]->wg_denoms[0];
  8340. const uint32_t num_partials = CEIL_DIV(ne, denom);
  8341. return num_partials;
  8342. }
  8343. static uint32_t ggml_vk_rms_partials_size(ggml_backend_vk_context * ctx, const ggml_tensor *node) {
  8344. const uint32_t num_partials = ggml_vk_rms_num_partials(ctx, node);
  8345. const uint32_t num_bytes = ROUNDUP_POW2(num_partials * sizeof(uint32_t), ctx->device->partials_binding_alignment);
  8346. return num_bytes;
  8347. }
  8348. static vk_op_rope_push_constants ggml_vk_make_rope_constants(const ggml_tensor *dst, const ggml_tensor *src0, const bool has_ff, bool backprop, const uint32_t set_rows_stride) {
  8349. const int n_dims = ((const int32_t *) dst->op_params)[1];
  8350. const int mode = ((const int32_t *) dst->op_params)[2];
  8351. // const int n_ctx = ((const int32_t *) dst->op_params)[3];
  8352. const int n_ctx_orig = ((const int32_t *) dst->op_params)[4];
  8353. const float freq_base = ((const float *) dst->op_params)[5];
  8354. const float freq_scale = ((const float *) dst->op_params)[6];
  8355. const float ext_factor = ((const float *) dst->op_params)[7];
  8356. const float attn_factor = ((const float *) dst->op_params)[8];
  8357. const float beta_fast = ((const float *) dst->op_params)[9];
  8358. const float beta_slow = ((const float *) dst->op_params)[10];
  8359. int sections[4] {};
  8360. if (mode & GGML_ROPE_TYPE_MROPE) {
  8361. memcpy(sections, (const int32_t *) dst->op_params + 11, sizeof(int)*4);
  8362. }
  8363. const bool is_imrope = mode == GGML_ROPE_TYPE_IMROPE;
  8364. float corr_dims[2];
  8365. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8366. const float theta_scale = powf(freq_base, -2.0f/n_dims);
  8367. uint32_t nb01 = src0->nb[1] / ggml_type_size(src0->type);
  8368. uint32_t nb02 = src0->nb[2] / ggml_type_size(src0->type);
  8369. vk_op_rope_push_constants rope {
  8370. (uint32_t)mode, (uint32_t)src0->ne[0], (uint32_t)n_dims, freq_scale, (uint32_t)src0->ne[1],
  8371. freq_base, ext_factor, attn_factor, {corr_dims[0], corr_dims[1]}, theta_scale,
  8372. has_ff, (uint32_t)src0->ne[2], nb01, nb02,
  8373. { sections[0], sections[1], sections[2], sections[3] }, is_imrope, backprop, set_rows_stride,
  8374. };
  8375. return rope;
  8376. }
  8377. static void ggml_vk_rms_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx, float * op_params) {
  8378. ggml_tensor * dst;
  8379. const ggml_tensor * src0;
  8380. const ggml_tensor * src1;
  8381. if (ctx->num_additional_fused_ops > 0) {
  8382. // fused rms_norm + mul
  8383. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8384. ggml_tensor *other_src = mul->src[0] == cgraph->nodes[node_idx + 0] ? mul->src[1] : mul->src[0];
  8385. dst = mul;
  8386. src0 = cgraph->nodes[node_idx]->src[0];
  8387. src1 = other_src;
  8388. } else {
  8389. dst = cgraph->nodes[node_idx];
  8390. src0 = src1 = dst->src[0];
  8391. }
  8392. const uint32_t src0_type_size = ggml_type_size(src0->type);
  8393. const uint32_t src1_type_size = ggml_type_size(src1->type);
  8394. const uint32_t dst_type_size = ggml_type_size(dst->type);
  8395. uint32_t param3 = ctx->do_add_rms_partials ? ggml_vk_rms_num_partials(ctx, dst) : 0;
  8396. vk_op_binary_push_constants bin {
  8397. (uint32_t)ggml_nelements(src0),
  8398. (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,
  8399. (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,
  8400. (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,
  8401. 0,
  8402. op_params[0], 0.0f, (int32_t)param3,
  8403. };
  8404. // more than one fused op means rms_norm+mul+rope
  8405. if (ctx->num_additional_fused_ops > 1) {
  8406. static constexpr uint32_t max_tensors = 7;
  8407. const ggml_tensor *tensors[max_tensors] {};
  8408. ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  8409. ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  8410. ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  8411. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  8412. bool do_set_rows = ctx->num_additional_fused_ops == 4;
  8413. tensors[0] = rms->src[0];
  8414. tensors[1] = other_src;
  8415. tensors[2] = mul;
  8416. tensors[3] = rope->src[1]; // pos
  8417. tensors[4] = rope->src[2]; // ff
  8418. tensors[5] = cgraph->nodes[node_idx + ctx->num_additional_fused_ops]; // dst
  8419. tensors[6] = do_set_rows ? tensors[5]->src[1] : nullptr;
  8420. const uint32_t set_rows_stride = do_set_rows ? tensors[5]->nb[1] / ggml_type_size(tensors[5]->type) : 0;
  8421. vk_op_rms_norm_mul_rope_push_constants pc;
  8422. pc.bin = bin;
  8423. pc.rope = ggml_vk_make_rope_constants(rope, rope->src[0], tensors[4] != nullptr, false, set_rows_stride);
  8424. vk_pipeline pipeline = tensors[5]->type == GGML_TYPE_F16 ? ctx->device->pipeline_rms_norm_mul_rope_f32_f16 : ctx->device->pipeline_rms_norm_mul_rope_f32_f32;
  8425. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8426. ggml_backend_vk_buffer_context * buf_ctx[max_tensors];
  8427. vk_buffer buf[max_tensors];
  8428. size_t offset[max_tensors];
  8429. bool uma[max_tensors];
  8430. for (uint32_t i = 0; i < max_tensors; ++i) {
  8431. if (!tensors[i]) {
  8432. // If any remaining descriptors are unused, just point them at src[0]
  8433. buf[i] = buf[0];
  8434. offset[i] = 0;
  8435. continue;
  8436. }
  8437. buf_ctx[i] = (ggml_backend_vk_buffer_context *)tensors[i]->buffer->context;
  8438. buf[i] = nullptr;
  8439. offset[i] = 0;
  8440. uma[i] = false;
  8441. if (ctx->device->uma) {
  8442. ggml_vk_host_get(ctx->device, tensors[i]->data, buf[i], offset[i]);
  8443. uma[i] = buf[i] != nullptr;
  8444. }
  8445. if (!uma[i]) {
  8446. buf[i] = buf_ctx[i]->dev_buffer;
  8447. offset[i] = vk_tensor_offset(tensors[i]) + tensors[i]->view_offs;
  8448. }
  8449. GGML_ASSERT(buf[i] != nullptr);
  8450. }
  8451. std::array<uint32_t, 3> elements;
  8452. elements = { (uint32_t)rms->src[0]->ne[1], (uint32_t)rms->src[0]->ne[2], (uint32_t)rms->src[0]->ne[3] };
  8453. static_assert(max_tensors == 7);
  8454. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
  8455. {
  8456. ggml_vk_subbuffer(ctx, buf[0], offset[0]),
  8457. ggml_vk_subbuffer(ctx, buf[1], offset[1]),
  8458. ggml_vk_subbuffer(ctx, buf[2], offset[2]),
  8459. ggml_vk_subbuffer(ctx, buf[3], offset[3]),
  8460. ggml_vk_subbuffer(ctx, buf[4], offset[4]),
  8461. ggml_vk_subbuffer(ctx, buf[5], offset[5]),
  8462. ggml_vk_subbuffer(ctx, buf[6], offset[6]),
  8463. }, pc, elements);
  8464. } else {
  8465. ggml_vk_op_f32<vk_op_binary_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM, std::move(bin));
  8466. }
  8467. if (ctx->do_add_rms_partials_offset_calculation) {
  8468. ctx->prealloc_size_add_rms_partials_offset += ggml_vk_rms_partials_size(ctx, src0);
  8469. ctx->do_add_rms_partials = false;
  8470. ctx->do_add_rms_partials_offset_calculation = false;
  8471. }
  8472. }
  8473. 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) {
  8474. float * op_params = (float *)dst->op_params;
  8475. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_RMS_NORM_BACK, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f });
  8476. }
  8477. static void ggml_vk_l2_norm(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8478. float * op_params = (float *)dst->op_params;
  8479. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_L2_NORM, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0], 0.0f });
  8480. }
  8481. static void ggml_vk_unary(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8482. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_UNARY, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f });
  8483. }
  8484. static void ggml_vk_glu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8485. const float * op_params_f = (const float *)dst->op_params;
  8486. const bool swapped = (bool)dst->op_params[1];
  8487. const bool split = src1 != nullptr;
  8488. const float alpha = op_params_f[2];
  8489. const float limit = op_params_f[3];
  8490. GGML_ASSERT(ggml_is_contiguous(src0));
  8491. if (!split) {
  8492. GGML_ASSERT(src0->ne[0] / 2 == dst->ne[0]);
  8493. } else {
  8494. GGML_ASSERT(src0->ne[0] == src1->ne[0]);
  8495. GGML_ASSERT(src0->ne[0] == dst->ne[0]);
  8496. GGML_ASSERT(src0->type == src1->type);
  8497. }
  8498. const uint32_t mode = split ? 2 : (swapped ? 1 : 0);
  8499. ggml_vk_op_f32<vk_op_glu_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_GLU,
  8500. {
  8501. (uint32_t)ggml_nelements(dst),
  8502. (uint32_t)src0->ne[0],
  8503. (uint32_t)dst->ne[0],
  8504. mode,
  8505. alpha,
  8506. limit
  8507. });
  8508. }
  8509. static void ggml_vk_diag_mask_inf(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8510. int32_t * op_params = (int32_t *)dst->op_params;
  8511. ggml_vk_op_f32<vk_op_diag_mask_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_DIAG_MASK_INF, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], op_params[0] });
  8512. }
  8513. 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) {
  8514. float * op_params = (float *)dst->op_params;
  8515. float scale = op_params[0];
  8516. float max_bias = op_params[1];
  8517. const uint32_t ncols = (uint32_t)src0->ne[0];
  8518. const uint32_t nrows_x = (uint32_t)ggml_nrows(src0);
  8519. const uint32_t nrows_y = (uint32_t)src0->ne[1];
  8520. const uint32_t ne12 = src1 ? (uint32_t)(src1->ne[2]) : 0u;
  8521. const uint32_t ne13 = src1 ? (uint32_t)(src1->ne[3]) : 0u;
  8522. const uint32_t nb11 = src1 ? (uint32_t)(src1->nb[1] / src1->nb[0]) : 0u;
  8523. const uint32_t nb12 = src1 ? (uint32_t)(src1->nb[2] / src1->nb[0]) : 0u;
  8524. const uint32_t nb13 = src1 ? (uint32_t)(src1->nb[3] / src1->nb[0]) : 0u;
  8525. const uint32_t n_head_kv = src0->ne[2];
  8526. const uint32_t n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head_kv));
  8527. const float m0 = powf(2.0f, -(max_bias ) / n_head_log2);
  8528. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2);
  8529. ggml_vk_op_f32<vk_op_soft_max_push_constants>(ctx, subctx, src0, src1, src2, nullptr, dst, GGML_OP_SOFT_MAX, {
  8530. ncols,
  8531. src1 != nullptr ? nrows_y : (uint32_t)0,
  8532. (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], (uint32_t)src0->ne[2],
  8533. ne12, ne13,
  8534. nb11, nb12, nb13,
  8535. scale, max_bias,
  8536. m0, m1,
  8537. n_head_log2,
  8538. nrows_x,
  8539. src2 != nullptr
  8540. });
  8541. }
  8542. 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) {
  8543. float * op_params = (float *)dst->op_params;
  8544. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_SOFT_MAX_BACK, { (uint32_t)src0->ne[0], (uint32_t)ggml_nrows(src0), op_params[0], op_params[1] });
  8545. }
  8546. static void ggml_vk_topk_moe(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_cgraph * cgraph, int node_idx) {
  8547. topk_moe_mode mode = ggml_vk_num_additional_ops_to_topk_moe_mode(ctx->num_additional_fused_ops);
  8548. ggml_tensor * logits = cgraph->nodes[node_idx + 0]->src[0];
  8549. ggml_tensor * weights = (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) ? cgraph->nodes[node_idx + 9] :
  8550. (mode == TOPK_MOE_EARLY_SOFTMAX) ? cgraph->nodes[node_idx + 4] :
  8551. cgraph->nodes[node_idx + 5];
  8552. ggml_tensor * ids = (mode == TOPK_MOE_LATE_SOFTMAX) ? cgraph->nodes[node_idx + 1] : cgraph->nodes[node_idx + 3];
  8553. GGML_ASSERT(logits->type == GGML_TYPE_F32);
  8554. GGML_ASSERT(weights->type == GGML_TYPE_F32);
  8555. GGML_ASSERT(ids->type == GGML_TYPE_I32);
  8556. const int n_experts = logits->ne[0];
  8557. const int n_rows = logits->ne[1];
  8558. const int n_expert_used = weights->ne[1];
  8559. GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) n_experts);
  8560. vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, cgraph->nodes[node_idx], GGML_OP_SOFT_MAX);
  8561. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8562. vk_subbuffer logits_buf = ggml_vk_tensor_subbuffer(ctx, logits);
  8563. vk_subbuffer weights_buf = ggml_vk_tensor_subbuffer(ctx, weights);
  8564. vk_subbuffer ids_buf = ggml_vk_tensor_subbuffer(ctx, ids);
  8565. vk_op_topk_moe_push_constants pc {};
  8566. pc.n_rows = n_rows;
  8567. pc.n_expert_used = n_expert_used;
  8568. if (mode == TOPK_MOE_EARLY_SOFTMAX_NORM) {
  8569. ggml_tensor * clamp = cgraph->nodes[node_idx + 7];
  8570. pc.clamp_min = ggml_get_op_params_f32(clamp, 0);
  8571. pc.clamp_max = ggml_get_op_params_f32(clamp, 1);
  8572. }
  8573. GGML_ASSERT(n_expert_used <= n_experts);
  8574. const uint32_t rows_per_block = 4;
  8575. std::array<uint32_t, 3> elements = { CEIL_DIV(n_rows, rows_per_block), 1, 1 };
  8576. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {logits_buf, weights_buf, ids_buf}, pc, elements);
  8577. }
  8578. static void ggml_vk_rope(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_cgraph * cgraph, int node_idx, bool backprop) {
  8579. ggml_tensor * dst = cgraph->nodes[node_idx];
  8580. const ggml_tensor * src0 = dst->src[0];
  8581. const ggml_tensor * src1 = dst->src[1];
  8582. const ggml_tensor * src2 = dst->src[2];
  8583. const ggml_tensor * src3 = nullptr;
  8584. const int n_dims = ((int32_t *) dst->op_params)[1];
  8585. const int mode = ((int32_t *) dst->op_params)[2];
  8586. // const int n_ctx = ((int32_t *) dst->op_params)[3];
  8587. const int n_ctx_orig = ((int32_t *) dst->op_params)[4];
  8588. const float freq_base = ((float *) dst->op_params)[5];
  8589. const float beta_fast = ((float *) dst->op_params)[9];
  8590. const float beta_slow = ((float *) dst->op_params)[10];
  8591. int sections[4] {};
  8592. if (mode & GGML_ROPE_TYPE_MROPE) {
  8593. memcpy(sections, (int32_t *) dst->op_params + 11, sizeof(int)*4);
  8594. }
  8595. float corr_dims[2];
  8596. ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
  8597. uint32_t set_rows_stride = 0;
  8598. // Fused rope + view + set_rows passes the set_rows destination stride in set_rows_stride
  8599. // and overrides the dst and sets src3=row_indices
  8600. if (ctx->num_additional_fused_ops > 0) {
  8601. set_rows_stride = cgraph->nodes[node_idx + 2]->nb[1] / ggml_type_size(cgraph->nodes[node_idx + 2]->type);
  8602. src3 = cgraph->nodes[node_idx + 2]->src[1];
  8603. dst = cgraph->nodes[node_idx + 2];
  8604. }
  8605. ggml_vk_op_f32<vk_op_rope_push_constants>(ctx, subctx, src0, src1, src2, src3, dst, GGML_OP_ROPE,
  8606. ggml_vk_make_rope_constants(cgraph->nodes[node_idx], src0, src2 != nullptr, backprop, set_rows_stride));
  8607. }
  8608. static void ggml_vk_argsort(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8609. const uint32_t * op_params = (const uint32_t *)dst->op_params;
  8610. uint32_t ncols = src0->ne[0];
  8611. uint32_t nrows = ggml_nrows(src0);
  8612. uint32_t ncols_pad_log2 = (uint32_t)ceilf(log2f(float(ncols)));
  8613. uint32_t ncolsp2 = 1 << ncols_pad_log2;
  8614. vk_op_argsort_push_constants pc { ncols, ncolsp2, ncols_pad_log2, nrows, op_params[0], 0, 0, 0, 0, };
  8615. // Pick the largest workgroup size <= ncolsp2
  8616. uint32_t pipeline_idx = std::min(ncols_pad_log2, num_argsort_pipelines - 1);
  8617. // Use the "small" argsort shader if the whole sort can be done by a single workgroup.
  8618. bool use_small = ncols_pad_log2 <= ctx->device->max_workgroup_size_log2 &&
  8619. ctx->device->pipeline_argsort_f32[pipeline_idx] != nullptr;
  8620. vk_pipeline pipeline = use_small ? ctx->device->pipeline_argsort_f32[pipeline_idx]
  8621. : ctx->device->pipeline_argsort_large_f32[pipeline_idx];
  8622. vk_subbuffer src0_buf = ggml_vk_tensor_subbuffer(ctx, src0);
  8623. vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
  8624. vk_subbuffer subbuf1 = dst_buf;
  8625. // Reserve space for ivec2 per element, with rows padded to a power of two
  8626. if (!use_small) {
  8627. const size_t x_sz = size_t{ncolsp2} * nrows * 2 * sizeof(int);
  8628. if (ctx->prealloc_size_x < x_sz) {
  8629. ctx->prealloc_size_x = x_sz;
  8630. ggml_vk_preallocate_buffers(ctx, subctx);
  8631. }
  8632. if (ctx->prealloc_x_need_sync) {
  8633. ggml_vk_sync_buffers(ctx, subctx);
  8634. }
  8635. subbuf1 = { ctx->prealloc_x, 0, ctx->prealloc_x->size };
  8636. }
  8637. std::array<uint32_t, 3> elements;
  8638. elements[0] = ncolsp2;
  8639. elements[1] = std::min((uint32_t)ggml_nrows(src0), ctx->device->properties.limits.maxComputeWorkGroupCount[1]);
  8640. elements[2] = 1;
  8641. // First dispatch initializes tmp_idx and does the first N passes where
  8642. // there is only communication between threads in the same workgroup.
  8643. {
  8644. vk_op_argsort_push_constants pc2 = pc;
  8645. pc2.outer_start = 0;
  8646. pc2.outer_end = std::min(ncols_pad_log2, ctx->device->max_workgroup_size_log2);
  8647. pc2.inner_start = 0;
  8648. pc2.inner_end = 100;
  8649. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8650. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements);
  8651. }
  8652. if (!use_small) {
  8653. ggml_vk_sync_buffers(ctx, subctx);
  8654. // Loop over outer/inner passes, synchronizing between each pass.
  8655. for (uint32_t outer = ctx->device->max_workgroup_size_log2; outer < ncols_pad_log2; ++outer) {
  8656. for (uint32_t inner = 0; inner < outer + 1; ++inner) {
  8657. vk_op_argsort_push_constants pc2 = pc;
  8658. pc2.outer_start = outer;
  8659. pc2.outer_end = outer + 1;
  8660. pc2.inner_start = inner;
  8661. pc2.inner_end = inner + 1;
  8662. // When the inner idx is large enough, there's only communication
  8663. // within a workgroup. So the remaining inner iterations can all
  8664. // run in the same dispatch.
  8665. if (outer - inner < pipeline_idx) {
  8666. pc2.inner_end = 100;
  8667. inner = outer;
  8668. pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx];
  8669. } else {
  8670. // Smaller workgroup empirically seems to perform better
  8671. pipeline = ctx->device->pipeline_argsort_large_f32[pipeline_idx - 2];
  8672. }
  8673. ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
  8674. ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { src0_buf, subbuf1, dst_buf }, pc2, elements);
  8675. ggml_vk_sync_buffers(ctx, subctx);
  8676. }
  8677. }
  8678. ctx->prealloc_x_need_sync = true;
  8679. }
  8680. }
  8681. static void ggml_vk_sum(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8682. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, ggml_nelements(src0));
  8683. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM, p);
  8684. }
  8685. static void ggml_vk_sum_rows(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8686. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8687. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SUM_ROWS, p);
  8688. }
  8689. static void ggml_vk_mean(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8690. vk_op_sum_rows_push_constants p = vk_op_sum_rows_push_constants_init(src0, dst, src0->ne[0]);
  8691. p.weight = 1.0f / (float)src0->ne[0];
  8692. ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_MEAN, p);
  8693. }
  8694. static void ggml_vk_argmax(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8695. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_ARGMAX, { (uint32_t)src0->ne[0], (uint32_t)src0->ne[1], 0.0f, 0.0f });
  8696. }
  8697. 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) {
  8698. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_COUNT_EQUAL, { (uint32_t)ggml_nelements(src0), 0, 0.0f, 0.0f });
  8699. }
  8700. static void ggml_vk_im2col(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8701. const int32_t s0 = dst->op_params[0];
  8702. const int32_t s1 = dst->op_params[1];
  8703. const int32_t p0 = dst->op_params[2];
  8704. const int32_t p1 = dst->op_params[3];
  8705. const int32_t d0 = dst->op_params[4];
  8706. const int32_t d1 = dst->op_params[5];
  8707. const bool is_2D = dst->op_params[6] == 1;
  8708. const uint32_t IC = src1->ne[is_2D ? 2 : 1];
  8709. const uint32_t IH = is_2D ? src1->ne[1] : 1;
  8710. const uint32_t IW = src1->ne[0];
  8711. const uint32_t KH = is_2D ? src0->ne[1] : 1;
  8712. const uint32_t KW = src0->ne[0];
  8713. const uint32_t OH = is_2D ? dst->ne[2] : 1;
  8714. const uint32_t OW = dst->ne[1];
  8715. const uint32_t offset_delta = src1->nb[is_2D ? 2 : 1] / 4; // nb is byte offset, src is type float32
  8716. const uint32_t batch_offset = src1->nb[is_2D ? 3 : 2] / 4; // nb is byte offset, src is type float32
  8717. const uint32_t pelements = OW * KW * KH;
  8718. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8719. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  8720. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  8721. ggml_vk_op_f32<vk_op_im2col_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL, {
  8722. dst_addr,
  8723. batch_offset, offset_delta,
  8724. IC, IW, IH, OW, OH, KW, KH,
  8725. pelements,
  8726. IC * KH * KW,
  8727. s0, s1, p0, p1, d0, d1,
  8728. });
  8729. }
  8730. static void ggml_vk_im2col_3d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
  8731. GGML_TENSOR_BINARY_OP_LOCALS
  8732. const int32_t s0 = ((const int32_t *)(dst->op_params))[0];
  8733. const int32_t s1 = ((const int32_t *)(dst->op_params))[1];
  8734. const int32_t s2 = ((const int32_t *)(dst->op_params))[2];
  8735. const int32_t p0 = ((const int32_t *)(dst->op_params))[3];
  8736. const int32_t p1 = ((const int32_t *)(dst->op_params))[4];
  8737. const int32_t p2 = ((const int32_t *)(dst->op_params))[5];
  8738. const int32_t d0 = ((const int32_t *)(dst->op_params))[6];
  8739. const int32_t d1 = ((const int32_t *)(dst->op_params))[7];
  8740. const int32_t d2 = ((const int32_t *)(dst->op_params))[8];
  8741. const int32_t IC = ((const int32_t *)(dst->op_params))[9];
  8742. const int64_t N = ne13 / IC;
  8743. const int64_t ID = ne12;
  8744. const int64_t IH = ne11;
  8745. const int64_t IW = ne10;
  8746. const int64_t KD = ne02;
  8747. const int64_t KH = ne01;
  8748. const int64_t KW = ne00;
  8749. const int64_t OD = ne3 / N;
  8750. const int64_t OH = ne2;
  8751. const int64_t OW = ne1;
  8752. const ggml_backend_vk_buffer_context * d_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  8753. const vk_buffer d_buf = d_buf_ctx->dev_buffer;
  8754. const vk::DeviceAddress dst_addr = d_buf->bda_addr + vk_tensor_offset(dst) + dst->view_offs;
  8755. vk_op_im2col_3d_push_constants pc {};
  8756. pc.dst_addr = dst_addr;
  8757. pc.nb10 = nb10 / ggml_type_size(src1->type);
  8758. pc.nb11 = nb11 / ggml_type_size(src1->type);
  8759. pc.nb12 = nb12 / ggml_type_size(src1->type);
  8760. pc.nb13 = nb13 / ggml_type_size(src1->type);
  8761. pc.s0 = s0;
  8762. pc.s1 = s1;
  8763. pc.s2 = s2;
  8764. pc.p0 = p0;
  8765. pc.p1 = p1;
  8766. pc.p2 = p2;
  8767. pc.d0 = d0;
  8768. pc.d1 = d1;
  8769. pc.d2 = d2;
  8770. pc.IW = IW;
  8771. pc.IH = IH;
  8772. pc.ID = ID;
  8773. pc.IC = IC;
  8774. pc.KW = KW;
  8775. pc.OH = OH;
  8776. pc.KD_KH_KW = KD*KH*KW;
  8777. pc.KH_KW = KH*KW;
  8778. pc.IC_KD_KH_KW = IC*KD*KH*KW;
  8779. pc.N_OD_OH = N*OD*OH;
  8780. pc.OD_OH = OD*OH;
  8781. pc.OD_OH_OW_IC_KD_KH_KW = OD*OH*OW*IC*KD*KH*KW;
  8782. pc.OH_OW_IC_KD_KH_KW = OH*OW*IC*KD*KH*KW;
  8783. pc.OW_IC_KD_KH_KW = OW*IC*KD*KH*KW;
  8784. ggml_vk_op_f32<vk_op_im2col_3d_push_constants>(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_IM2COL_3D, std::move(pc));
  8785. }
  8786. static void ggml_vk_timestep_embedding(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8787. const uint32_t dim = dst->op_params[0];
  8788. const uint32_t max_period = dst->op_params[1];
  8789. const uint32_t nb1 = dst->nb[1] / ggml_type_size(dst->type);
  8790. ggml_vk_op_f32<vk_op_timestep_embedding_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_TIMESTEP_EMBEDDING, {
  8791. nb1, dim, max_period,
  8792. });
  8793. }
  8794. 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) {
  8795. // src0: (K, Cout, Cin, 1) -- kernel
  8796. // src1: (L, Cin, 1, 1) -- input
  8797. // dst: (*, Cout, 1, 1)
  8798. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  8799. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8800. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  8801. GGML_TENSOR_BINARY_OP_LOCALS
  8802. GGML_ASSERT(nb00 == sizeof(float));
  8803. GGML_ASSERT(nb10 == sizeof(float));
  8804. const int32_t s0 = dst->op_params[0];
  8805. vk_op_conv_transpose_1d_push_constants p{};
  8806. p.Cout = static_cast<uint32_t>(ne01);
  8807. p.Cin = static_cast<uint32_t>(ne02);
  8808. p.K = static_cast<uint32_t>(ne00);
  8809. p.L = static_cast<uint32_t>(ne10);
  8810. p.KL = static_cast<uint32_t>(ne0);
  8811. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8812. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8813. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8814. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8815. p.s0 = static_cast<uint32_t>(s0);
  8816. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_1D, std::move(p));
  8817. }
  8818. static void ggml_vk_pool_2d(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8819. uint32_t op = static_cast<uint32_t>(dst->op_params[0]);
  8820. const int32_t k1 = dst->op_params[1];
  8821. const int32_t k0 = dst->op_params[2];
  8822. const int32_t s1 = dst->op_params[3];
  8823. const int32_t s0 = dst->op_params[4];
  8824. const int32_t p1 = dst->op_params[5];
  8825. const int32_t p0 = dst->op_params[6];
  8826. const uint32_t IH = src0->ne[1];
  8827. const uint32_t IW = src0->ne[0];
  8828. const uint32_t N = dst->ne[3];
  8829. const uint32_t OC = dst->ne[2];
  8830. const uint32_t OH = dst->ne[1];
  8831. const uint32_t OW = dst->ne[0];
  8832. const uint32_t parallel_elements = N * OC * OH * OW;
  8833. ggml_vk_op_f32<vk_op_pool2d_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_POOL_2D, {
  8834. IW, IH, OW, OH, OC,
  8835. parallel_elements,
  8836. op,
  8837. k0, k1, s0, s1, p0, p1,
  8838. });
  8839. }
  8840. static void ggml_vk_conv_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8841. const ggml_tensor * src1, ggml_tensor * dst) {
  8842. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8843. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8844. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8845. GGML_TENSOR_BINARY_OP_LOCALS
  8846. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8847. GGML_ASSERT(nb10 == sizeof(float));
  8848. GGML_ASSERT(nb0 == sizeof(float));
  8849. vk_op_conv2d_push_constants p{};
  8850. p.Cout = static_cast<uint32_t>(ne03);
  8851. p.Cin = static_cast<uint32_t>(ne02);
  8852. p.N = static_cast<uint32_t>(ne13);
  8853. p.KW = static_cast<uint32_t>(ne00);
  8854. p.KH = static_cast<uint32_t>(ne01);
  8855. p.W = static_cast<uint32_t>(ne10);
  8856. p.H = static_cast<uint32_t>(ne11);
  8857. p.OW = static_cast<uint32_t>(ne0);
  8858. p.OH = static_cast<uint32_t>(ne1);
  8859. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8860. p.s1 = static_cast<uint32_t>(dst->op_params[1]);
  8861. p.p0 = static_cast<uint32_t>(dst->op_params[2]);
  8862. p.p1 = static_cast<uint32_t>(dst->op_params[3]);
  8863. p.d0 = static_cast<uint32_t>(dst->op_params[4]);
  8864. p.d1 = static_cast<uint32_t>(dst->op_params[5]);
  8865. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8866. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8867. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  8868. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8869. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  8870. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  8871. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8872. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  8873. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  8874. GGML_ASSERT(ne03 == ne2);
  8875. GGML_ASSERT(ne02 == ne12);
  8876. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D, std::move(p));
  8877. }
  8878. static void ggml_vk_conv_transpose_2d(ggml_backend_vk_context * ctx, vk_context & subctx, const ggml_tensor * src0,
  8879. const ggml_tensor * src1, ggml_tensor * dst) {
  8880. GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16);
  8881. GGML_ASSERT(src1->type == GGML_TYPE_F32);
  8882. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  8883. GGML_TENSOR_BINARY_OP_LOCALS
  8884. GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
  8885. GGML_ASSERT(nb10 == sizeof(float));
  8886. GGML_ASSERT(nb0 == sizeof(float));
  8887. vk_op_conv_transpose_2d_push_constants p{};
  8888. p.Cout = static_cast<uint32_t>(ne02);
  8889. p.Cin = static_cast<uint32_t>(ne03);
  8890. p.N = static_cast<uint32_t>(ne13);
  8891. p.KW = static_cast<uint32_t>(ne00);
  8892. p.KH = static_cast<uint32_t>(ne01);
  8893. p.W = static_cast<uint32_t>(ne10);
  8894. p.H = static_cast<uint32_t>(ne11);
  8895. p.OW = static_cast<uint32_t>(ne0);
  8896. p.OH = static_cast<uint32_t>(ne1);
  8897. p.s0 = static_cast<uint32_t>(dst->op_params[0]);
  8898. p.s1 = static_cast<uint32_t>(dst->op_params[0]);
  8899. p.p0 = 0;
  8900. p.p1 = 0;
  8901. p.d0 = 1;
  8902. p.d1 = 1;
  8903. p.nb01 = static_cast<uint32_t>(nb01 / nb00);
  8904. p.nb02 = static_cast<uint32_t>(nb02 / nb00);
  8905. p.nb03 = static_cast<uint32_t>(nb03 / nb00);
  8906. p.nb11 = static_cast<uint32_t>(nb11 / nb10);
  8907. p.nb12 = static_cast<uint32_t>(nb12 / nb10);
  8908. p.nb13 = static_cast<uint32_t>(nb13 / nb10);
  8909. p.nb1 = static_cast<uint32_t>(nb1 / nb0);
  8910. p.nb2 = static_cast<uint32_t>(nb2 / nb0);
  8911. p.nb3 = static_cast<uint32_t>(nb3 / nb0);
  8912. GGML_ASSERT(ne02 == ne2);
  8913. GGML_ASSERT(ne03 == ne12);
  8914. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_TRANSPOSE_2D, std::move(p));
  8915. }
  8916. 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) {
  8917. vk_op_conv2d_dw_push_constants p{};
  8918. p.ne = ggml_nelements(dst);
  8919. p.channels = dst->ne[2];
  8920. p.batches = dst->ne[3];
  8921. p.dst_w = dst->ne[0];
  8922. p.dst_h = dst->ne[1];
  8923. p.src_w = src1->ne[0];
  8924. p.src_h = src1->ne[1];
  8925. p.knl_w = src0->ne[0];
  8926. p.knl_h = src0->ne[1];
  8927. p.stride_x = dst->op_params[0];
  8928. p.stride_y = dst->op_params[1];
  8929. p.pad_x = dst->op_params[2];
  8930. p.pad_y = dst->op_params[3];
  8931. p.dilation_x = dst->op_params[4];
  8932. p.dilation_y = dst->op_params[5];
  8933. GGML_ASSERT(src0->ne[3] == p.channels);
  8934. GGML_ASSERT(src1->ne[3] == p.batches);
  8935. ggml_vk_op_f32(ctx, subctx, src0, src1, nullptr, nullptr, dst, GGML_OP_CONV_2D_DW, std::move(p));
  8936. }
  8937. static void ggml_vk_leaky_relu(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) {
  8938. const float * op_params = (const float *)dst->op_params;
  8939. ggml_vk_op_f32<vk_op_push_constants>(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_LEAKY_RELU, { (uint32_t)ggml_nelements(src0), 0, op_params[0], 0.0f });
  8940. }
  8941. #ifdef GGML_VULKAN_RUN_TESTS
  8942. static void ggml_vk_print_matrix_area(const void * data, ggml_type type, int ne0, int ne1, int i0, int i1, int i2) {
  8943. if (type != GGML_TYPE_F32 && type != GGML_TYPE_F16) {
  8944. return;
  8945. }
  8946. i0 = std::max(i0, 5);
  8947. i1 = std::max(i1, 5);
  8948. i2 = std::max(i2, 0);
  8949. fprintf(stderr, " ");
  8950. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8951. fprintf(stderr, "%7d ", idx1);
  8952. }
  8953. fprintf(stderr, "\n");
  8954. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  8955. fprintf(stderr, "%7d: ", idx0);
  8956. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  8957. if (idx0 >= 0 && idx0 < ne0 && idx1 >= 0 && idx1 < ne1) {
  8958. float val;
  8959. if (type == GGML_TYPE_F32) {
  8960. val = *((const float *) data + i2*ne1*ne0 + idx1*ne0 + idx0);
  8961. } else if (type == GGML_TYPE_F16) {
  8962. val = ggml_fp16_to_fp32(*((const ggml_fp16_t *) data + i2*ne1*ne0 + idx1*ne0 + idx0));
  8963. } else {
  8964. GGML_ABORT("fatal error");
  8965. }
  8966. fprintf(stderr, "% 7.2f ", val);
  8967. } else {
  8968. fprintf(stderr, " ");
  8969. }
  8970. }
  8971. fprintf(stderr, "\n");
  8972. }
  8973. }
  8974. template <typename X_TYPE, typename Y_TYPE>
  8975. 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) {
  8976. VK_LOG_DEBUG("ggml_vk_test_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << shader_size << ")");
  8977. const size_t x_ne = m * k * batch;
  8978. const size_t y_ne = k * n * batch;
  8979. const size_t d_ne = m * n * batch;
  8980. vk_pipeline p;
  8981. std::string shname;
  8982. if (shader_size == 0) {
  8983. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8984. p = ctx->device->pipeline_matmul_f32->a_s;
  8985. shname = "F32_ALIGNED_S";
  8986. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8987. p = ctx->device->pipeline_matmul_f32_f16->a_s;
  8988. shname = "F32_F16_ALIGNED_S";
  8989. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  8990. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_s;
  8991. shname = "F16_F32_ALIGNED_S";
  8992. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  8993. p = ctx->device->pipeline_matmul_f16.f32acc->a_s;
  8994. shname = "F16_ALIGNED_S";
  8995. } else {
  8996. GGML_ABORT("fatal error");
  8997. }
  8998. } else if (shader_size == 1) {
  8999. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9000. p = ctx->device->pipeline_matmul_f32->a_m;
  9001. shname = "F32_ALIGNED_M";
  9002. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9003. p = ctx->device->pipeline_matmul_f32_f16->a_m;
  9004. shname = "F32_F16_ALIGNED_M";
  9005. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9006. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_m;
  9007. shname = "F16_F32_ALIGNED_M";
  9008. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9009. p = ctx->device->pipeline_matmul_f16.f32acc->a_m;
  9010. shname = "F16_ALIGNED_M";
  9011. } else {
  9012. GGML_ABORT("fatal error");
  9013. }
  9014. } else if (shader_size == 2) {
  9015. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9016. p = ctx->device->pipeline_matmul_f32->a_l;
  9017. shname = "F32_ALIGNED_L";
  9018. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9019. p = ctx->device->pipeline_matmul_f32_f16->a_l;
  9020. shname = "F32_F16_ALIGNED_L";
  9021. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9022. p = ctx->device->pipeline_matmul_f16_f32.f32acc->a_l;
  9023. shname = "F16_F32_ALIGNED_L";
  9024. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9025. p = ctx->device->pipeline_matmul_f16.f32acc->a_l;
  9026. shname = "F16_ALIGNED_L";
  9027. } else {
  9028. GGML_ABORT("fatal error");
  9029. }
  9030. } else {
  9031. GGML_ASSERT(0);
  9032. }
  9033. const size_t kpad = ggml_vk_align_size(k, p->align);
  9034. if (k != kpad) {
  9035. if (shader_size == 0) {
  9036. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9037. p = ctx->device->pipeline_matmul_f32->s;
  9038. shname = "F32_S";
  9039. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9040. p = ctx->device->pipeline_matmul_f32_f16->s;
  9041. shname = "F32_F16_S";
  9042. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9043. p = ctx->device->pipeline_matmul_f16_f32.f32acc->s;
  9044. shname = "F16_F32_S";
  9045. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9046. p = ctx->device->pipeline_matmul_f16.f32acc->s;
  9047. shname = "F16_S";
  9048. }
  9049. } else if (shader_size == 1) {
  9050. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9051. p = ctx->device->pipeline_matmul_f32->m;
  9052. shname = "F32_M";
  9053. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9054. p = ctx->device->pipeline_matmul_f32_f16->m;
  9055. shname = "F32_F16_M";
  9056. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9057. p = ctx->device->pipeline_matmul_f16_f32.f32acc->m;
  9058. shname = "F16_F32_M";
  9059. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9060. p = ctx->device->pipeline_matmul_f16.f32acc->m;
  9061. shname = "F16_M";
  9062. }
  9063. } else if (shader_size == 2) {
  9064. if (std::is_same<float, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9065. p = ctx->device->pipeline_matmul_f32->l;
  9066. shname = "F32_L";
  9067. } else if (std::is_same<float, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9068. p = ctx->device->pipeline_matmul_f32_f16->l;
  9069. shname = "F32_F16_L";
  9070. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<float, Y_TYPE>()) {
  9071. p = ctx->device->pipeline_matmul_f16_f32.f32acc->l;
  9072. shname = "F16_F32_L";
  9073. } else if (std::is_same<ggml_fp16_t, X_TYPE>() && std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9074. p = ctx->device->pipeline_matmul_f16.f32acc->l;
  9075. shname = "F16_L";
  9076. }
  9077. }
  9078. }
  9079. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9080. if (split_k > 1) {
  9081. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9082. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9083. // Resize buffer
  9084. if (ctx->prealloc_split_k != nullptr) {
  9085. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9086. }
  9087. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9088. }
  9089. }
  9090. ggml_pipeline_allocate_descriptor_sets(ctx);
  9091. vk_buffer d_X = ggml_vk_create_buffer_check(ctx->device, sizeof(X_TYPE) * x_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9092. vk_buffer d_Y = ggml_vk_create_buffer_check(ctx->device, sizeof(Y_TYPE) * y_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9093. vk_buffer d_D = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9094. X_TYPE* x = (X_TYPE *) malloc(sizeof(X_TYPE) * x_ne);
  9095. Y_TYPE* y = (Y_TYPE *) malloc(sizeof(Y_TYPE) * y_ne);
  9096. float* d = (float *) malloc(sizeof(float) * d_ne);
  9097. for (size_t i = 0; i < x_ne; i++) {
  9098. if (std::is_same<float, X_TYPE>()) {
  9099. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9100. // x[i] = 1.0f;
  9101. // x[i] = i + 1;
  9102. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9103. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9104. x[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9105. // x[i] = ggml_fp32_to_fp16(1.0f);
  9106. // x[i] = ggml_fp32_to_fp16(i + 1);
  9107. // x[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9108. } else {
  9109. GGML_ABORT("fatal error");
  9110. }
  9111. }
  9112. for (size_t i = 0; i < y_ne; i++) {
  9113. if (std::is_same<float, Y_TYPE>()) {
  9114. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9115. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9116. // y[i] = i + 1;
  9117. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9118. y[i] = ggml_fp32_to_fp16((rand() / (float)RAND_MAX) * 2.0f - 1.0f);
  9119. // y[i] = ggml_fp32_to_fp16((i % k == i / k) ? 1.0f : 0.0f);
  9120. // y[i] = ggml_fp32_to_fp16(i + 1);
  9121. } else {
  9122. GGML_ABORT("fatal error");
  9123. }
  9124. }
  9125. ggml_vk_buffer_write(d_X, 0, x, sizeof(X_TYPE) * k * m * batch);
  9126. ggml_vk_buffer_write(d_Y, 0, y, sizeof(Y_TYPE) * k * n * batch);
  9127. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9128. ggml_vk_ctx_begin(ctx->device, subctx);
  9129. for (size_t i = 0; i < num_it; i++) {
  9130. ggml_vk_matmul(
  9131. ctx, subctx, p, ggml_vk_subbuffer(ctx, d_X), ggml_vk_subbuffer(ctx, d_Y), ggml_vk_subbuffer(ctx, d_D), ggml_vk_subbuffer(ctx, ctx->prealloc_split_k),
  9132. m, n, k,
  9133. k, k, m, k*m, k*n, m*n,
  9134. split_k, batch, batch, batch, 1, 1, n
  9135. );
  9136. }
  9137. ggml_vk_ctx_end(subctx);
  9138. auto begin = std::chrono::high_resolution_clock::now();
  9139. ggml_vk_submit(subctx, ctx->fence);
  9140. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_matmul waitForFences");
  9141. ctx->device->device.resetFences({ ctx->fence });
  9142. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9143. auto end = std::chrono::high_resolution_clock::now();
  9144. double time = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9145. // copy dst to host
  9146. ggml_vk_buffer_read(d_D, 0, d, sizeof(float) * d_ne);
  9147. float * d_chk = (float *) malloc(sizeof(float) * d_ne);
  9148. ggml_init_params iparams = {
  9149. /*.mem_size =*/ 1024*1024*1024,
  9150. /*.mem_buffer =*/ NULL,
  9151. /*.no_alloc =*/ true,
  9152. };
  9153. ggml_context * ggml_ctx = ggml_init(iparams);
  9154. ggml_type src0_type;
  9155. ggml_type src1_type;
  9156. if (std::is_same<float, X_TYPE>()) {
  9157. src0_type = GGML_TYPE_F32;
  9158. } else if (std::is_same<ggml_fp16_t, X_TYPE>()) {
  9159. src0_type = GGML_TYPE_F16;
  9160. } else {
  9161. GGML_ABORT("fatal error");
  9162. }
  9163. if (std::is_same<float, Y_TYPE>()) {
  9164. src1_type = GGML_TYPE_F32;
  9165. } else if (std::is_same<ggml_fp16_t, Y_TYPE>()) {
  9166. src1_type = GGML_TYPE_F16;
  9167. } else {
  9168. GGML_ABORT("fatal error");
  9169. }
  9170. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, src0_type, k, m, batch);
  9171. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, src1_type, k, n, batch);
  9172. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9173. src0_ggml->data = x;
  9174. src1_ggml->data = y;
  9175. tensor_ggml->data = d_chk;
  9176. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9177. ggml_build_forward_expand(cgraph, tensor_ggml);
  9178. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9179. ggml_free(ggml_ctx);
  9180. double avg_err = 0.0;
  9181. int first_err_n = -1;
  9182. int first_err_m = -1;
  9183. int first_err_b = -1;
  9184. for (size_t i = 0; i < m*n*batch; i++) {
  9185. double err = std::fabs(d[i] - d_chk[i]);
  9186. avg_err += err;
  9187. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9188. first_err_b = i / (m * n);
  9189. first_err_n = (i % (m * n)) / m;
  9190. first_err_m = (i % (m * n)) % m;
  9191. }
  9192. }
  9193. avg_err /= m * n;
  9194. double tflops = 2.0*m*n*k*batch*num_it / (time / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9195. 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;
  9196. if (avg_err > 0.1 || std::isnan(avg_err)) {
  9197. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9198. std::cerr << "Actual result: " << std::endl << std::endl;
  9199. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9200. std::cerr << "Expected result: " << std::endl << std::endl;
  9201. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9202. if (split_k > 1) {
  9203. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9204. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9205. std::cerr << "d_buf0: " << std::endl << std::endl;
  9206. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9207. std::cerr << "d_buf1: " << std::endl << std::endl;
  9208. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9209. std::cerr << "d_buf2: " << std::endl << std::endl;
  9210. 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);
  9211. std::cerr << "d_buf3: " << std::endl << std::endl;
  9212. 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);
  9213. free(split_k_buf);
  9214. }
  9215. }
  9216. free(d_chk);
  9217. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  9218. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  9219. ggml_vk_destroy_buffer(d_X);
  9220. ggml_vk_destroy_buffer(d_Y);
  9221. ggml_vk_destroy_buffer(d_D);
  9222. free(x);
  9223. free(y);
  9224. free(d);
  9225. }
  9226. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, int i0, int i1, int i2, int i3) {
  9227. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16) {
  9228. return;
  9229. }
  9230. i0 = std::max(i0, 5);
  9231. i1 = std::max(i1, 5);
  9232. i2 = std::max(i2, 0);
  9233. i3 = std::max(i3, 0);
  9234. fprintf(stderr, " ");
  9235. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9236. fprintf(stderr, "%7d ", idx1);
  9237. }
  9238. fprintf(stderr, "\n");
  9239. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  9240. fprintf(stderr, "%7d: ", idx0);
  9241. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  9242. 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]) {
  9243. float val;
  9244. if (tensor->type == GGML_TYPE_F32) {
  9245. val = *(float *) ((char *) tensor->data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  9246. } else if (tensor->type == GGML_TYPE_F16) {
  9247. 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]));
  9248. } else {
  9249. GGML_ABORT("fatal error");
  9250. }
  9251. fprintf(stderr, "% 7.2f ", val);
  9252. } else {
  9253. fprintf(stderr, " ");
  9254. }
  9255. }
  9256. fprintf(stderr, "\n");
  9257. }
  9258. }
  9259. static void ggml_vk_quantize_data(const float * from, void * to, size_t ne, ggml_type quant) {
  9260. ggml_quantize_chunk(quant, from, to, 0, 1, ne, nullptr);
  9261. }
  9262. static void ggml_vk_dequantize_data(const void * from, float * to, size_t ne, ggml_type quant) {
  9263. if (quant == GGML_TYPE_F32) {
  9264. memcpy(to, from, sizeof(float) * ne);
  9265. return;
  9266. }
  9267. const auto * tt = ggml_get_type_traits(quant);
  9268. ggml_to_float_t dequant_fn = tt->to_float;
  9269. dequant_fn(from, to, ne);
  9270. }
  9271. static void ggml_vk_test_dequant(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9272. VK_LOG_DEBUG("ggml_vk_test_dequant(" << ne << ")");
  9273. const size_t x_sz = sizeof(float) * ne;
  9274. const size_t x_sz_f16 = sizeof(ggml_fp16_t) * ne;
  9275. const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9276. float * x = (float *) malloc(x_sz);
  9277. void * qx = malloc(qx_sz);
  9278. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9279. vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz_f16, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9280. float * x_ref = (float *) malloc(x_sz);
  9281. ggml_fp16_t * x_chk = (ggml_fp16_t *) malloc(x_sz_f16);
  9282. for (size_t i = 0; i < ne; i++) {
  9283. x[i] = rand() / (float)RAND_MAX;
  9284. }
  9285. vk_pipeline p = ggml_vk_get_to_fp16(ctx, quant);
  9286. ggml_vk_quantize_data(x, qx, ne, quant);
  9287. ggml_vk_dequantize_data(qx, x_ref, ne, quant);
  9288. ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9289. ggml_pipeline_allocate_descriptor_sets(ctx);
  9290. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9291. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9292. ggml_vk_ctx_begin(ctx->device, subctx);
  9293. const std::vector<uint32_t> pc = { 1, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne, (uint32_t)ne };
  9294. 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});
  9295. ggml_vk_ctx_end(subctx);
  9296. auto begin = std::chrono::high_resolution_clock::now();
  9297. ggml_vk_submit(subctx, ctx->fence);
  9298. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9299. ctx->device->device.resetFences({ ctx->fence });
  9300. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9301. auto end = std::chrono::high_resolution_clock::now();
  9302. double ms_dequant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9303. ggml_vk_buffer_read(x_buf, 0, x_chk, x_sz_f16);
  9304. int first_err = -1;
  9305. double avg_err = 0.0;
  9306. for (size_t i = 0; i < ne; i++) {
  9307. double error = std::fabs(x_ref[i] - ggml_fp16_to_fp32(x_chk[i]));
  9308. avg_err += error;
  9309. if (first_err < 0 && error > 0.05) {
  9310. first_err = i;
  9311. }
  9312. }
  9313. avg_err /= ne;
  9314. std::cerr << "TEST DEQUANT " << ggml_type_name(quant) << " time=" << ms_dequant << "ms avg_err=" << avg_err << std::endl;
  9315. if (avg_err > 0.1) {
  9316. std::cerr << "first_error = " << first_err << std::endl;
  9317. std::cerr << "Actual result: " << std::endl << std::endl;
  9318. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9319. std::cerr << ggml_fp16_to_fp32(x_chk[i]) << ", ";
  9320. }
  9321. std::cerr << std::endl << "Expected result: " << std::endl << std::endl;
  9322. for (int i = std::max(0, first_err - 5); i < std::min((int)ne, first_err + 5); i++) {
  9323. std::cerr << x_ref[i] << ", ";
  9324. }
  9325. std::cerr << std::endl;
  9326. }
  9327. ggml_vk_destroy_buffer(x_buf);
  9328. ggml_vk_destroy_buffer(qx_buf);
  9329. free(x);
  9330. free(qx);
  9331. free(x_ref);
  9332. free(x_chk);
  9333. }
  9334. // This does not work without ggml q8_1 quantization support
  9335. //
  9336. // typedef uint16_t ggml_half;
  9337. // typedef uint32_t ggml_half2;
  9338. //
  9339. // #define QK8_1 32
  9340. // typedef struct {
  9341. // union {
  9342. // struct {
  9343. // ggml_half d; // delta
  9344. // ggml_half s; // d * sum(qs[i])
  9345. // } GGML_COMMON_AGGR_S;
  9346. // ggml_half2 ds;
  9347. // } GGML_COMMON_AGGR_U;
  9348. // int8_t qs[QK8_1]; // quants
  9349. // } block_q8_1;
  9350. //
  9351. // static void ggml_vk_test_quantize(ggml_backend_vk_context * ctx, size_t ne, ggml_type quant) {
  9352. // VK_LOG_DEBUG("ggml_vk_test_quantize(" << ne << ")");
  9353. // GGML_ASSERT(quant == GGML_TYPE_Q8_1);
  9354. //
  9355. // const size_t x_sz = sizeof(float) * ne;
  9356. // const size_t qx_sz = ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9357. // float * x = (float *) malloc(x_sz);
  9358. // block_q8_1 * qx = (block_q8_1 *)malloc(qx_sz);
  9359. // block_q8_1 * qx_res = (block_q8_1 *)malloc(qx_sz);
  9360. // vk_buffer x_buf = ggml_vk_create_buffer_check(ctx->device, x_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9361. // vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9362. //
  9363. // for (size_t i = 0; i < ne; i++) {
  9364. // x[i] = rand() / (float)RAND_MAX;
  9365. // }
  9366. //
  9367. // vk_pipeline p = ggml_vk_get_quantize_pipeline(ctx, quant);
  9368. //
  9369. // ggml_pipeline_request_descriptor_sets(ctx, p, 1);
  9370. //
  9371. // ggml_pipeline_allocate_descriptor_sets(ctx);
  9372. //
  9373. // ggml_vk_buffer_write(x_buf, 0, x, x_sz);
  9374. //
  9375. // vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9376. // ggml_vk_ctx_begin(ctx->device, subctx);
  9377. // ggml_vk_quantize_q8_1(ctx, subctx, ggml_vk_subbuffer(ctx, x_buf), ggml_vk_subbuffer(ctx, qx_buf), ne);
  9378. // ggml_vk_ctx_end(subctx);
  9379. //
  9380. // auto begin = std::chrono::high_resolution_clock::now();
  9381. //
  9382. // ggml_vk_submit(subctx, ctx->fence);
  9383. // VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_quantize waitForFences");
  9384. // ctx->device->device.resetFences({ ctx->fence });
  9385. // ggml_vk_queue_command_pools_cleanup(ctx->device);
  9386. //
  9387. // auto end = std::chrono::high_resolution_clock::now();
  9388. //
  9389. // double ms_quant = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9390. // ggml_vk_buffer_read(qx_buf, 0, qx, qx_sz);
  9391. //
  9392. // ggml_vk_quantize_data(x, qx_res, ne, quant);
  9393. //
  9394. // int first_err = -1;
  9395. //
  9396. // for (size_t i = 0; i < ne / 32; i++) {
  9397. // 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));
  9398. //
  9399. // if (first_err < 0 && error > 0.1) {
  9400. // first_err = i;
  9401. // }
  9402. //
  9403. // 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));
  9404. //
  9405. // if (first_err < 0 && error > 0.1) {
  9406. // first_err = i;
  9407. // }
  9408. //
  9409. // for (size_t j = 0; j < 32; j++) {
  9410. // uint64_t error = std::abs(qx_res[i].qs[j] - qx[i].qs[j]);
  9411. //
  9412. // if (first_err < 0 && error > 1) {
  9413. // first_err = i;
  9414. // }
  9415. // }
  9416. // }
  9417. //
  9418. // std::cerr << "TEST QUANTIZE " << ggml_type_name(quant) << " time=" << ms_quant << "ms " << (first_err == -1 ? "CORRECT" : "INCORRECT") << std::endl;
  9419. //
  9420. // if (first_err != -1) {
  9421. // std::cerr << "first_error = " << first_err << std::endl;
  9422. // std::cerr << "Actual result: " << std::endl << std::endl;
  9423. // 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) << " ";
  9424. // for (size_t j = 0; j < 32; j++) {
  9425. // std::cout << " qs" << j << "=" << (uint32_t)qx[first_err].qs[j] << " ";
  9426. // }
  9427. // std::cerr << std::endl << std::endl << "Expected result: " << std::endl << std::endl;
  9428. // 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) << " ";
  9429. // for (size_t j = 0; j < 32; j++) {
  9430. // std::cout << " qs" << j << "=" << (uint32_t)qx_res[first_err].qs[j] << " ";
  9431. // }
  9432. // std::cerr << std::endl;
  9433. // }
  9434. //
  9435. // ggml_vk_destroy_buffer(x_buf);
  9436. // ggml_vk_destroy_buffer(qx_buf);
  9437. //
  9438. // free(x);
  9439. // free(qx);
  9440. // free(qx_res);
  9441. // }
  9442. 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) {
  9443. VK_LOG_DEBUG("ggml_vk_test_dequant_matmul(" << m << ", " << n << ", " << k << ", " << batch << ", " << num_it << ", " << split_k << ", " << ggml_type_name(quant) << ")");
  9444. const size_t x_ne = m * k * batch;
  9445. const size_t y_ne = k * n * batch;
  9446. const size_t d_ne = m * n * batch;
  9447. vk_matmul_pipeline2 * pipelines;
  9448. if (mmq) {
  9449. pipelines = ctx->device->pipeline_dequant_mul_mat_mat_q8_1;
  9450. } else {
  9451. pipelines = ctx->device->pipeline_dequant_mul_mat_mat;
  9452. }
  9453. const bool fp16acc = ctx->device->fp16;
  9454. vk_pipeline p;
  9455. std::string shname;
  9456. if (shader_size == 0) {
  9457. p = fp16acc ? pipelines[quant].f16acc->a_s : pipelines[quant].f32acc->a_s;
  9458. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_S";
  9459. } else if (shader_size == 1) {
  9460. p = fp16acc ? pipelines[quant].f16acc->a_m : pipelines[quant].f32acc->a_m;
  9461. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_M";
  9462. } else if (shader_size == 2) {
  9463. p = fp16acc ? pipelines[quant].f16acc->a_l : pipelines[quant].f32acc->a_l;
  9464. shname = std::string(ggml_type_name(quant)) + "_ALIGNED_L";
  9465. } else {
  9466. GGML_ASSERT(0);
  9467. }
  9468. const size_t kpad = mmq ? 0 : ggml_vk_align_size(k, p->align);
  9469. if (mmq || k != kpad) {
  9470. if (shader_size == 0) {
  9471. p = fp16acc ? pipelines[quant].f16acc->s : pipelines[quant].f32acc->s;
  9472. shname = std::string(ggml_type_name(quant)) + "_S";
  9473. } else if (shader_size == 1) {
  9474. p = fp16acc ? pipelines[quant].f16acc->m : pipelines[quant].f32acc->m;
  9475. shname = std::string(ggml_type_name(quant)) + "_M";
  9476. } else if (shader_size == 2) {
  9477. p = fp16acc ? pipelines[quant].f16acc->l : pipelines[quant].f32acc->l;
  9478. shname = std::string(ggml_type_name(quant)) + "_L";
  9479. } else {
  9480. GGML_ASSERT(0);
  9481. }
  9482. }
  9483. if (p == nullptr) {
  9484. std::cerr << "error: no pipeline for ggml_vk_test_dequant_matmul " << ggml_type_name(quant) << std::endl;
  9485. return;
  9486. }
  9487. const size_t x_sz = sizeof(float) * x_ne;
  9488. const size_t y_sz = sizeof(float) * y_ne;
  9489. const size_t qx_sz = x_ne * ggml_type_size(quant)/ggml_blck_size(quant);
  9490. const size_t qy_sz = mmq ? y_ne * ggml_type_size(GGML_TYPE_Q8_1)/ggml_blck_size(GGML_TYPE_Q8_1) : y_sz;
  9491. const size_t d_sz = sizeof(float) * d_ne;
  9492. float * x = (float *) malloc(x_sz);
  9493. float * y = (float *) malloc(y_sz);
  9494. void * qx = malloc(qx_sz);
  9495. vk_buffer qx_buf = ggml_vk_create_buffer_check(ctx->device, qx_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9496. vk_buffer y_buf = ggml_vk_create_buffer_check(ctx->device, y_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9497. vk_buffer qy_buf = ggml_vk_create_buffer_check(ctx->device, qy_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9498. vk_buffer d_buf = ggml_vk_create_buffer_check(ctx->device, d_sz, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9499. float * d = (float *) malloc(d_sz);
  9500. float * d_chk = (float *) malloc(d_sz);
  9501. for (size_t i = 0; i < x_ne; i++) {
  9502. x[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9503. // x[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9504. // x[i] = i % k;
  9505. }
  9506. ggml_vk_quantize_data(x, qx, x_ne, quant);
  9507. for (size_t i = 0; i < y_ne; i++) {
  9508. y[i] = (rand() / (float)RAND_MAX) * 2.0f - 1.0f;
  9509. // y[i] = (i % k == i / k) ? 1.0f : 0.0f;
  9510. // y[i] = i % k;
  9511. }
  9512. ggml_pipeline_request_descriptor_sets(ctx, p, num_it);
  9513. if (split_k > 1) {
  9514. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, num_it);
  9515. if (ctx->prealloc_split_k == nullptr || ctx->prealloc_split_k->size < sizeof(float) * d_ne * split_k) {
  9516. // Resize buffer
  9517. if (ctx->prealloc_split_k != nullptr) {
  9518. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9519. }
  9520. ctx->prealloc_split_k = ggml_vk_create_buffer_check(ctx->device, sizeof(float) * d_ne * split_k, {vk::MemoryPropertyFlagBits::eDeviceLocal});
  9521. }
  9522. }
  9523. if (mmq) {
  9524. ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_quantize_q8_1, num_it);
  9525. }
  9526. ggml_pipeline_allocate_descriptor_sets(ctx);
  9527. ggml_vk_buffer_write(qx_buf, 0, qx, qx_sz);
  9528. ggml_vk_buffer_write(y_buf, 0, y, y_sz);
  9529. vk_context subctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9530. ggml_vk_ctx_begin(ctx->device, subctx);
  9531. if (mmq) {
  9532. for (size_t i = 0; i < num_it; i++) {
  9533. ggml_vk_quantize_q8_1(ctx, subctx, { y_buf, 0, y_sz }, { qy_buf, 0, qy_sz }, y_ne);
  9534. ggml_vk_matmul(
  9535. 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 },
  9536. m, n, k,
  9537. k, k, m, k*m, k*n, m*n,
  9538. split_k, batch, batch, batch, 1, 1, n
  9539. );
  9540. }
  9541. } else {
  9542. for (size_t i = 0; i < num_it; i++) {
  9543. ggml_vk_matmul(
  9544. 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 },
  9545. m, n, k,
  9546. k, k, m, k*m, k*n, m*n,
  9547. split_k, batch, batch, batch, 1, 1, n
  9548. );
  9549. }
  9550. }
  9551. ggml_vk_ctx_end(subctx);
  9552. auto begin = std::chrono::high_resolution_clock::now();
  9553. ggml_vk_submit(subctx, ctx->fence);
  9554. VK_CHECK(ctx->device->device.waitForFences({ ctx->fence }, true, UINT64_MAX), "ggml_vk_test_dequant waitForFences");
  9555. ctx->device->device.resetFences({ ctx->fence });
  9556. ggml_vk_queue_command_pools_cleanup(ctx->device);
  9557. auto end = std::chrono::high_resolution_clock::now();
  9558. double time_ms = std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count() / 1000.0;
  9559. ggml_vk_buffer_read(d_buf, 0, d, d_sz);
  9560. ggml_init_params iparams = {
  9561. /*.mem_size =*/ 1024*1024*1024,
  9562. /*.mem_buffer =*/ NULL,
  9563. /*.no_alloc =*/ true,
  9564. };
  9565. ggml_context * ggml_ctx = ggml_init(iparams);
  9566. ggml_tensor * src0_ggml = ggml_new_tensor_3d(ggml_ctx, quant, k, m, batch);
  9567. ggml_tensor * src1_ggml = ggml_new_tensor_3d(ggml_ctx, GGML_TYPE_F32, k, n, batch);
  9568. ggml_tensor * tensor_ggml = ggml_mul_mat(ggml_ctx, src0_ggml, src1_ggml);
  9569. src0_ggml->data = qx;
  9570. src1_ggml->data = y;
  9571. tensor_ggml->data = d_chk;
  9572. ggml_cgraph * cgraph = ggml_new_graph(ggml_ctx);
  9573. ggml_build_forward_expand(cgraph, tensor_ggml);
  9574. ggml_graph_compute_with_ctx(ggml_ctx, cgraph, 1);
  9575. ggml_free(ggml_ctx);
  9576. double avg_err = 0.0;
  9577. int first_err_n = -1;
  9578. int first_err_m = -1;
  9579. int first_err_b = -1;
  9580. for (size_t i = 0; i < m*n*batch; i++) {
  9581. double err = std::fabs(d[i] - d_chk[i]);
  9582. avg_err += err;
  9583. if ((err > 0.05f || std::isnan(err)) && first_err_n == -1) {
  9584. first_err_b = i / (m * n);
  9585. first_err_n = (i % (m * n)) / m;
  9586. first_err_m = (i % (m * n)) % m;
  9587. }
  9588. }
  9589. avg_err /= m * n;
  9590. double tflops = 2.0*m*n*k*batch*num_it / (time_ms / 1000.0) / (1000.0*1000.0*1000.0*1000.0);
  9591. std::cerr << "TEST dequant matmul " << shname;
  9592. if (mmq) {
  9593. std::cerr << " mmq";
  9594. }
  9595. 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;
  9596. if (avg_err > 0.01 || std::isnan(avg_err)) {
  9597. std::cerr << "m = " << first_err_m << " n = " << first_err_n << " b = " << first_err_b << std::endl;
  9598. std::cerr << "Actual result: " << std::endl << std::endl;
  9599. ggml_vk_print_matrix_area(d, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9600. std::cerr << std::endl;
  9601. std::cerr << "Expected result: " << std::endl << std::endl;
  9602. ggml_vk_print_matrix_area(d_chk, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9603. std::cerr << "src0: " << std::endl << std::endl;
  9604. ggml_vk_print_matrix_area(x, GGML_TYPE_F32, k, m, first_err_m, first_err_n, first_err_b);
  9605. std::cerr << std::endl;
  9606. std::cerr << "src1: " << std::endl << std::endl;
  9607. ggml_vk_print_matrix_area(y, GGML_TYPE_F32, k, n, first_err_m, first_err_n, first_err_b);
  9608. if (split_k > 1) {
  9609. float * split_k_buf = (float *) malloc(sizeof(float) * d_ne * split_k);
  9610. ggml_vk_buffer_read(ctx->prealloc_split_k, 0, split_k_buf, sizeof(float) * d_ne * split_k);
  9611. std::cerr << "d_buf0: " << std::endl << std::endl;
  9612. ggml_vk_print_matrix_area(split_k_buf, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9613. std::cerr << "d_buf1: " << std::endl << std::endl;
  9614. ggml_vk_print_matrix_area(split_k_buf + d_ne, GGML_TYPE_F32, m, n, first_err_m, first_err_n, first_err_b);
  9615. std::cerr << "d_buf2: " << std::endl << std::endl;
  9616. 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);
  9617. std::cerr << "d_buf3: " << std::endl << std::endl;
  9618. 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);
  9619. free(split_k_buf);
  9620. }
  9621. }
  9622. ggml_vk_destroy_buffer(qx_buf);
  9623. ggml_vk_destroy_buffer(y_buf);
  9624. ggml_vk_destroy_buffer(qy_buf);
  9625. ggml_vk_destroy_buffer(d_buf);
  9626. free(x);
  9627. free(qx);
  9628. free(y);
  9629. free(d);
  9630. free(d_chk);
  9631. }
  9632. #endif
  9633. static void ggml_vk_preallocate_buffers(ggml_backend_vk_context * ctx, vk_context subctx) {
  9634. #if defined(GGML_VULKAN_RUN_TESTS)
  9635. const std::vector<size_t> vals {
  9636. 512, 512, 128,
  9637. 128, 512, 512,
  9638. 4096, 512, 4096,
  9639. 11008, 512, 4096,
  9640. 4096, 512, 11008,
  9641. 32000, 512, 4096,
  9642. 8, 8, 8,
  9643. 100, 46, 576,
  9644. 623, 111, 128,
  9645. 100, 46, 558,
  9646. 512, 1, 256,
  9647. 128, 110, 622,
  9648. 511, 511, 127,
  9649. 511, 511, 7,
  9650. 511, 511, 17,
  9651. 49, 49, 128,
  9652. 128, 49, 49,
  9653. 4096, 49, 4096,
  9654. };
  9655. const size_t num_it = 100;
  9656. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9657. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9658. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9659. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q4_0, true);
  9660. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q4_0, true);
  9661. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q4_0, true);
  9662. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0);
  9663. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0);
  9664. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0);
  9665. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 0, GGML_TYPE_Q8_0, true);
  9666. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 1, GGML_TYPE_Q8_0, true);
  9667. ggml_vk_test_dequant_matmul(ctx, 4096, 512, 4096, 2, num_it, 1, 2, GGML_TYPE_Q8_0, true);
  9668. abort();
  9669. for (size_t i = 0; i < vals.size(); i += 3) {
  9670. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0);
  9671. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1);
  9672. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2);
  9673. std::cerr << '\n';
  9674. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0);
  9675. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1);
  9676. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2);
  9677. std::cerr << '\n';
  9678. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0);
  9679. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1);
  9680. ggml_vk_test_matmul<ggml_fp16_t, float>(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2);
  9681. std::cerr << '\n' << std::endl;
  9682. if (vals[i + 2] % 32 == 0) {
  9683. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_0);
  9684. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_0);
  9685. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_0);
  9686. std::cerr << '\n';
  9687. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_0);
  9688. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_0);
  9689. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_0);
  9690. std::cerr << '\n';
  9691. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_0);
  9692. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_0);
  9693. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_0);
  9694. std::cerr << '\n' << std::endl;
  9695. }
  9696. if (vals[i + 2] % 256 == 0) {
  9697. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 0, GGML_TYPE_Q4_K);
  9698. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 1, GGML_TYPE_Q4_K);
  9699. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 1, 2, GGML_TYPE_Q4_K);
  9700. std::cerr << '\n';
  9701. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 0, GGML_TYPE_Q4_K);
  9702. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 1, GGML_TYPE_Q4_K);
  9703. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 2, 2, GGML_TYPE_Q4_K);
  9704. std::cerr << '\n';
  9705. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 0, GGML_TYPE_Q4_K);
  9706. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 1, GGML_TYPE_Q4_K);
  9707. ggml_vk_test_dequant_matmul(ctx, vals[i], vals[i + 1], vals[i + 2], 2, num_it, 4, 2, GGML_TYPE_Q4_K);
  9708. std::cerr << '\n' << std::endl;
  9709. }
  9710. }
  9711. GGML_ABORT("fatal error");
  9712. #endif
  9713. if (subctx) {
  9714. // Submit and wait for any pending work before reallocating the buffers
  9715. ggml_vk_ctx_end(subctx);
  9716. ggml_vk_submit(subctx, {});
  9717. ctx->submit_pending = true;
  9718. ggml_vk_synchronize(ctx);
  9719. ggml_vk_ctx_begin(ctx->device, subctx);
  9720. }
  9721. if (ctx->prealloc_x == nullptr || (ctx->prealloc_size_x > 0 && ctx->prealloc_x->size < ctx->prealloc_size_x)) {
  9722. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(x_size: " << ctx->prealloc_size_x << ")");
  9723. // Resize buffer
  9724. if (ctx->prealloc_x != nullptr) {
  9725. ggml_vk_destroy_buffer(ctx->prealloc_x);
  9726. }
  9727. ctx->prealloc_x = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_x);
  9728. }
  9729. if (ctx->prealloc_y == nullptr || (ctx->prealloc_size_y > 0 && ctx->prealloc_y->size < ctx->prealloc_size_y)) {
  9730. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(y_size: " << ctx->prealloc_size_y << ")");
  9731. // Resize buffer
  9732. if (ctx->prealloc_y != nullptr) {
  9733. ggml_vk_destroy_buffer(ctx->prealloc_y);
  9734. }
  9735. ctx->prealloc_y = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_y);
  9736. }
  9737. if (ctx->prealloc_split_k == nullptr || (ctx->prealloc_size_split_k > 0 && ctx->prealloc_split_k->size < ctx->prealloc_size_split_k)) {
  9738. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(split_k_size: " << ctx->prealloc_size_split_k << ")");
  9739. // Resize buffer
  9740. if (ctx->prealloc_split_k != nullptr) {
  9741. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  9742. }
  9743. ctx->prealloc_split_k = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_split_k);
  9744. }
  9745. if (ctx->prealloc_add_rms_partials == nullptr || (ctx->prealloc_size_add_rms_partials > 0 && ctx->prealloc_add_rms_partials->size < ctx->prealloc_size_add_rms_partials)) {
  9746. VK_LOG_MEMORY("ggml_vk_preallocate_buffers(add_partials_size: " << ctx->prealloc_add_rms_partials << ")");
  9747. // Resize buffer
  9748. if (ctx->prealloc_add_rms_partials != nullptr) {
  9749. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  9750. }
  9751. ctx->prealloc_add_rms_partials = ggml_vk_create_buffer_device(ctx->device, ctx->prealloc_size_add_rms_partials);
  9752. }
  9753. }
  9754. static bool ggml_vk_compute_forward(ggml_backend_vk_context* ctx, ggml_cgraph * cgraph, ggml_tensor* tensor, int tensor_idx, bool almost_ready);
  9755. // Returns true if node has enqueued work into the queue, false otherwise
  9756. // If submit is true the current all operations queued so far are being submitted to Vulkan to overlap cmdlist creation and GPU execution.
  9757. 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 last_node, bool almost_ready, bool submit){
  9758. ggml_tensor * node = cgraph->nodes[node_idx];
  9759. if (ggml_is_empty(node) || !node->buffer) {
  9760. return false;
  9761. }
  9762. VK_LOG_DEBUG("ggml_vk_build_graph(" << node << ", " << ggml_op_name(node->op) << ")");
  9763. ctx->semaphore_idx = 0;
  9764. ggml_tensor * src0 = node->src[0];
  9765. ggml_tensor * src1 = node->src[1];
  9766. ggml_tensor * src2 = node->src[2];
  9767. ggml_tensor * src3 = node->src[3];
  9768. switch (node->op) {
  9769. // Return on empty ops to avoid generating a compute_ctx and setting exit_tensor
  9770. case GGML_OP_RESHAPE:
  9771. case GGML_OP_VIEW:
  9772. case GGML_OP_PERMUTE:
  9773. case GGML_OP_TRANSPOSE:
  9774. case GGML_OP_NONE:
  9775. return false;
  9776. case GGML_OP_UNARY:
  9777. switch (ggml_get_unary_op(node)) {
  9778. case GGML_UNARY_OP_EXP:
  9779. case GGML_UNARY_OP_SILU:
  9780. case GGML_UNARY_OP_GELU:
  9781. case GGML_UNARY_OP_GELU_ERF:
  9782. case GGML_UNARY_OP_GELU_QUICK:
  9783. case GGML_UNARY_OP_RELU:
  9784. case GGML_UNARY_OP_NEG:
  9785. case GGML_UNARY_OP_TANH:
  9786. case GGML_UNARY_OP_SIGMOID:
  9787. case GGML_UNARY_OP_HARDSIGMOID:
  9788. case GGML_UNARY_OP_HARDSWISH:
  9789. case GGML_UNARY_OP_ABS:
  9790. case GGML_UNARY_OP_SOFTPLUS:
  9791. case GGML_UNARY_OP_STEP:
  9792. case GGML_UNARY_OP_ROUND:
  9793. case GGML_UNARY_OP_CEIL:
  9794. case GGML_UNARY_OP_FLOOR:
  9795. case GGML_UNARY_OP_TRUNC:
  9796. break;
  9797. default:
  9798. return false;
  9799. }
  9800. break;
  9801. case GGML_OP_GLU:
  9802. switch (ggml_get_glu_op(node)) {
  9803. case GGML_GLU_OP_GEGLU:
  9804. case GGML_GLU_OP_REGLU:
  9805. case GGML_GLU_OP_SWIGLU:
  9806. case GGML_GLU_OP_SWIGLU_OAI:
  9807. case GGML_GLU_OP_GEGLU_ERF:
  9808. case GGML_GLU_OP_GEGLU_QUICK:
  9809. break;
  9810. default:
  9811. return false;
  9812. }
  9813. break;
  9814. case GGML_OP_ADD:
  9815. {
  9816. int next_node_idx = node_idx + 1 + ctx->num_additional_fused_ops;
  9817. if (next_node_idx < cgraph->n_nodes &&
  9818. cgraph->nodes[next_node_idx]->op == GGML_OP_RMS_NORM &&
  9819. cgraph->nodes[next_node_idx]->src[0] == cgraph->nodes[next_node_idx - 1] &&
  9820. ggml_nrows(cgraph->nodes[next_node_idx]) == 1 &&
  9821. ctx->device->add_rms_fusion) {
  9822. uint32_t size = ggml_vk_rms_partials_size(ctx, cgraph->nodes[node_idx]);
  9823. ctx->do_add_rms_partials_offset_calculation = true;
  9824. if (ctx->prealloc_size_add_rms_partials_offset + size <= ctx->prealloc_size_add_rms_partials) {
  9825. ctx->do_add_rms_partials = true;
  9826. }
  9827. }
  9828. } break;
  9829. case GGML_OP_REPEAT:
  9830. case GGML_OP_REPEAT_BACK:
  9831. case GGML_OP_GET_ROWS:
  9832. case GGML_OP_ADD_ID:
  9833. case GGML_OP_ACC:
  9834. case GGML_OP_SUB:
  9835. case GGML_OP_MUL:
  9836. case GGML_OP_DIV:
  9837. case GGML_OP_ADD1:
  9838. case GGML_OP_ARANGE:
  9839. case GGML_OP_FILL:
  9840. case GGML_OP_CONCAT:
  9841. case GGML_OP_UPSCALE:
  9842. case GGML_OP_SCALE:
  9843. case GGML_OP_SQR:
  9844. case GGML_OP_SQRT:
  9845. case GGML_OP_SIN:
  9846. case GGML_OP_COS:
  9847. case GGML_OP_LOG:
  9848. case GGML_OP_CLAMP:
  9849. case GGML_OP_PAD:
  9850. case GGML_OP_ROLL:
  9851. case GGML_OP_CPY:
  9852. case GGML_OP_SET_ROWS:
  9853. case GGML_OP_CONT:
  9854. case GGML_OP_DUP:
  9855. case GGML_OP_SILU_BACK:
  9856. case GGML_OP_NORM:
  9857. case GGML_OP_GROUP_NORM:
  9858. case GGML_OP_RMS_NORM:
  9859. case GGML_OP_RMS_NORM_BACK:
  9860. case GGML_OP_L2_NORM:
  9861. case GGML_OP_DIAG_MASK_INF:
  9862. case GGML_OP_SOFT_MAX:
  9863. case GGML_OP_SOFT_MAX_BACK:
  9864. case GGML_OP_ROPE:
  9865. case GGML_OP_ROPE_BACK:
  9866. case GGML_OP_MUL_MAT:
  9867. case GGML_OP_MUL_MAT_ID:
  9868. case GGML_OP_ARGSORT:
  9869. case GGML_OP_SUM:
  9870. case GGML_OP_SUM_ROWS:
  9871. case GGML_OP_MEAN:
  9872. case GGML_OP_ARGMAX:
  9873. case GGML_OP_COUNT_EQUAL:
  9874. case GGML_OP_IM2COL:
  9875. case GGML_OP_IM2COL_3D:
  9876. case GGML_OP_TIMESTEP_EMBEDDING:
  9877. case GGML_OP_CONV_TRANSPOSE_1D:
  9878. case GGML_OP_POOL_2D:
  9879. case GGML_OP_CONV_2D:
  9880. case GGML_OP_CONV_TRANSPOSE_2D:
  9881. case GGML_OP_CONV_2D_DW:
  9882. case GGML_OP_RWKV_WKV6:
  9883. case GGML_OP_RWKV_WKV7:
  9884. case GGML_OP_SSM_SCAN:
  9885. case GGML_OP_SSM_CONV:
  9886. case GGML_OP_LEAKY_RELU:
  9887. case GGML_OP_FLASH_ATTN_EXT:
  9888. case GGML_OP_OPT_STEP_ADAMW:
  9889. case GGML_OP_OPT_STEP_SGD:
  9890. break;
  9891. default:
  9892. std::cerr << "ggml_vulkan: Error: Missing op: " << ggml_op_name(node->op) << std::endl;
  9893. GGML_ABORT("fatal error");
  9894. }
  9895. vk_context compute_ctx;
  9896. if (ctx->compute_ctx.expired()) {
  9897. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  9898. ctx->compute_ctx = compute_ctx;
  9899. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  9900. } else {
  9901. compute_ctx = ctx->compute_ctx.lock();
  9902. }
  9903. {
  9904. // This logic detects dependencies between modes in the graph and calls ggml_vk_sync_buffers
  9905. // to synchronize them. This handles most "normal" synchronization when computing the graph, and when
  9906. // there is no auxiliary memory use, it shouldn't be necessary to call ggml_vk_sync_buffers
  9907. // outside of this logic. When a node uses one of the prealloc buffers for something like
  9908. // dequantization or split_k, additional synchronization is needed between those passes.
  9909. bool need_sync = false;
  9910. // Check whether "node" requires synchronization. The node requires synchronization if it
  9911. // overlaps in memory with another unsynchronized node and at least one of them is a write.
  9912. // Destination nodes are checked against both the written/read lists. Source nodes are only
  9913. // checked against the written list. Two nodes overlap in memory if they come from the same
  9914. // buffer and the tensor or view ranges overlap.
  9915. auto const &overlaps_unsynced = [&](const ggml_tensor *node, const std::vector<const ggml_tensor *> &unsynced_nodes) -> bool {
  9916. if (unsynced_nodes.size() == 0) {
  9917. return false;
  9918. }
  9919. auto n_base = vk_tensor_offset(node) + node->view_offs;
  9920. auto n_size = ggml_nbytes(node);
  9921. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)node->buffer->context;
  9922. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  9923. for (auto &other : unsynced_nodes) {
  9924. ggml_backend_vk_buffer_context * o_buf_ctx = (ggml_backend_vk_buffer_context *)other->buffer->context;
  9925. vk_buffer o_buf = o_buf_ctx->dev_buffer;
  9926. if (a_buf == o_buf) {
  9927. auto o_base = vk_tensor_offset(other) + other->view_offs;
  9928. auto o_size = ggml_nbytes(other);
  9929. if ((o_base <= n_base && n_base < o_base + o_size) ||
  9930. (n_base <= o_base && o_base < n_base + n_size)) {
  9931. return true;
  9932. }
  9933. }
  9934. }
  9935. return false;
  9936. };
  9937. // For all fused ops, check if the destination node or any of the source
  9938. // nodes require synchronization.
  9939. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1 && !need_sync; ++i) {
  9940. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  9941. // If the node actually writes to memory, then check if it needs to sync
  9942. if (ctx->fused_ops_write_mask & (1 << i)) {
  9943. if (overlaps_unsynced(cur_node, ctx->unsynced_nodes_read) || overlaps_unsynced(cur_node, ctx->unsynced_nodes_written)) {
  9944. need_sync = true;
  9945. break;
  9946. }
  9947. }
  9948. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  9949. if (!cur_node->src[j]) {
  9950. continue;
  9951. }
  9952. if (overlaps_unsynced(cur_node->src[j], ctx->unsynced_nodes_written)) {
  9953. need_sync = true;
  9954. break;
  9955. }
  9956. }
  9957. }
  9958. #define ENABLE_SYNC_LOGGING 0
  9959. if (need_sync) {
  9960. #if ENABLE_SYNC_LOGGING
  9961. std::cerr << "sync" << std::endl;
  9962. #endif
  9963. ctx->unsynced_nodes_written.clear();
  9964. ctx->unsynced_nodes_read.clear();
  9965. ggml_vk_sync_buffers(ctx, compute_ctx);
  9966. }
  9967. // Add all fused nodes to the unsynchronized lists.
  9968. for (int32_t i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  9969. const ggml_tensor *cur_node = cgraph->nodes[node_idx + i];
  9970. // Multiple outputs could be written, e.g. in topk_moe. Add them all to the list.
  9971. if (ctx->fused_ops_write_mask & (1 << i)) {
  9972. ctx->unsynced_nodes_written.push_back(cur_node);
  9973. }
  9974. for (uint32_t j = 0; j < GGML_MAX_SRC; ++j) {
  9975. if (!cur_node->src[j]) {
  9976. continue;
  9977. }
  9978. ctx->unsynced_nodes_read.push_back(cur_node->src[j]);
  9979. }
  9980. }
  9981. }
  9982. #if ENABLE_SYNC_LOGGING
  9983. for (int i = 0; i < ctx->num_additional_fused_ops + 1; ++i) {
  9984. auto *n = cgraph->nodes[node_idx + i];
  9985. std::cerr << node_idx + i << " " << ggml_op_name(n->op) << " " << n->name;
  9986. if (n->op == GGML_OP_GLU) {
  9987. std::cerr << " " << ggml_glu_op_name(ggml_get_glu_op(n)) << " " << (n->src[1] ? "split" : "single") << " ";
  9988. }
  9989. if (n->op == GGML_OP_ROPE) {
  9990. const int mode = ((const int32_t *) n->op_params)[2];
  9991. std::cerr << " rope mode: " << mode;
  9992. }
  9993. std::cerr << std::endl;
  9994. }
  9995. #endif
  9996. switch (node->op) {
  9997. case GGML_OP_REPEAT:
  9998. ggml_vk_repeat(ctx, compute_ctx, src0, node);
  9999. break;
  10000. case GGML_OP_REPEAT_BACK:
  10001. ggml_vk_repeat_back(ctx, compute_ctx, src0, node);
  10002. break;
  10003. case GGML_OP_ACC:
  10004. ggml_vk_acc(ctx, compute_ctx, src0, src1, node);
  10005. break;
  10006. case GGML_OP_GET_ROWS:
  10007. ggml_vk_get_rows(ctx, compute_ctx, src0, src1, node);
  10008. break;
  10009. case GGML_OP_ADD:
  10010. if (ctx->num_additional_fused_ops) {
  10011. ggml_vk_multi_add(ctx, compute_ctx, cgraph, node_idx);
  10012. } else {
  10013. ggml_vk_add(ctx, compute_ctx, src0, src1, node);
  10014. }
  10015. break;
  10016. case GGML_OP_SUB:
  10017. ggml_vk_sub(ctx, compute_ctx, src0, src1, node);
  10018. break;
  10019. case GGML_OP_MUL:
  10020. ggml_vk_mul(ctx, compute_ctx, src0, src1, node);
  10021. break;
  10022. case GGML_OP_DIV:
  10023. ggml_vk_div(ctx, compute_ctx, src0, src1, node);
  10024. break;
  10025. case GGML_OP_ADD_ID:
  10026. ggml_vk_add_id(ctx, compute_ctx, src0, src1, src2, node);
  10027. break;
  10028. case GGML_OP_CONCAT:
  10029. ggml_vk_concat(ctx, compute_ctx, src0, src1, node);
  10030. break;
  10031. case GGML_OP_UPSCALE:
  10032. ggml_vk_upscale(ctx, compute_ctx, src0, node);
  10033. break;
  10034. case GGML_OP_ADD1:
  10035. ggml_vk_add1(ctx, compute_ctx, src0, src1, node);
  10036. break;
  10037. case GGML_OP_ARANGE:
  10038. ggml_vk_arange(ctx, compute_ctx, node);
  10039. break;
  10040. case GGML_OP_FILL:
  10041. ggml_vk_fill(ctx, compute_ctx, node);
  10042. break;
  10043. case GGML_OP_SCALE:
  10044. ggml_vk_scale(ctx, compute_ctx, src0, node);
  10045. break;
  10046. case GGML_OP_SQR:
  10047. ggml_vk_sqr(ctx, compute_ctx, src0, node);
  10048. break;
  10049. case GGML_OP_SQRT:
  10050. ggml_vk_sqrt(ctx, compute_ctx, src0, node);
  10051. break;
  10052. case GGML_OP_SIN:
  10053. ggml_vk_sin(ctx, compute_ctx, src0, node);
  10054. break;
  10055. case GGML_OP_COS:
  10056. ggml_vk_cos(ctx, compute_ctx, src0, node);
  10057. break;
  10058. case GGML_OP_LOG:
  10059. ggml_vk_log(ctx, compute_ctx, src0, node);
  10060. break;
  10061. case GGML_OP_CLAMP:
  10062. ggml_vk_clamp(ctx, compute_ctx, src0, node);
  10063. break;
  10064. case GGML_OP_PAD:
  10065. ggml_vk_pad(ctx, compute_ctx, src0, node);
  10066. break;
  10067. case GGML_OP_ROLL:
  10068. ggml_vk_roll(ctx, compute_ctx, src0, node);
  10069. break;
  10070. case GGML_OP_CPY:
  10071. case GGML_OP_CONT:
  10072. case GGML_OP_DUP:
  10073. ggml_vk_cpy(ctx, compute_ctx, src0, node);
  10074. break;
  10075. case GGML_OP_SET_ROWS:
  10076. ggml_vk_set_rows(ctx, compute_ctx, src0, src1, node);
  10077. break;
  10078. case GGML_OP_SILU_BACK:
  10079. ggml_vk_silu_back(ctx, compute_ctx, src0, src1, node);
  10080. break;
  10081. case GGML_OP_NORM:
  10082. ggml_vk_norm(ctx, compute_ctx, src0, node);
  10083. break;
  10084. case GGML_OP_GROUP_NORM:
  10085. ggml_vk_group_norm(ctx, compute_ctx, src0, node);
  10086. break;
  10087. case GGML_OP_RMS_NORM:
  10088. ggml_vk_rms_norm(ctx, compute_ctx, cgraph, node_idx, (float *)node->op_params);
  10089. break;
  10090. case GGML_OP_RMS_NORM_BACK:
  10091. ggml_vk_rms_norm_back(ctx, compute_ctx, src0, src1, node);
  10092. break;
  10093. case GGML_OP_L2_NORM:
  10094. ggml_vk_l2_norm(ctx, compute_ctx, src0, node);
  10095. break;
  10096. case GGML_OP_UNARY:
  10097. switch (ggml_get_unary_op(node)) {
  10098. case GGML_UNARY_OP_EXP:
  10099. case GGML_UNARY_OP_SILU:
  10100. case GGML_UNARY_OP_GELU:
  10101. case GGML_UNARY_OP_GELU_ERF:
  10102. case GGML_UNARY_OP_GELU_QUICK:
  10103. case GGML_UNARY_OP_RELU:
  10104. case GGML_UNARY_OP_NEG:
  10105. case GGML_UNARY_OP_TANH:
  10106. case GGML_UNARY_OP_SIGMOID:
  10107. case GGML_UNARY_OP_HARDSIGMOID:
  10108. case GGML_UNARY_OP_HARDSWISH:
  10109. case GGML_UNARY_OP_ABS:
  10110. case GGML_UNARY_OP_SOFTPLUS:
  10111. case GGML_UNARY_OP_STEP:
  10112. case GGML_UNARY_OP_ROUND:
  10113. case GGML_UNARY_OP_CEIL:
  10114. case GGML_UNARY_OP_FLOOR:
  10115. case GGML_UNARY_OP_TRUNC:
  10116. ggml_vk_unary(ctx, compute_ctx, src0, node);
  10117. break;
  10118. default:
  10119. return false;
  10120. }
  10121. break;
  10122. case GGML_OP_GLU:
  10123. switch (ggml_get_glu_op(node)) {
  10124. case GGML_GLU_OP_GEGLU:
  10125. case GGML_GLU_OP_REGLU:
  10126. case GGML_GLU_OP_SWIGLU:
  10127. case GGML_GLU_OP_SWIGLU_OAI:
  10128. case GGML_GLU_OP_GEGLU_ERF:
  10129. case GGML_GLU_OP_GEGLU_QUICK:
  10130. ggml_vk_glu(ctx, compute_ctx, src0, src1, node);
  10131. break;
  10132. default:
  10133. return false;
  10134. }
  10135. break;
  10136. case GGML_OP_DIAG_MASK_INF:
  10137. ggml_vk_diag_mask_inf(ctx, compute_ctx, src0, node);
  10138. break;
  10139. case GGML_OP_SOFT_MAX:
  10140. if (ctx->num_additional_fused_ops) {
  10141. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10142. } else {
  10143. ggml_vk_soft_max(ctx, compute_ctx, src0, src1, src2, node);
  10144. }
  10145. break;
  10146. case GGML_OP_SOFT_MAX_BACK:
  10147. ggml_vk_soft_max_back(ctx, compute_ctx, src0, src1, node);
  10148. break;
  10149. case GGML_OP_ROPE:
  10150. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, false);
  10151. break;
  10152. case GGML_OP_ROPE_BACK:
  10153. ggml_vk_rope(ctx, compute_ctx, cgraph, node_idx, true);
  10154. break;
  10155. case GGML_OP_ARGSORT:
  10156. if (ctx->num_additional_fused_ops) {
  10157. ggml_vk_topk_moe(ctx, compute_ctx, cgraph, node_idx);
  10158. } else {
  10159. ggml_vk_argsort(ctx, compute_ctx, src0, node);
  10160. }
  10161. break;
  10162. case GGML_OP_SUM:
  10163. ggml_vk_sum(ctx, compute_ctx, src0, node);
  10164. break;
  10165. case GGML_OP_SUM_ROWS:
  10166. ggml_vk_sum_rows(ctx, compute_ctx, src0, node);
  10167. break;
  10168. case GGML_OP_MEAN:
  10169. ggml_vk_mean(ctx, compute_ctx, src0, node);
  10170. break;
  10171. case GGML_OP_ARGMAX:
  10172. ggml_vk_argmax(ctx, compute_ctx, src0, node);
  10173. break;
  10174. case GGML_OP_COUNT_EQUAL:
  10175. ggml_vk_count_equal(ctx, compute_ctx, src0, src1, node);
  10176. break;
  10177. case GGML_OP_IM2COL:
  10178. ggml_vk_im2col(ctx, compute_ctx, src0, src1, node);
  10179. break;
  10180. case GGML_OP_IM2COL_3D:
  10181. ggml_vk_im2col_3d(ctx, compute_ctx, src0, src1, node);
  10182. break;
  10183. case GGML_OP_TIMESTEP_EMBEDDING:
  10184. ggml_vk_timestep_embedding(ctx, compute_ctx, src0, node);
  10185. break;
  10186. case GGML_OP_CONV_TRANSPOSE_1D:
  10187. ggml_vk_conv_transpose_1d(ctx, compute_ctx, src0, src1, node);
  10188. break;
  10189. case GGML_OP_POOL_2D:
  10190. ggml_vk_pool_2d(ctx, compute_ctx, src0, node);
  10191. break;
  10192. case GGML_OP_CONV_2D:
  10193. ggml_vk_conv_2d(ctx, compute_ctx, src0, src1, node);
  10194. break;
  10195. case GGML_OP_CONV_TRANSPOSE_2D:
  10196. ggml_vk_conv_transpose_2d(ctx, compute_ctx, src0, src1, node);
  10197. break;
  10198. case GGML_OP_CONV_2D_DW:
  10199. ggml_vk_conv_2d_dw(ctx, compute_ctx, src0, src1, node);
  10200. break;
  10201. case GGML_OP_LEAKY_RELU:
  10202. ggml_vk_leaky_relu(ctx, compute_ctx, src0, node);
  10203. break;
  10204. case GGML_OP_MUL_MAT:
  10205. ggml_vk_mul_mat(ctx, compute_ctx, cgraph, node_idx);
  10206. break;
  10207. case GGML_OP_MUL_MAT_ID:
  10208. ggml_vk_mul_mat_id(ctx, compute_ctx, cgraph, node_idx);
  10209. break;
  10210. case GGML_OP_FLASH_ATTN_EXT:
  10211. ggml_vk_flash_attn(ctx, compute_ctx, src0, src1, src2, src3, node->src[4], node);
  10212. break;
  10213. case GGML_OP_RWKV_WKV6:
  10214. ggml_vk_rwkv_wkv6(ctx, compute_ctx, node);
  10215. break;
  10216. case GGML_OP_RWKV_WKV7:
  10217. ggml_vk_rwkv_wkv7(ctx, compute_ctx, node);
  10218. break;
  10219. case GGML_OP_SSM_SCAN:
  10220. ggml_vk_ssm_scan(ctx, compute_ctx, node);
  10221. break;
  10222. case GGML_OP_SSM_CONV:
  10223. ggml_vk_ssm_conv(ctx, compute_ctx, node);
  10224. break;
  10225. case GGML_OP_OPT_STEP_ADAMW:
  10226. ggml_vk_opt_step_adamw(ctx, compute_ctx, node);
  10227. break;
  10228. case GGML_OP_OPT_STEP_SGD:
  10229. ggml_vk_opt_step_sgd(ctx, compute_ctx, src0, src1, src2, node);
  10230. break;
  10231. default:
  10232. return false;
  10233. }
  10234. ctx->tensor_ctxs[node_idx] = compute_ctx;
  10235. #if defined(GGML_VULKAN_CHECK_RESULTS)
  10236. // Force context reset on each node so that each tensor ends up in its own context
  10237. // and can be run and compared to its CPU equivalent separately
  10238. last_node = true;
  10239. #endif
  10240. if (submit || last_node) {
  10241. ggml_vk_ctx_end(compute_ctx);
  10242. // TODO probably it'd be better to pass a exit_node flag to ggml_vk_compute_forward
  10243. if (last_node) {
  10244. compute_ctx->exit_tensor_idx = node_idx_begin;
  10245. }
  10246. else {
  10247. compute_ctx->exit_tensor_idx = -1;
  10248. }
  10249. ctx->compute_ctx.reset();
  10250. bool ok = ggml_vk_compute_forward(ctx, cgraph, node_begin, node_idx_begin, almost_ready);
  10251. if (!ok) {
  10252. if (node->op == GGML_OP_UNARY) {
  10253. 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;
  10254. } else if (node->op == GGML_OP_GLU) {
  10255. 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;
  10256. } else {
  10257. std::cerr << __func__ << ": error: op not supported " << node->name << " (" << ggml_op_name(node->op) << ")" << std::endl;
  10258. }
  10259. }
  10260. }
  10261. return true;
  10262. }
  10263. static bool ggml_vk_compute_forward(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, ggml_tensor * tensor, int tensor_idx, bool almost_ready = false) {
  10264. GGML_UNUSED(cgraph);
  10265. ggml_backend_buffer * buf = nullptr;
  10266. switch (tensor->op) {
  10267. case GGML_OP_ADD:
  10268. case GGML_OP_ACC:
  10269. case GGML_OP_GET_ROWS:
  10270. case GGML_OP_SUB:
  10271. case GGML_OP_MUL:
  10272. case GGML_OP_DIV:
  10273. case GGML_OP_ADD1:
  10274. case GGML_OP_ARANGE:
  10275. case GGML_OP_FILL:
  10276. case GGML_OP_ADD_ID:
  10277. case GGML_OP_CONCAT:
  10278. case GGML_OP_UPSCALE:
  10279. case GGML_OP_SCALE:
  10280. case GGML_OP_SQR:
  10281. case GGML_OP_SQRT:
  10282. case GGML_OP_SIN:
  10283. case GGML_OP_COS:
  10284. case GGML_OP_LOG:
  10285. case GGML_OP_CLAMP:
  10286. case GGML_OP_PAD:
  10287. case GGML_OP_ROLL:
  10288. case GGML_OP_CPY:
  10289. case GGML_OP_SET_ROWS:
  10290. case GGML_OP_CONT:
  10291. case GGML_OP_DUP:
  10292. case GGML_OP_SILU_BACK:
  10293. case GGML_OP_NORM:
  10294. case GGML_OP_GROUP_NORM:
  10295. case GGML_OP_RMS_NORM:
  10296. case GGML_OP_RMS_NORM_BACK:
  10297. case GGML_OP_L2_NORM:
  10298. case GGML_OP_DIAG_MASK_INF:
  10299. case GGML_OP_SOFT_MAX:
  10300. case GGML_OP_SOFT_MAX_BACK:
  10301. case GGML_OP_ROPE:
  10302. case GGML_OP_ROPE_BACK:
  10303. case GGML_OP_RESHAPE:
  10304. case GGML_OP_VIEW:
  10305. case GGML_OP_PERMUTE:
  10306. case GGML_OP_TRANSPOSE:
  10307. case GGML_OP_NONE:
  10308. case GGML_OP_ARGSORT:
  10309. case GGML_OP_SUM:
  10310. case GGML_OP_SUM_ROWS:
  10311. case GGML_OP_MEAN:
  10312. case GGML_OP_ARGMAX:
  10313. case GGML_OP_COUNT_EQUAL:
  10314. case GGML_OP_IM2COL:
  10315. case GGML_OP_IM2COL_3D:
  10316. case GGML_OP_TIMESTEP_EMBEDDING:
  10317. case GGML_OP_CONV_TRANSPOSE_1D:
  10318. case GGML_OP_POOL_2D:
  10319. case GGML_OP_CONV_2D:
  10320. case GGML_OP_CONV_TRANSPOSE_2D:
  10321. case GGML_OP_CONV_2D_DW:
  10322. case GGML_OP_RWKV_WKV6:
  10323. case GGML_OP_RWKV_WKV7:
  10324. case GGML_OP_SSM_SCAN:
  10325. case GGML_OP_SSM_CONV:
  10326. case GGML_OP_LEAKY_RELU:
  10327. case GGML_OP_REPEAT:
  10328. case GGML_OP_REPEAT_BACK:
  10329. case GGML_OP_OPT_STEP_ADAMW:
  10330. case GGML_OP_OPT_STEP_SGD:
  10331. buf = tensor->buffer;
  10332. break;
  10333. case GGML_OP_UNARY:
  10334. switch (ggml_get_unary_op(tensor)) {
  10335. case GGML_UNARY_OP_EXP:
  10336. case GGML_UNARY_OP_SILU:
  10337. case GGML_UNARY_OP_GELU:
  10338. case GGML_UNARY_OP_GELU_ERF:
  10339. case GGML_UNARY_OP_GELU_QUICK:
  10340. case GGML_UNARY_OP_RELU:
  10341. case GGML_UNARY_OP_NEG:
  10342. case GGML_UNARY_OP_TANH:
  10343. case GGML_UNARY_OP_SIGMOID:
  10344. case GGML_UNARY_OP_HARDSIGMOID:
  10345. case GGML_UNARY_OP_HARDSWISH:
  10346. case GGML_UNARY_OP_ABS:
  10347. case GGML_UNARY_OP_SOFTPLUS:
  10348. case GGML_UNARY_OP_STEP:
  10349. case GGML_UNARY_OP_ROUND:
  10350. case GGML_UNARY_OP_CEIL:
  10351. case GGML_UNARY_OP_FLOOR:
  10352. case GGML_UNARY_OP_TRUNC:
  10353. buf = tensor->buffer;
  10354. break;
  10355. default:
  10356. return false;
  10357. }
  10358. break;
  10359. case GGML_OP_GLU:
  10360. switch (ggml_get_glu_op(tensor)) {
  10361. case GGML_GLU_OP_GEGLU:
  10362. case GGML_GLU_OP_REGLU:
  10363. case GGML_GLU_OP_SWIGLU:
  10364. case GGML_GLU_OP_SWIGLU_OAI:
  10365. case GGML_GLU_OP_GEGLU_ERF:
  10366. case GGML_GLU_OP_GEGLU_QUICK:
  10367. buf = tensor->buffer;
  10368. break;
  10369. default:
  10370. return false;
  10371. }
  10372. break;
  10373. case GGML_OP_MUL_MAT:
  10374. case GGML_OP_MUL_MAT_ID:
  10375. case GGML_OP_FLASH_ATTN_EXT:
  10376. buf = tensor->buffer;
  10377. break;
  10378. default:
  10379. return false;
  10380. }
  10381. if (buf == nullptr) {
  10382. return false;
  10383. }
  10384. 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 << ")");
  10385. vk_context subctx = ctx->tensor_ctxs[tensor_idx].lock();
  10386. // Only run if ctx hasn't been submitted yet
  10387. if (!subctx->seqs.empty()) {
  10388. #ifdef GGML_VULKAN_CHECK_RESULTS
  10389. ggml_vk_check_results_0(ctx, cgraph, tensor_idx);
  10390. #endif
  10391. // Do staging buffer copies
  10392. for (auto& cpy : subctx->in_memcpys) {
  10393. memcpy(cpy.dst, cpy.src, cpy.n);
  10394. }
  10395. for (auto& mset : subctx->memsets) {
  10396. memset(mset.dst, mset.val, mset.n);
  10397. }
  10398. if (almost_ready && !ctx->almost_ready_fence_pending) {
  10399. ggml_vk_submit(subctx, ctx->almost_ready_fence);
  10400. ctx->almost_ready_fence_pending = true;
  10401. } else {
  10402. ggml_vk_submit(subctx, {});
  10403. }
  10404. ctx->submit_pending = true;
  10405. #ifdef GGML_VULKAN_CHECK_RESULTS
  10406. ggml_vk_synchronize(ctx);
  10407. ggml_vk_check_results_1(ctx, cgraph, tensor_idx);
  10408. #endif
  10409. }
  10410. if (tensor_idx == subctx->exit_tensor_idx) {
  10411. // Do staging buffer copies
  10412. for (auto& cpy : subctx->out_memcpys) {
  10413. memcpy(cpy.dst, cpy.src, cpy.n);
  10414. }
  10415. subctx->in_memcpys.clear();
  10416. subctx->out_memcpys.clear();
  10417. subctx->memsets.clear();
  10418. }
  10419. return true;
  10420. }
  10421. // Clean up after graph processing is done
  10422. static void ggml_vk_graph_cleanup(ggml_backend_vk_context * ctx) {
  10423. VK_LOG_DEBUG("ggml_vk_graph_cleanup()");
  10424. ctx->prealloc_y_last_pipeline_used = {};
  10425. ctx->unsynced_nodes_written.clear();
  10426. ctx->unsynced_nodes_read.clear();
  10427. ctx->prealloc_x_need_sync = ctx->prealloc_y_need_sync = ctx->prealloc_split_k_need_sync = false;
  10428. ggml_vk_command_pool_cleanup(ctx->device, ctx->compute_cmd_pool);
  10429. ggml_vk_command_pool_cleanup(ctx->device, ctx->transfer_cmd_pool);
  10430. for (size_t i = 0; i < ctx->gc.semaphores.size(); i++) {
  10431. ctx->device->device.destroySemaphore({ ctx->gc.semaphores[i].s });
  10432. }
  10433. ctx->gc.semaphores.clear();
  10434. for (size_t i = 0; i < ctx->gc.tl_semaphores.size(); i++) {
  10435. ctx->device->device.destroySemaphore({ ctx->gc.tl_semaphores[i].s });
  10436. }
  10437. ctx->gc.tl_semaphores.clear();
  10438. ctx->semaphore_idx = 0;
  10439. ctx->event_idx = 0;
  10440. for (auto& event : ctx->gc.events) {
  10441. ctx->device->device.resetEvent(event);
  10442. }
  10443. ctx->tensor_ctxs.clear();
  10444. ctx->gc.contexts.clear();
  10445. ctx->pipeline_descriptor_set_requirements = 0;
  10446. ctx->descriptor_set_idx = 0;
  10447. }
  10448. // Clean up on backend free
  10449. static void ggml_vk_cleanup(ggml_backend_vk_context * ctx) {
  10450. VK_LOG_DEBUG("ggml_vk_cleanup(" << ctx->name << ")");
  10451. // discard any unsubmitted command buffers
  10452. ctx->transfer_ctx.reset();
  10453. // wait for any pending command buffers to finish
  10454. ggml_vk_synchronize(ctx);
  10455. ggml_vk_graph_cleanup(ctx);
  10456. ggml_vk_destroy_buffer(ctx->prealloc_x);
  10457. ggml_vk_destroy_buffer(ctx->prealloc_y);
  10458. ggml_vk_destroy_buffer(ctx->prealloc_split_k);
  10459. ggml_vk_destroy_buffer(ctx->prealloc_add_rms_partials);
  10460. ggml_vk_destroy_buffer(ctx->sync_staging);
  10461. ctx->prealloc_y_last_pipeline_used = nullptr;
  10462. ctx->prealloc_size_x = 0;
  10463. ctx->prealloc_size_y = 0;
  10464. ctx->prealloc_size_split_k = 0;
  10465. for (auto& event : ctx->gc.events) {
  10466. ctx->device->device.destroyEvent(event);
  10467. }
  10468. ctx->gc.events.clear();
  10469. ctx->device->device.destroyFence(ctx->fence);
  10470. ctx->device->device.destroyFence(ctx->almost_ready_fence);
  10471. for (auto& pool : ctx->descriptor_pools) {
  10472. ctx->device->device.destroyDescriptorPool(pool);
  10473. }
  10474. ctx->descriptor_pools.clear();
  10475. ctx->descriptor_sets.clear();
  10476. ctx->compute_cmd_pool.destroy(ctx->device->device);
  10477. ctx->transfer_cmd_pool.destroy(ctx->device->device);
  10478. }
  10479. static int ggml_vk_get_device_count() {
  10480. ggml_vk_instance_init();
  10481. return vk_instance.device_indices.size();
  10482. }
  10483. static void ggml_vk_get_device_description(int device, char * description, size_t description_size) {
  10484. ggml_vk_instance_init();
  10485. std::vector<vk::PhysicalDevice> devices = vk_instance.instance.enumeratePhysicalDevices();
  10486. vk::PhysicalDeviceProperties props;
  10487. devices[device].getProperties(&props);
  10488. snprintf(description, description_size, "%s", props.deviceName.data());
  10489. }
  10490. // backend interface
  10491. #define UNUSED GGML_UNUSED
  10492. // device backend
  10493. static bool ggml_backend_buffer_is_vk(ggml_backend_buffer_t buffer) {
  10494. return buffer->buft->iface.get_name == ggml_backend_vk_buffer_type_name;
  10495. }
  10496. static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10497. VK_LOG_MEMORY("ggml_backend_vk_buffer_free_buffer()");
  10498. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10499. ggml_vk_destroy_buffer(ctx->dev_buffer);
  10500. delete ctx;
  10501. }
  10502. static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
  10503. return vk_ptr_base;
  10504. UNUSED(buffer);
  10505. }
  10506. static enum ggml_status ggml_backend_vk_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
  10507. VK_LOG_DEBUG("ggml_backend_vk_buffer_init_tensor(" << buffer << " (" << buffer->context << "), " << tensor << ")");
  10508. if (tensor->view_src != nullptr) {
  10509. GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft);
  10510. }
  10511. return GGML_STATUS_SUCCESS;
  10512. }
  10513. 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) {
  10514. VK_LOG_DEBUG("ggml_backend_vk_buffer_memset_tensor(" << buffer << ", " << tensor << ", " << value << ", " << offset << ", " << size << ")");
  10515. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10516. vk_buffer buf = buf_ctx->dev_buffer;
  10517. uint32_t val32 = (uint32_t)value * 0x01010101;
  10518. ggml_vk_buffer_memset(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, val32, size);
  10519. }
  10520. 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) {
  10521. VK_LOG_DEBUG("ggml_backend_vk_buffer_set_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10522. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10523. vk_buffer buf = buf_ctx->dev_buffer;
  10524. ggml_vk_buffer_write(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10525. }
  10526. 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) {
  10527. VK_LOG_DEBUG("ggml_backend_vk_buffer_get_tensor(" << buffer << ", " << tensor << ", " << data << ", " << offset << ", " << size << ")");
  10528. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10529. vk_buffer buf = buf_ctx->dev_buffer;
  10530. ggml_vk_buffer_read(buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10531. }
  10532. static bool ggml_backend_vk_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
  10533. if (ggml_backend_buffer_is_vk(src->buffer)) {
  10534. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10535. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10536. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10537. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10538. 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));
  10539. return true;
  10540. }
  10541. return false;
  10542. UNUSED(buffer);
  10543. }
  10544. static void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
  10545. ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context;
  10546. ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size);
  10547. }
  10548. static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
  10549. /* .free_buffer = */ ggml_backend_vk_buffer_free_buffer,
  10550. /* .get_base = */ ggml_backend_vk_buffer_get_base,
  10551. /* .init_tensor = */ ggml_backend_vk_buffer_init_tensor,
  10552. /* .memset_tensor = */ ggml_backend_vk_buffer_memset_tensor,
  10553. /* .set_tensor = */ ggml_backend_vk_buffer_set_tensor,
  10554. /* .get_tensor = */ ggml_backend_vk_buffer_get_tensor,
  10555. /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
  10556. /* .clear = */ ggml_backend_vk_buffer_clear,
  10557. /* .reset = */ NULL,
  10558. };
  10559. // vk buffer type
  10560. static const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10561. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  10562. return ctx->name.c_str();
  10563. }
  10564. static ggml_backend_buffer_t ggml_backend_vk_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10565. VK_LOG_MEMORY("ggml_backend_vk_buffer_type_alloc_buffer(" << size << ")");
  10566. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10567. vk_buffer dev_buffer = nullptr;
  10568. try {
  10569. dev_buffer = ggml_vk_create_buffer_device(ctx->device, size);
  10570. } catch (const vk::SystemError& e) {
  10571. return nullptr;
  10572. }
  10573. ggml_backend_vk_buffer_context * bufctx = new ggml_backend_vk_buffer_context(ctx->device, std::move(dev_buffer), ctx->name);
  10574. return ggml_backend_buffer_init(buft, ggml_backend_vk_buffer_interface, bufctx, size);
  10575. }
  10576. static size_t ggml_backend_vk_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10577. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10578. return ctx->device->properties.limits.minStorageBufferOffsetAlignment;
  10579. }
  10580. static size_t ggml_backend_vk_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10581. ggml_backend_vk_buffer_type_context * ctx = (ggml_backend_vk_buffer_type_context *) buft->context;
  10582. return ctx->device->suballocation_block_size;
  10583. }
  10584. static size_t ggml_backend_vk_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
  10585. return ggml_nbytes(tensor);
  10586. UNUSED(buft);
  10587. }
  10588. ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num) {
  10589. ggml_vk_instance_init();
  10590. VK_LOG_DEBUG("ggml_backend_vk_buffer_type(" << dev_num << ")");
  10591. vk_device dev = ggml_vk_get_device(dev_num);
  10592. return &dev->buffer_type;
  10593. }
  10594. // host buffer type
  10595. static const char * ggml_backend_vk_host_buffer_type_name(ggml_backend_buffer_type_t buft) {
  10596. return GGML_VK_NAME "_Host";
  10597. UNUSED(buft);
  10598. }
  10599. static const char * ggml_backend_vk_host_buffer_name(ggml_backend_buffer_t buffer) {
  10600. return GGML_VK_NAME "_Host";
  10601. UNUSED(buffer);
  10602. }
  10603. static void ggml_backend_vk_host_buffer_free_buffer(ggml_backend_buffer_t buffer) {
  10604. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_free_buffer()");
  10605. ggml_vk_host_free(vk_instance.devices[0], buffer->context);
  10606. }
  10607. static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
  10608. VK_LOG_MEMORY("ggml_backend_vk_host_buffer_type_alloc_buffer(" << size << ")");
  10609. size += 32; // Behave like the CPU buffer type
  10610. void * ptr = nullptr;
  10611. try {
  10612. ptr = ggml_vk_host_malloc(vk_instance.devices[0], size);
  10613. } catch (vk::SystemError& e) {
  10614. GGML_LOG_WARN("ggml_vulkan: Failed to allocate pinned memory (%s)\n", e.what());
  10615. // fallback to cpu buffer
  10616. return ggml_backend_buft_alloc_buffer(ggml_backend_cpu_buffer_type(), size);
  10617. }
  10618. ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
  10619. buffer->buft = buft;
  10620. buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
  10621. return buffer;
  10622. UNUSED(buft);
  10623. }
  10624. static size_t ggml_backend_vk_host_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
  10625. return vk_instance.devices[0]->properties.limits.minMemoryMapAlignment;
  10626. UNUSED(buft);
  10627. }
  10628. static size_t ggml_backend_vk_host_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
  10629. return vk_instance.devices[0]->suballocation_block_size;
  10630. UNUSED(buft);
  10631. }
  10632. // Should be changed to return device-specific host buffer type
  10633. // but that probably requires changes in llama.cpp
  10634. ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type() {
  10635. static struct ggml_backend_buffer_type ggml_backend_vk_buffer_type_host = {
  10636. /* .iface = */ {
  10637. /* .get_name = */ ggml_backend_vk_host_buffer_type_name,
  10638. /* .alloc_buffer = */ ggml_backend_vk_host_buffer_type_alloc_buffer,
  10639. /* .get_alignment = */ ggml_backend_vk_host_buffer_type_get_alignment,
  10640. /* .get_max_size = */ ggml_backend_vk_host_buffer_type_get_max_size,
  10641. /* .get_alloc_size = */ ggml_backend_cpu_buffer_type()->iface.get_alloc_size,
  10642. /* .is_host = */ ggml_backend_cpu_buffer_type()->iface.is_host,
  10643. },
  10644. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), 0),
  10645. /* .context = */ nullptr,
  10646. };
  10647. // Make sure device 0 is initialized
  10648. ggml_vk_instance_init();
  10649. ggml_vk_get_device(0);
  10650. return &ggml_backend_vk_buffer_type_host;
  10651. }
  10652. // backend
  10653. static const char * ggml_backend_vk_name(ggml_backend_t backend) {
  10654. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10655. return ctx->name.c_str();
  10656. }
  10657. static void ggml_backend_vk_free(ggml_backend_t backend) {
  10658. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10659. VK_LOG_DEBUG("ggml_backend_vk_free(" << ctx->name << ")");
  10660. ggml_vk_cleanup(ctx);
  10661. delete ctx;
  10662. delete backend;
  10663. }
  10664. static ggml_backend_buffer_type_t ggml_backend_vk_get_default_buffer_type(ggml_backend_t backend) {
  10665. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10666. return &ctx->device->buffer_type;
  10667. }
  10668. static void ggml_backend_vk_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
  10669. VK_LOG_DEBUG("ggml_backend_vk_set_tensor_async(" << size << ")");
  10670. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10671. 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");
  10672. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10673. vk_context transfer_ctx;
  10674. if (ctx->transfer_ctx.expired()) {
  10675. // Initialize new transfer context
  10676. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10677. ctx->transfer_ctx = transfer_ctx;
  10678. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10679. } else {
  10680. transfer_ctx = ctx->transfer_ctx.lock();
  10681. }
  10682. vk_buffer buf = buf_ctx->dev_buffer;
  10683. ggml_vk_buffer_write_async(transfer_ctx, buf, vk_tensor_offset(tensor) + tensor->view_offs + offset, data, size);
  10684. }
  10685. static void ggml_backend_vk_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
  10686. VK_LOG_DEBUG("ggml_backend_vk_get_tensor_async(" << size << ")");
  10687. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10688. 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");
  10689. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  10690. vk_context transfer_ctx;
  10691. if (ctx->transfer_ctx.expired()) {
  10692. // Initialize new transfer context
  10693. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10694. ctx->transfer_ctx = transfer_ctx;
  10695. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10696. } else {
  10697. transfer_ctx = ctx->transfer_ctx.lock();
  10698. }
  10699. vk_buffer buf = buf_ctx->dev_buffer;
  10700. auto src_offset = vk_tensor_offset(tensor) + tensor->view_offs + offset;
  10701. bool ret = ggml_vk_buffer_read_async(transfer_ctx, buf, src_offset, data, size);
  10702. // If that failed, copy synchronously through a staging buffer
  10703. if (!ret) {
  10704. ggml_vk_ensure_sync_staging_buffer(ctx, size);
  10705. ggml_vk_sync_buffers(nullptr, transfer_ctx);
  10706. vk::BufferCopy buffer_cpy;
  10707. buffer_cpy.srcOffset = src_offset;
  10708. buffer_cpy.dstOffset = 0;
  10709. buffer_cpy.size = size;
  10710. transfer_ctx->s->buffer.copyBuffer(buf->buffer, ctx->sync_staging->buffer, { buffer_cpy });
  10711. deferred_memcpy(data, ctx->sync_staging->ptr, size, &transfer_ctx->out_memcpys);
  10712. ggml_vk_synchronize(ctx);
  10713. }
  10714. }
  10715. static bool ggml_backend_vk_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) {
  10716. VK_LOG_DEBUG("ggml_backend_vk_cpy_tensor_async()");
  10717. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10718. 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)) {
  10719. ggml_backend_vk_buffer_context * src_buf_ctx = (ggml_backend_vk_buffer_context *)src->buffer->context;
  10720. ggml_backend_vk_buffer_context * dst_buf_ctx = (ggml_backend_vk_buffer_context *)dst->buffer->context;
  10721. vk_context transfer_ctx;
  10722. if (ctx->transfer_ctx.expired()) {
  10723. // Initialize new transfer context
  10724. transfer_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  10725. ctx->transfer_ctx = transfer_ctx;
  10726. ggml_vk_ctx_begin(ctx->device, transfer_ctx);
  10727. } else {
  10728. transfer_ctx = ctx->transfer_ctx.lock();
  10729. }
  10730. vk_buffer src_buf = src_buf_ctx->dev_buffer;
  10731. vk_buffer dst_buf = dst_buf_ctx->dev_buffer;
  10732. 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));
  10733. return true;
  10734. }
  10735. return false;
  10736. }
  10737. static void ggml_vk_synchronize(ggml_backend_vk_context * ctx) {
  10738. VK_LOG_DEBUG("ggml_vk_synchronize()");
  10739. bool do_transfer = !ctx->transfer_ctx.expired();
  10740. vk_context transfer_ctx;
  10741. if (do_transfer) {
  10742. transfer_ctx = ctx->transfer_ctx.lock();
  10743. ggml_vk_ctx_end(transfer_ctx);
  10744. for (auto& cpy : transfer_ctx->in_memcpys) {
  10745. memcpy(cpy.dst, cpy.src, cpy.n);
  10746. }
  10747. ggml_vk_submit(transfer_ctx, {});
  10748. ctx->submit_pending = true;
  10749. }
  10750. if (ctx->submit_pending) {
  10751. {
  10752. std::lock_guard<std::mutex> guard(queue_mutex);
  10753. ctx->device->compute_queue.queue.submit({}, ctx->fence);
  10754. }
  10755. ggml_vk_wait_for_fence(ctx);
  10756. ctx->submit_pending = false;
  10757. }
  10758. if (do_transfer) {
  10759. for (auto& cpy : transfer_ctx->out_memcpys) {
  10760. memcpy(cpy.dst, cpy.src, cpy.n);
  10761. }
  10762. ctx->transfer_ctx.reset();
  10763. }
  10764. }
  10765. static void ggml_backend_vk_synchronize(ggml_backend_t backend) {
  10766. VK_LOG_DEBUG("ggml_backend_vk_synchronize()");
  10767. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  10768. ggml_vk_synchronize(ctx);
  10769. ggml_vk_graph_cleanup(ctx);
  10770. }
  10771. static bool ggml_vk_is_empty(ggml_tensor * node) {
  10772. 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;
  10773. }
  10774. static bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list<enum ggml_op> ops) {
  10775. if (!ggml_can_fuse(cgraph, node_idx, ops)) {
  10776. return false;
  10777. }
  10778. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
  10779. // additional constraints specific to this fusion
  10780. const ggml_tensor *rms_norm = cgraph->nodes[node_idx];
  10781. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10782. GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32);
  10783. GGML_ASSERT(rms_norm->type == GGML_TYPE_F32);
  10784. // rms_norm only supports f32
  10785. if (mul->src[0]->type != GGML_TYPE_F32 ||
  10786. mul->src[1]->type != GGML_TYPE_F32 ||
  10787. mul->type != GGML_TYPE_F32) {
  10788. return false;
  10789. }
  10790. // if rms_norm is the B operand, then we don't handle broadcast
  10791. if (rms_norm == mul->src[1] &&
  10792. !ggml_are_same_shape(mul->src[0], rms_norm)) {
  10793. return false;
  10794. }
  10795. // rms_norm shader assumes contiguous rows
  10796. if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) {
  10797. return false;
  10798. }
  10799. }
  10800. auto const &mm_add_ok = [&](const ggml_tensor *mul, const ggml_tensor *add) {
  10801. const ggml_tensor *bias = add->src[0] == mul ? add->src[1] : add->src[0];
  10802. // mat-vec only
  10803. if (ggml_nrows(mul) != 1) {
  10804. return false;
  10805. }
  10806. // shaders assume the types match
  10807. if (mul->type != bias->type) {
  10808. return false;
  10809. }
  10810. // shaders reuse the D shape for bias
  10811. if (!ggml_are_same_shape(mul, bias) ||
  10812. !ggml_are_same_stride(mul, bias)) {
  10813. return false;
  10814. }
  10815. // unaligned bias isn't handled
  10816. if (get_misalign_bytes(ctx, bias) != 0) {
  10817. return false;
  10818. }
  10819. return true;
  10820. };
  10821. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT && ops.begin()[1] == GGML_OP_ADD) {
  10822. // additional constraints specific to this fusion
  10823. const ggml_tensor *mul = cgraph->nodes[node_idx];
  10824. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  10825. if (!mm_add_ok(mul, add)) {
  10826. return false;
  10827. }
  10828. if (ops.size() == 3) {
  10829. if (ops.begin()[2] != GGML_OP_ADD) {
  10830. return false;
  10831. }
  10832. if (!mm_add_ok(add, cgraph->nodes[node_idx + 2])) {
  10833. return false;
  10834. }
  10835. }
  10836. }
  10837. auto const &mmid_mul_ok = [&](const ggml_tensor *mmid, const ggml_tensor *mul) {
  10838. const ggml_tensor *scale = mul->src[1];
  10839. if (mmid != mul->src[0]) {
  10840. return false;
  10841. }
  10842. // mat-vec only
  10843. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  10844. return false;
  10845. }
  10846. // shaders assume the types match
  10847. if (mmid->type != scale->type) {
  10848. return false;
  10849. }
  10850. // shaders assume the bias is contiguous
  10851. if (!ggml_is_contiguous(scale)) {
  10852. return false;
  10853. }
  10854. // unaligned bias isn't handled
  10855. if (get_misalign_bytes(ctx, scale) != 0) {
  10856. return false;
  10857. }
  10858. // shader only indexes by expert index
  10859. if (scale->ne[0] != 1 ||
  10860. scale->ne[1] != mul->ne[1] ||
  10861. scale->ne[2] != 1 ||
  10862. scale->ne[3] != 1) {
  10863. return false;
  10864. }
  10865. return true;
  10866. };
  10867. if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_ADD_ID) {
  10868. // additional constraints specific to this fusion
  10869. const ggml_tensor *mul = cgraph->nodes[node_idx];
  10870. const ggml_tensor *add = cgraph->nodes[node_idx + 1];
  10871. const ggml_tensor *bias = add->src[1];
  10872. if (mul != add->src[0]) {
  10873. return false;
  10874. }
  10875. // mat-vec only
  10876. if (!ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
  10877. return false;
  10878. }
  10879. // shaders assume the types match
  10880. if (mul->type != bias->type) {
  10881. return false;
  10882. }
  10883. // shaders assume the bias is contiguous
  10884. if (!ggml_is_contiguous(bias)) {
  10885. return false;
  10886. }
  10887. // the ID tensor must be the same for mul_mat_id and add_id
  10888. if (mul->src[2] != add->src[2]) {
  10889. return false;
  10890. }
  10891. // unaligned bias isn't handled
  10892. if (get_misalign_bytes(ctx, bias) != 0) {
  10893. return false;
  10894. }
  10895. if (ops.size() == 3) {
  10896. if (ops.begin()[2] != GGML_OP_MUL) {
  10897. return false;
  10898. }
  10899. const ggml_tensor *mul = cgraph->nodes[node_idx + 2];
  10900. return mmid_mul_ok(add, mul);
  10901. }
  10902. }
  10903. if (ops.size() == 2 && ops.begin()[0] == GGML_OP_MUL_MAT_ID && ops.begin()[1] == GGML_OP_MUL) {
  10904. // additional constraints specific to this fusion
  10905. const ggml_tensor *mmid = cgraph->nodes[node_idx];
  10906. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  10907. if (!mmid_mul_ok(mmid, mul)) {
  10908. return false;
  10909. }
  10910. }
  10911. return true;
  10912. }
  10913. static bool ggml_vk_can_fuse_topk_moe(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10914. int node_idx, topk_moe_mode mode) {
  10915. const ggml_tensor * softmax;
  10916. const ggml_tensor * weights;
  10917. switch (mode) {
  10918. case TOPK_MOE_EARLY_SOFTMAX_NORM:
  10919. softmax = cgraph->nodes[node_idx + 0];
  10920. weights = cgraph->nodes[node_idx + 9];
  10921. break;
  10922. case TOPK_MOE_EARLY_SOFTMAX:
  10923. softmax = cgraph->nodes[node_idx + 0];
  10924. weights = cgraph->nodes[node_idx + 4];
  10925. break;
  10926. case TOPK_MOE_LATE_SOFTMAX:
  10927. softmax = cgraph->nodes[node_idx + 4];
  10928. weights = cgraph->nodes[node_idx + 5];
  10929. break;
  10930. default:
  10931. return false;
  10932. }
  10933. const float * op_params = (const float *)softmax->op_params;
  10934. float scale = op_params[0];
  10935. float max_bias = op_params[1];
  10936. if (!ggml_is_contiguous(softmax->src[0]) || !ggml_is_contiguous(weights)) {
  10937. return false;
  10938. }
  10939. if (scale != 1.0f || max_bias != 0.0f) {
  10940. return false;
  10941. }
  10942. // don't fuse when masks or sinks are present
  10943. if (softmax->src[1] || softmax->src[2]) {
  10944. return false;
  10945. }
  10946. const int n_expert = softmax->ne[0];
  10947. // n_expert must be a power of 2
  10948. if (!is_pow2(n_expert) || n_expert > (1 << (num_topk_moe_pipelines-1))) {
  10949. return false;
  10950. }
  10951. if (!ctx->device->subgroup_arithmetic ||
  10952. !ctx->device->subgroup_shuffle ||
  10953. !ctx->device->subgroup_require_full_support ||
  10954. ctx->device->disable_fusion) {
  10955. return false;
  10956. }
  10957. return true;
  10958. }
  10959. static bool ggml_vk_can_fuse_rope_set_rows(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  10960. int node_idx) {
  10961. GGML_UNUSED(ctx);
  10962. const ggml_tensor *rope = cgraph->nodes[node_idx + 0];
  10963. const ggml_tensor *view = cgraph->nodes[node_idx + 1];
  10964. const ggml_tensor *set_rows = cgraph->nodes[node_idx + 2];
  10965. // ne3 not tested
  10966. if (rope->src[0]->ne[3] != 1) {
  10967. return false;
  10968. }
  10969. if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) {
  10970. return false;
  10971. }
  10972. if (set_rows->src[1]->type != GGML_TYPE_I64) {
  10973. return false;
  10974. }
  10975. // The view should flatten two dims of rope into one dim
  10976. if (!ggml_is_contiguous(view) ||
  10977. view->ne[0] != rope->ne[0] * rope->ne[1]) {
  10978. return false;
  10979. }
  10980. // Only norm/neox shaders have the fusion code
  10981. const int mode = ((const int32_t *) rope->op_params)[2];
  10982. if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX) {
  10983. return false;
  10984. }
  10985. return true;
  10986. }
  10987. // Check whether the tensors overlap in memory but are not equal.
  10988. // Fusions can potenitally overwrite src tensors in ways that are not prevented
  10989. // by ggml-alloc. If the fusion is entirely elementwise, then it's OK for them
  10990. // to overlap if they are exactly equal.
  10991. // XXX TODO this check is probably missing from several fusion optimizations.
  10992. static bool ggml_vk_tensors_overlap_but_not_equal(const ggml_tensor * a, const ggml_tensor * b) {
  10993. ggml_backend_vk_buffer_context * a_buf_ctx = (ggml_backend_vk_buffer_context *)a->buffer->context;
  10994. vk_buffer a_buf = a_buf_ctx->dev_buffer;
  10995. ggml_backend_vk_buffer_context * b_buf_ctx = (ggml_backend_vk_buffer_context *)b->buffer->context;
  10996. vk_buffer b_buf = b_buf_ctx->dev_buffer;
  10997. if (a_buf == b_buf) {
  10998. auto a_base = vk_tensor_offset(a) + a->view_offs;
  10999. auto a_size = ggml_nbytes(a);
  11000. auto b_base = vk_tensor_offset(b) + b->view_offs;
  11001. auto b_size = ggml_nbytes(b);
  11002. if (a_base == b_base && a_size == b_size) {
  11003. return false;
  11004. }
  11005. if ((b_base <= a_base && a_base < b_base + b_size) ||
  11006. (a_base <= b_base && b_base < a_base + a_size)) {
  11007. return true;
  11008. }
  11009. }
  11010. return false;
  11011. }
  11012. static bool ggml_vk_can_fuse_rms_norm_mul_rope(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph,
  11013. int node_idx) {
  11014. GGML_UNUSED(ctx);
  11015. const ggml_tensor *rms = cgraph->nodes[node_idx + 0];
  11016. const ggml_tensor *mul = cgraph->nodes[node_idx + 1];
  11017. const ggml_tensor *rope = cgraph->nodes[node_idx + 2];
  11018. const int mode = ((const int32_t *) rope->op_params)[2];
  11019. // noncontig tensors aren't tested, and don't seem common in practice
  11020. if (!ggml_is_contiguous(rms) ||
  11021. !ggml_is_contiguous(mul) ||
  11022. !ggml_is_contiguous(rope)) {
  11023. return false;
  11024. }
  11025. // only norm/neox are handled in the shader
  11026. if (mode != GGML_ROPE_TYPE_NEOX && mode != GGML_ROPE_TYPE_NORMAL) {
  11027. return false;
  11028. }
  11029. // shared memory size for passing data from mul->rope
  11030. if (mul->ne[0] > 1024) {
  11031. return false;
  11032. }
  11033. // must not overwrite srcs in a way that's not elementwise
  11034. ggml_tensor *other_src = mul->src[0] == rms ? mul->src[1] : mul->src[0];
  11035. if (ggml_vk_tensors_overlap_but_not_equal(rms->src[0], rope) ||
  11036. ggml_vk_tensors_overlap_but_not_equal(other_src, rope)) {
  11037. return false;
  11038. }
  11039. // conditions for pipeline creation
  11040. if (!(ctx->device->float_controls_rte_fp16 &&
  11041. sizeof(vk_op_rms_norm_mul_rope_push_constants) <= ctx->device->properties.limits.maxPushConstantsSize)) {
  11042. return false;
  11043. }
  11044. return true;
  11045. }
  11046. static uint32_t ggml_vk_fuse_multi_add(ggml_backend_vk_context * ctx, const struct ggml_cgraph * cgraph, int node_idx) {
  11047. const ggml_tensor *first_node = cgraph->nodes[node_idx];
  11048. if (first_node->op != GGML_OP_ADD) {
  11049. return 0;
  11050. }
  11051. if (!ctx->device->multi_add) {
  11052. return 0;
  11053. }
  11054. int32_t num_adds = 1;
  11055. while (node_idx + num_adds < cgraph->n_nodes &&
  11056. cgraph->nodes[node_idx + num_adds]->op == GGML_OP_ADD &&
  11057. num_adds < MAX_FUSED_ADDS) {
  11058. num_adds++;
  11059. }
  11060. // The shader currently requires same shapes (but different strides are allowed),
  11061. // everything f32, and no misalignment
  11062. for (int32_t i = 0; i < num_adds; ++i) {
  11063. const ggml_tensor *next_node = cgraph->nodes[node_idx + i];
  11064. if (!ggml_are_same_shape(first_node, next_node->src[0]) ||
  11065. !ggml_are_same_shape(first_node, next_node->src[1]) ||
  11066. next_node->type != GGML_TYPE_F32 ||
  11067. next_node->src[0]->type != GGML_TYPE_F32 ||
  11068. next_node->src[1]->type != GGML_TYPE_F32 ||
  11069. get_misalign_bytes(ctx, next_node) ||
  11070. get_misalign_bytes(ctx, next_node->src[0]) ||
  11071. get_misalign_bytes(ctx, next_node->src[1])) {
  11072. num_adds = i;
  11073. }
  11074. }
  11075. // Verify we can fuse these
  11076. ggml_op adds[MAX_FUSED_ADDS];
  11077. for (int32_t i = 0; i < num_adds; ++i) {
  11078. adds[i] = GGML_OP_ADD;
  11079. }
  11080. // decrease num_adds if they can't all be fused
  11081. while (num_adds > 1 && !ggml_can_fuse(cgraph, node_idx, adds, num_adds)) {
  11082. num_adds--;
  11083. }
  11084. // a single add is not "fused", so just return zero
  11085. if (num_adds == 1) {
  11086. return 0;
  11087. }
  11088. return num_adds;
  11089. }
  11090. static ggml_status ggml_backend_vk_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
  11091. VK_LOG_DEBUG("ggml_backend_vk_graph_compute(" << cgraph->n_nodes << " nodes)");
  11092. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11093. if (vk_instance.debug_utils_support) {
  11094. vk::DebugUtilsLabelEXT dul = {};
  11095. dul.pLabelName = "ggml_backend_vk_graph_compute";
  11096. dul.color = std::array<float,4>{1.0f, 1.0f, 1.0f, 1.0f};
  11097. vk_instance.pfn_vkQueueBeginDebugUtilsLabelEXT(ctx->device->compute_queue.queue, reinterpret_cast<VkDebugUtilsLabelEXT*>(&dul));
  11098. }
  11099. ctx->prealloc_size_add_rms_partials_offset = 0;
  11100. ctx->do_add_rms_partials = false;
  11101. ctx->do_add_rms_partials_offset_calculation = false;
  11102. int last_node = cgraph->n_nodes - 1;
  11103. // If the last op in the cgraph isn't backend GPU, the command buffer doesn't get closed properly
  11104. while (last_node > 0 && ggml_vk_is_empty(cgraph->nodes[last_node])) {
  11105. last_node -= 1;
  11106. }
  11107. // Reserve tensor context space for all nodes
  11108. ctx->tensor_ctxs.resize(cgraph->n_nodes);
  11109. bool first_node_in_batch = true; // true if next node will be first node in a batch
  11110. int submit_node_idx = 0; // index to first node in a batch
  11111. vk_context compute_ctx;
  11112. if (vk_perf_logger_enabled) {
  11113. // allocate/resize the query pool
  11114. if (ctx->device->num_queries < cgraph->n_nodes + 1) {
  11115. if (ctx->device->query_pool) {
  11116. ctx->device->device.destroyQueryPool(ctx->device->query_pool);
  11117. }
  11118. vk::QueryPoolCreateInfo query_create_info;
  11119. query_create_info.queryType = vk::QueryType::eTimestamp;
  11120. query_create_info.queryCount = cgraph->n_nodes + 100;
  11121. ctx->device->query_pool = ctx->device->device.createQueryPool(query_create_info);
  11122. ctx->device->num_queries = query_create_info.queryCount;
  11123. }
  11124. ctx->device->device.resetQueryPool(ctx->device->query_pool, 0, cgraph->n_nodes+1);
  11125. GGML_ASSERT(ctx->compute_ctx.expired());
  11126. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11127. ctx->compute_ctx = compute_ctx;
  11128. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11129. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, 0);
  11130. }
  11131. ctx->prealloc_y_last_pipeline_used = nullptr;
  11132. ctx->prealloc_y_last_tensor_used = nullptr;
  11133. if (ctx->prealloc_size_add_rms_partials) {
  11134. ggml_vk_preallocate_buffers(ctx, nullptr);
  11135. if (ctx->compute_ctx.expired()) {
  11136. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11137. ctx->compute_ctx = compute_ctx;
  11138. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11139. } else {
  11140. compute_ctx = ctx->compute_ctx.lock();
  11141. }
  11142. // initialize partial sums to zero.
  11143. ggml_vk_buffer_memset_async(compute_ctx, ctx->prealloc_add_rms_partials, 0, 0, ctx->prealloc_size_add_rms_partials);
  11144. ggml_vk_sync_buffers(ctx, compute_ctx);
  11145. }
  11146. // Submit after enough work has accumulated, to overlap CPU cmdbuffer generation with GPU execution.
  11147. // Estimate the amount of matmul work by looking at the weight matrix size, and submit every 100MB
  11148. // (and scaled down based on model size, so smaller models submit earlier).
  11149. // Also submit at least every 100 nodes, in case there are workloads without as much matmul.
  11150. int nodes_per_submit = 100;
  11151. int submitted_nodes = 0;
  11152. int submit_count = 0;
  11153. uint64_t mul_mat_bytes = 0;
  11154. uint64_t total_mul_mat_bytes = 0;
  11155. uint64_t mul_mat_bytes_per_submit = std::min(uint64_t(100*1000*1000), ctx->last_total_mul_mat_bytes / 40u);
  11156. for (int i = 0; i < cgraph->n_nodes; i++) {
  11157. if (first_node_in_batch) {
  11158. submit_node_idx = i;
  11159. }
  11160. if (cgraph->nodes[i]->op == GGML_OP_MUL_MAT || cgraph->nodes[i]->op == GGML_OP_MUL_MAT_ID) {
  11161. auto bytes = ggml_nbytes(cgraph->nodes[i]->src[0]);
  11162. mul_mat_bytes += bytes;
  11163. total_mul_mat_bytes += bytes;
  11164. }
  11165. if (!ctx->device->disable_fusion) {
  11166. uint32_t num_adds = ggml_vk_fuse_multi_add(ctx, cgraph, i);
  11167. if (num_adds) {
  11168. ctx->num_additional_fused_ops = num_adds - 1;
  11169. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_ADD })) {
  11170. ctx->num_additional_fused_ops = 2;
  11171. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_ADD })) {
  11172. ctx->num_additional_fused_ops = 1;
  11173. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_MUL })) {
  11174. ctx->num_additional_fused_ops = 2;
  11175. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID })) {
  11176. ctx->num_additional_fused_ops = 1;
  11177. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_MUL_MAT_ID, GGML_OP_MUL })) {
  11178. ctx->num_additional_fused_ops = 1;
  11179. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 4 }) &&
  11180. ggml_check_edges(cgraph, i, rms_norm_mul_rope_view_set_rows_edges) &&
  11181. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i) &&
  11182. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i + 2)) {
  11183. ctx->num_additional_fused_ops = 4;
  11184. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE })&&
  11185. ggml_vk_can_fuse_rms_norm_mul_rope(ctx, cgraph, i)) {
  11186. ctx->num_additional_fused_ops = 2;
  11187. } else if (ggml_vk_can_fuse(ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) {
  11188. ctx->num_additional_fused_ops = 1;
  11189. } else if (ggml_can_fuse_subgraph(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, { i + 2 }) &&
  11190. ggml_check_edges(cgraph, i, rope_view_set_rows_edges) &&
  11191. ggml_vk_can_fuse_rope_set_rows(ctx, cgraph, i)) {
  11192. ctx->num_additional_fused_ops = 2;
  11193. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax_norm, { i + 3, i + 9 }) &&
  11194. ggml_check_edges(cgraph, i, topk_moe_early_softmax_norm_edges) &&
  11195. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX_NORM)) {
  11196. ctx->num_additional_fused_ops = topk_moe_early_softmax_norm.size() - 1;
  11197. // view of argsort writes to memory
  11198. ctx->fused_ops_write_mask |= 1 << 3;
  11199. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_early_softmax, { i + 3, i + 4 }) &&
  11200. ggml_check_edges(cgraph, i, topk_moe_early_softmax_edges) &&
  11201. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_EARLY_SOFTMAX)) {
  11202. ctx->num_additional_fused_ops = topk_moe_early_softmax.size() - 1;
  11203. // view of argsort writes to memory
  11204. ctx->fused_ops_write_mask |= 1 << 3;
  11205. } else if (ggml_can_fuse_subgraph(cgraph, i, topk_moe_late_softmax, { i + 1, i + 5 }) &&
  11206. ggml_check_edges(cgraph, i, topk_moe_late_softmax_edges) &&
  11207. ggml_vk_can_fuse_topk_moe(ctx, cgraph, i, TOPK_MOE_LATE_SOFTMAX)) {
  11208. ctx->num_additional_fused_ops = topk_moe_late_softmax.size() - 1;
  11209. // view of argsort writes to memory
  11210. ctx->fused_ops_write_mask |= 1 << 1;
  11211. }
  11212. }
  11213. ctx->fused_ops_write_mask |= 1 << ctx->num_additional_fused_ops;
  11214. // Signal the almost_ready fence when the graph is mostly complete (< 20% remaining)
  11215. bool almost_ready = (cgraph->n_nodes - i) < cgraph->n_nodes / 5;
  11216. bool submit = (submitted_nodes >= nodes_per_submit) ||
  11217. (mul_mat_bytes_per_submit != 0 && mul_mat_bytes >= mul_mat_bytes_per_submit) ||
  11218. (i + ctx->num_additional_fused_ops >= last_node) ||
  11219. (almost_ready && !ctx->almost_ready_fence_pending);
  11220. bool enqueued = ggml_vk_build_graph(ctx, cgraph, i, cgraph->nodes[submit_node_idx], submit_node_idx, i + ctx->num_additional_fused_ops >= last_node, almost_ready, submit);
  11221. if (vk_perf_logger_enabled) {
  11222. if (ctx->compute_ctx.expired()) {
  11223. compute_ctx = ggml_vk_create_context(ctx, ctx->compute_cmd_pool);
  11224. ctx->compute_ctx = compute_ctx;
  11225. ggml_vk_ctx_begin(ctx->device, compute_ctx);
  11226. } else {
  11227. compute_ctx = ctx->compute_ctx.lock();
  11228. }
  11229. // If there are fused ops, just write out timestamps for all nodes to keep the accounting simple
  11230. for (int j = 0; j < ctx->num_additional_fused_ops + 1; ++j) {
  11231. compute_ctx->s->buffer.writeTimestamp(vk::PipelineStageFlagBits::eAllCommands, ctx->device->query_pool, i+j+1);
  11232. }
  11233. }
  11234. if (enqueued) {
  11235. ++submitted_nodes;
  11236. #ifndef GGML_VULKAN_CHECK_RESULTS
  11237. if (first_node_in_batch) {
  11238. first_node_in_batch = false;
  11239. }
  11240. #endif
  11241. }
  11242. if (submit && enqueued) {
  11243. first_node_in_batch = true;
  11244. submitted_nodes = 0;
  11245. mul_mat_bytes = 0;
  11246. if (submit_count < 3) {
  11247. mul_mat_bytes_per_submit *= 2;
  11248. }
  11249. submit_count++;
  11250. }
  11251. i += ctx->num_additional_fused_ops;
  11252. ctx->num_additional_fused_ops = 0;
  11253. ctx->fused_ops_write_mask = 0;
  11254. }
  11255. ctx->prealloc_size_add_rms_partials = std::max(ctx->prealloc_size_add_rms_partials, ctx->prealloc_size_add_rms_partials_offset);
  11256. ctx->last_total_mul_mat_bytes = total_mul_mat_bytes;
  11257. if (vk_perf_logger_enabled) {
  11258. // End the command buffer and submit/wait
  11259. GGML_ASSERT(!ctx->compute_ctx.expired());
  11260. compute_ctx = ctx->compute_ctx.lock();
  11261. ggml_vk_ctx_end(compute_ctx);
  11262. ggml_vk_submit(compute_ctx, ctx->device->fence);
  11263. VK_CHECK(ctx->device->device.waitForFences({ ctx->device->fence }, true, UINT64_MAX), "GGML_VULKAN_PERF waitForFences");
  11264. ctx->device->device.resetFences({ ctx->device->fence });
  11265. // Get the results and pass them to the logger
  11266. std::vector<uint64_t> timestamps(cgraph->n_nodes + 1);
  11267. 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");
  11268. for (int i = 0; i < cgraph->n_nodes; i++) {
  11269. if (!ggml_vk_is_empty(cgraph->nodes[i])) {
  11270. ctx->device->perf_logger->log_timing(cgraph->nodes[i], uint64_t((timestamps[i+1] - timestamps[i]) * ctx->device->properties.limits.timestampPeriod));
  11271. }
  11272. }
  11273. ctx->device->perf_logger->print_timings();
  11274. }
  11275. return GGML_STATUS_SUCCESS;
  11276. UNUSED(backend);
  11277. }
  11278. // Sort the graph for improved parallelism.
  11279. static void ggml_vk_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * graph)
  11280. {
  11281. VK_LOG_DEBUG("ggml_vk_graph_optimize(" << graph->n_nodes << " nodes)");
  11282. ggml_backend_vk_context * ctx = (ggml_backend_vk_context *)backend->context;
  11283. if (ctx->device->disable_graph_optimize) {
  11284. return;
  11285. }
  11286. auto const &is_empty = [](ggml_tensor * node) -> bool {
  11287. return node->op == GGML_OP_NONE || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE;
  11288. };
  11289. auto const &is_src_of = [](const ggml_tensor *dst, const ggml_tensor *src) -> bool {
  11290. for (uint32_t s = 0; s < GGML_MAX_SRC; ++s) {
  11291. if (dst->src[s] == src) {
  11292. return true;
  11293. }
  11294. }
  11295. // implicit dependency if they view the same tensor
  11296. const ggml_tensor *dst2 = dst->view_src ? dst->view_src : dst;
  11297. const ggml_tensor *src2 = src->view_src ? src->view_src : src;
  11298. if (dst2 == src2) {
  11299. return true;
  11300. }
  11301. return false;
  11302. };
  11303. // This function tries to reorder the graph to allow nodes to run in parallel.
  11304. // This helps with small batches, but for large batches its a slowdown, probably
  11305. // due to cache contention. So only reorder if the majority of nodes have few rows.
  11306. int num_small_nodes = 0;
  11307. int num_counted_nodes = 0;
  11308. for (int i = 0; i < graph->n_nodes; ++i) {
  11309. if (!is_empty(graph->nodes[i]) &&
  11310. graph->nodes[i]->op != GGML_OP_SET_ROWS) {
  11311. if (ggml_nrows(graph->nodes[i]) <= 8) {
  11312. num_small_nodes++;
  11313. }
  11314. num_counted_nodes++;
  11315. }
  11316. }
  11317. if (num_small_nodes < num_counted_nodes / 2) {
  11318. return;
  11319. }
  11320. std::vector<ggml_tensor *> new_order;
  11321. std::vector<bool> used(graph->n_nodes, false);
  11322. std::set<ggml_tensor *> used_node_set;
  11323. int first_unused = 0;
  11324. while (first_unused < graph->n_nodes) {
  11325. std::vector<int> current_set;
  11326. // Check for fusion patterns and avoid reordering them
  11327. auto const &match_pattern = [&](const std::initializer_list<ggml_op> &pattern, int start) -> bool {
  11328. if (start + (int)pattern.size() <= graph->n_nodes) {
  11329. bool is_pattern = true;
  11330. for (size_t j = 0; j < pattern.size(); ++j) {
  11331. if (graph->nodes[start + j]->op != pattern.begin()[j] || used[start + j]) {
  11332. is_pattern = false;
  11333. }
  11334. }
  11335. return is_pattern;
  11336. }
  11337. return false;
  11338. };
  11339. auto const &keep_pattern = [&](const std::initializer_list<ggml_op> &pattern) -> bool {
  11340. if (match_pattern(pattern, first_unused)) {
  11341. for (size_t j = 0; j < pattern.size(); ++j) {
  11342. new_order.push_back(graph->nodes[first_unused + j]);
  11343. used_node_set.insert(graph->nodes[first_unused + j]);
  11344. used[first_unused + j] = true;
  11345. }
  11346. while (first_unused < graph->n_nodes && used[first_unused]) {
  11347. first_unused++;
  11348. }
  11349. return true;
  11350. }
  11351. return false;
  11352. };
  11353. if (keep_pattern(topk_moe_early_softmax_norm)) {
  11354. continue;
  11355. }
  11356. if (keep_pattern(topk_moe_early_softmax)) {
  11357. continue;
  11358. }
  11359. if (keep_pattern(topk_moe_late_softmax)) {
  11360. continue;
  11361. }
  11362. // First, grab the next unused node.
  11363. current_set.push_back(first_unused);
  11364. // Loop through the next N nodes. Grab any that don't depend on other nodes that
  11365. // haven't already been run. Nodes that have already been run have used[i] set
  11366. // to true. Allow nodes that depend on the previous node if it's a fusion pattern
  11367. // that we support (e.g. RMS_NORM + MUL).
  11368. // This first pass only grabs "real" (non-view nodes). Second pass grabs view nodes.
  11369. // The goal is to not interleave real and view nodes in a way that breaks fusion.
  11370. const int NUM_TO_CHECK = 20;
  11371. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11372. if (used[j]) {
  11373. continue;
  11374. }
  11375. if (is_empty(graph->nodes[j])) {
  11376. continue;
  11377. }
  11378. // Don't pull forward nodes from fusion patterns
  11379. if (match_pattern(topk_moe_early_softmax_norm, j) ||
  11380. match_pattern(topk_moe_early_softmax, j) ||
  11381. match_pattern(topk_moe_late_softmax, j)) {
  11382. continue;
  11383. }
  11384. bool ok = true;
  11385. for (int c = first_unused; c < j; ++c) {
  11386. if (!used[c] &&
  11387. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11388. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_RMS_NORM && graph->nodes[j]->op == GGML_OP_MUL) &&
  11389. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT && graph->nodes[j]->op == GGML_OP_ADD) &&
  11390. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_ADD_ID) &&
  11391. !(j == c+1 && c == current_set.back() && graph->nodes[c]->op == GGML_OP_MUL_MAT_ID && graph->nodes[j]->op == GGML_OP_MUL)) {
  11392. ok = false;
  11393. break;
  11394. }
  11395. }
  11396. if (ok) {
  11397. current_set.push_back(j);
  11398. int rope_idx = j;
  11399. // When we've found RMS_NORM + MUL, try to find a ROPE that uses it
  11400. if (j > 0 &&
  11401. graph->nodes[j]->op == GGML_OP_MUL &&
  11402. graph->nodes[j-1]->op == GGML_OP_RMS_NORM) {
  11403. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11404. if (graph->nodes[k]->op == GGML_OP_ROPE &&
  11405. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11406. // Check that other srcs are already valid
  11407. graph->nodes[k]->src[1]->op == GGML_OP_NONE &&
  11408. (graph->nodes[k]->src[2] == nullptr || graph->nodes[k]->src[2]->op == GGML_OP_NONE)) {
  11409. rope_idx = k;
  11410. current_set.push_back(rope_idx);
  11411. used[rope_idx] = true;
  11412. break;
  11413. }
  11414. }
  11415. }
  11416. // Look for ROPE + VIEW + SET_ROWS and make them consecutive
  11417. if (graph->nodes[rope_idx]->op == GGML_OP_ROPE) {
  11418. int view_idx = -1;
  11419. int set_rows_idx = -1;
  11420. for (int k = rope_idx+1; k < std::min(rope_idx + 10, graph->n_nodes); ++k) {
  11421. if (view_idx == -1 &&
  11422. graph->nodes[k]->op == GGML_OP_VIEW &&
  11423. graph->nodes[k]->src[0] == graph->nodes[rope_idx]) {
  11424. view_idx = k;
  11425. continue;
  11426. }
  11427. if (view_idx != -1 &&
  11428. set_rows_idx == -1 &&
  11429. graph->nodes[k]->op == GGML_OP_SET_ROWS &&
  11430. graph->nodes[k]->src[0] == graph->nodes[view_idx]) {
  11431. set_rows_idx = k;
  11432. break;
  11433. }
  11434. }
  11435. if (set_rows_idx != -1) {
  11436. current_set.push_back(view_idx);
  11437. current_set.push_back(set_rows_idx);
  11438. used[view_idx] = true;
  11439. used[set_rows_idx] = true;
  11440. }
  11441. }
  11442. // Look for MUL_MAT_ID + ADD_ID + MUL
  11443. if (j > 0 &&
  11444. graph->nodes[j]->op == GGML_OP_ADD_ID &&
  11445. graph->nodes[j-1]->op == GGML_OP_MUL_MAT_ID) {
  11446. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11447. if (graph->nodes[k]->op == GGML_OP_MUL &&
  11448. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11449. // src1 must either be weights or already processed
  11450. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  11451. current_set.push_back(k);
  11452. used[k] = true;
  11453. break;
  11454. }
  11455. }
  11456. }
  11457. // Look for MUL_MAT + ADD + ADD
  11458. if (j > 0 &&
  11459. graph->nodes[j]->op == GGML_OP_ADD &&
  11460. graph->nodes[j-1]->op == GGML_OP_MUL_MAT) {
  11461. for (int k = j + 1; k < std::min(j + 15, graph->n_nodes); ++k) {
  11462. if (graph->nodes[k]->op == GGML_OP_ADD &&
  11463. graph->nodes[k]->src[0] == graph->nodes[j] &&
  11464. // src1 must either be weights or already processed
  11465. (graph->nodes[k]->src[1]->op == GGML_OP_NONE || used_node_set.find(graph->nodes[k]->src[1]) != used_node_set.end())) {
  11466. current_set.push_back(k);
  11467. used[k] = true;
  11468. break;
  11469. }
  11470. }
  11471. }
  11472. }
  11473. }
  11474. // Second pass grabs view nodes.
  11475. // Skip this if it would break a fusion optimization (don't split up add->rms_norm or add->add).
  11476. if (graph->nodes[current_set.back()]->op != GGML_OP_ADD) {
  11477. for (int j = first_unused+1; j < std::min(first_unused + NUM_TO_CHECK, graph->n_nodes); ++j) {
  11478. if (used[j]) {
  11479. continue;
  11480. }
  11481. if (!is_empty(graph->nodes[j])) {
  11482. continue;
  11483. }
  11484. bool ok = true;
  11485. for (int c = first_unused; c < j; ++c) {
  11486. bool c_in_current_set = std::find(current_set.begin(), current_set.end(), c) != current_set.end();
  11487. // skip views whose srcs haven't been processed.
  11488. if (!used[c] &&
  11489. is_src_of(graph->nodes[j], graph->nodes[c]) &&
  11490. !c_in_current_set) {
  11491. ok = false;
  11492. break;
  11493. }
  11494. }
  11495. if (ok) {
  11496. current_set.push_back(j);
  11497. }
  11498. }
  11499. }
  11500. // Push the current set into new_order
  11501. for (auto c : current_set) {
  11502. new_order.push_back(graph->nodes[c]);
  11503. used_node_set.insert(graph->nodes[c]);
  11504. used[c] = true;
  11505. }
  11506. while (first_unused < graph->n_nodes && used[first_unused]) {
  11507. first_unused++;
  11508. }
  11509. }
  11510. // Replace the graph with the new order.
  11511. for (int i = 0; i < graph->n_nodes; ++i) {
  11512. graph->nodes[i] = new_order[i];
  11513. }
  11514. }
  11515. // TODO: enable async and synchronize
  11516. static ggml_backend_i ggml_backend_vk_interface = {
  11517. /* .get_name = */ ggml_backend_vk_name,
  11518. /* .free = */ ggml_backend_vk_free,
  11519. /* .set_tensor_async = */ NULL, // ggml_backend_vk_set_tensor_async,
  11520. /* .get_tensor_async = */ ggml_backend_vk_get_tensor_async,
  11521. /* .cpy_tensor_async = */ NULL, // ggml_backend_vk_cpy_tensor_async,
  11522. /* .synchronize = */ ggml_backend_vk_synchronize,
  11523. /* .graph_plan_create = */ NULL,
  11524. /* .graph_plan_free = */ NULL,
  11525. /* .graph_plan_update = */ NULL,
  11526. /* .graph_plan_compute = */ NULL,
  11527. /* .graph_compute = */ ggml_backend_vk_graph_compute,
  11528. /* .event_record = */ NULL,
  11529. /* .event_wait = */ NULL,
  11530. /* .graph_optimize = */ ggml_vk_graph_optimize,
  11531. };
  11532. static ggml_guid_t ggml_backend_vk_guid() {
  11533. static ggml_guid guid = { 0xb8, 0xf7, 0x4f, 0x86, 0x40, 0x3c, 0xe1, 0x02, 0x91, 0xc8, 0xdd, 0xe9, 0x02, 0x3f, 0xc0, 0x2b };
  11534. return &guid;
  11535. }
  11536. ggml_backend_t ggml_backend_vk_init(size_t dev_num) {
  11537. VK_LOG_DEBUG("ggml_backend_vk_init(" << dev_num << ")");
  11538. ggml_backend_vk_context * ctx = new ggml_backend_vk_context;
  11539. ggml_vk_init(ctx, dev_num);
  11540. ggml_backend_t vk_backend = new ggml_backend {
  11541. /* .guid = */ ggml_backend_vk_guid(),
  11542. /* .iface = */ ggml_backend_vk_interface,
  11543. /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), dev_num),
  11544. /* .context = */ ctx,
  11545. };
  11546. return vk_backend;
  11547. }
  11548. bool ggml_backend_is_vk(ggml_backend_t backend) {
  11549. return backend != NULL && ggml_guid_matches(backend->guid, ggml_backend_vk_guid());
  11550. }
  11551. int ggml_backend_vk_get_device_count() {
  11552. return ggml_vk_get_device_count();
  11553. }
  11554. void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size) {
  11555. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11556. int dev_idx = vk_instance.device_indices[device];
  11557. ggml_vk_get_device_description(dev_idx, description, description_size);
  11558. }
  11559. void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total) {
  11560. GGML_ASSERT(device < (int) vk_instance.device_indices.size());
  11561. GGML_ASSERT(device < (int) vk_instance.device_supports_membudget.size());
  11562. vk::PhysicalDevice vkdev = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device]];
  11563. vk::PhysicalDeviceMemoryBudgetPropertiesEXT budgetprops;
  11564. vk::PhysicalDeviceMemoryProperties2 memprops = {};
  11565. const bool membudget_supported = vk_instance.device_supports_membudget[device];
  11566. const bool is_integrated_gpu = vkdev.getProperties().deviceType == vk::PhysicalDeviceType::eIntegratedGpu;
  11567. if (membudget_supported) {
  11568. memprops.pNext = &budgetprops;
  11569. }
  11570. vkdev.getMemoryProperties2(&memprops);
  11571. *total = 0;
  11572. *free = 0;
  11573. for (uint32_t i = 0; i < memprops.memoryProperties.memoryHeapCount; ++i) {
  11574. const vk::MemoryHeap & heap = memprops.memoryProperties.memoryHeaps[i];
  11575. if (is_integrated_gpu || (heap.flags & vk::MemoryHeapFlagBits::eDeviceLocal)) {
  11576. *total += heap.size;
  11577. if (membudget_supported && i < budgetprops.heapUsage.size()) {
  11578. *free += budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
  11579. } else {
  11580. *free += heap.size;
  11581. }
  11582. }
  11583. }
  11584. }
  11585. static vk::PhysicalDeviceType ggml_backend_vk_get_device_type(int device_idx) {
  11586. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11587. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11588. vk::PhysicalDeviceProperties2 props = {};
  11589. device.getProperties2(&props);
  11590. return props.properties.deviceType;
  11591. }
  11592. static std::string ggml_backend_vk_get_device_pci_id(int device_idx) {
  11593. GGML_ASSERT(device_idx >= 0 && device_idx < (int) vk_instance.device_indices.size());
  11594. vk::PhysicalDevice device = vk_instance.instance.enumeratePhysicalDevices()[vk_instance.device_indices[device_idx]];
  11595. const std::vector<vk::ExtensionProperties> ext_props = device.enumerateDeviceExtensionProperties();
  11596. bool ext_support = false;
  11597. for (const auto& properties : ext_props) {
  11598. if (strcmp("VK_EXT_pci_bus_info", properties.extensionName) == 0) {
  11599. ext_support = true;
  11600. break;
  11601. }
  11602. }
  11603. if (!ext_support) {
  11604. return "";
  11605. }
  11606. vk::PhysicalDeviceProperties2 props = {};
  11607. vk::PhysicalDevicePCIBusInfoPropertiesEXT pci_bus_info = {};
  11608. props.pNext = &pci_bus_info;
  11609. device.getProperties2(&props);
  11610. const uint32_t pci_domain = pci_bus_info.pciDomain;
  11611. const uint32_t pci_bus = pci_bus_info.pciBus;
  11612. const uint32_t pci_device = pci_bus_info.pciDevice;
  11613. const uint8_t pci_function = (uint8_t) pci_bus_info.pciFunction; // pci function is between 0 and 7, prevent printf overflow warning
  11614. char pci_bus_id[16] = {};
  11615. snprintf(pci_bus_id, sizeof(pci_bus_id), "%04x:%02x:%02x.%x", pci_domain, pci_bus, pci_device, pci_function);
  11616. return std::string(pci_bus_id);
  11617. }
  11618. //////////////////////////
  11619. struct ggml_backend_vk_device_context {
  11620. size_t device;
  11621. std::string name;
  11622. std::string description;
  11623. bool is_integrated_gpu;
  11624. std::string pci_bus_id;
  11625. };
  11626. static const char * ggml_backend_vk_device_get_name(ggml_backend_dev_t dev) {
  11627. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11628. return ctx->name.c_str();
  11629. }
  11630. static const char * ggml_backend_vk_device_get_description(ggml_backend_dev_t dev) {
  11631. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11632. return ctx->description.c_str();
  11633. }
  11634. static void ggml_backend_vk_device_get_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
  11635. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)device->context;
  11636. ggml_backend_vk_get_device_memory(ctx->device, free, total);
  11637. }
  11638. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_buffer_type(ggml_backend_dev_t dev) {
  11639. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11640. return ggml_backend_vk_buffer_type(ctx->device);
  11641. }
  11642. static ggml_backend_buffer_type_t ggml_backend_vk_device_get_host_buffer_type(ggml_backend_dev_t dev) {
  11643. UNUSED(dev);
  11644. return ggml_backend_vk_host_buffer_type();
  11645. }
  11646. static enum ggml_backend_dev_type ggml_backend_vk_device_get_type(ggml_backend_dev_t dev) {
  11647. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11648. return ctx->is_integrated_gpu ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
  11649. }
  11650. static void ggml_backend_vk_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) {
  11651. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11652. props->name = ggml_backend_vk_device_get_name(dev);
  11653. props->description = ggml_backend_vk_device_get_description(dev);
  11654. props->type = ggml_backend_vk_device_get_type(dev);
  11655. props->device_id = ctx->pci_bus_id.empty() ? nullptr : ctx->pci_bus_id.c_str();
  11656. ggml_backend_vk_device_get_memory(dev, &props->memory_free, &props->memory_total);
  11657. props->caps = {
  11658. /* .async = */ false,
  11659. /* .host_buffer = */ true,
  11660. /* .buffer_from_host_ptr = */ false,
  11661. /* .events = */ false,
  11662. };
  11663. }
  11664. static ggml_backend_t ggml_backend_vk_device_init(ggml_backend_dev_t dev, const char * params) {
  11665. UNUSED(params);
  11666. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11667. return ggml_backend_vk_init(ctx->device);
  11668. }
  11669. static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  11670. switch (op->op) {
  11671. case GGML_OP_UNARY:
  11672. switch (ggml_get_unary_op(op)) {
  11673. case GGML_UNARY_OP_EXP:
  11674. case GGML_UNARY_OP_GELU:
  11675. case GGML_UNARY_OP_GELU_ERF:
  11676. case GGML_UNARY_OP_GELU_QUICK:
  11677. case GGML_UNARY_OP_SILU:
  11678. case GGML_UNARY_OP_RELU:
  11679. case GGML_UNARY_OP_NEG:
  11680. case GGML_UNARY_OP_TANH:
  11681. case GGML_UNARY_OP_SIGMOID:
  11682. case GGML_UNARY_OP_HARDSIGMOID:
  11683. case GGML_UNARY_OP_HARDSWISH:
  11684. case GGML_UNARY_OP_ABS:
  11685. case GGML_UNARY_OP_SOFTPLUS:
  11686. case GGML_UNARY_OP_STEP:
  11687. case GGML_UNARY_OP_ROUND:
  11688. case GGML_UNARY_OP_CEIL:
  11689. case GGML_UNARY_OP_FLOOR:
  11690. case GGML_UNARY_OP_TRUNC:
  11691. return ggml_is_contiguous(op->src[0]) &&
  11692. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11693. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11694. (op->src[0]->type == op->type);
  11695. default:
  11696. return false;
  11697. }
  11698. case GGML_OP_GLU:
  11699. switch (ggml_get_glu_op(op)) {
  11700. case GGML_GLU_OP_GEGLU:
  11701. case GGML_GLU_OP_REGLU:
  11702. case GGML_GLU_OP_SWIGLU:
  11703. case GGML_GLU_OP_SWIGLU_OAI:
  11704. case GGML_GLU_OP_GEGLU_ERF:
  11705. case GGML_GLU_OP_GEGLU_QUICK:
  11706. return ggml_is_contiguous(op->src[0]) &&
  11707. (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11708. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) &&
  11709. (op->src[0]->type == op->type);
  11710. default:
  11711. return false;
  11712. }
  11713. case GGML_OP_MUL_MAT:
  11714. case GGML_OP_MUL_MAT_ID:
  11715. {
  11716. ggml_type src0_type = op->src[0]->type;
  11717. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11718. const vk_device& device = ggml_vk_get_device(ctx->device);
  11719. if (op->op == GGML_OP_MUL_MAT_ID) {
  11720. if (!device->mul_mat_id_s[src0_type] && !device->mul_mat_id_m[src0_type] && !device->mul_mat_id_l[src0_type]) {
  11721. // If there's not enough shared memory for row_ids and the result tile, fallback to CPU
  11722. return false;
  11723. }
  11724. }
  11725. switch (src0_type) {
  11726. case GGML_TYPE_F32:
  11727. case GGML_TYPE_F16:
  11728. case GGML_TYPE_BF16:
  11729. case GGML_TYPE_Q4_0:
  11730. case GGML_TYPE_Q4_1:
  11731. case GGML_TYPE_Q5_0:
  11732. case GGML_TYPE_Q5_1:
  11733. case GGML_TYPE_Q8_0:
  11734. case GGML_TYPE_Q2_K:
  11735. case GGML_TYPE_Q3_K:
  11736. case GGML_TYPE_Q4_K:
  11737. case GGML_TYPE_Q5_K:
  11738. case GGML_TYPE_Q6_K:
  11739. case GGML_TYPE_IQ1_S:
  11740. case GGML_TYPE_IQ1_M:
  11741. case GGML_TYPE_IQ2_XXS:
  11742. case GGML_TYPE_IQ2_XS:
  11743. case GGML_TYPE_IQ2_S:
  11744. case GGML_TYPE_IQ3_XXS:
  11745. case GGML_TYPE_IQ3_S:
  11746. case GGML_TYPE_IQ4_XS:
  11747. case GGML_TYPE_IQ4_NL:
  11748. case GGML_TYPE_MXFP4:
  11749. break;
  11750. default:
  11751. return false;
  11752. }
  11753. struct ggml_tensor * a;
  11754. struct ggml_tensor * b;
  11755. if (op->op == GGML_OP_MUL_MAT) {
  11756. a = op->src[0];
  11757. b = op->src[1];
  11758. } else {
  11759. a = op->src[2];
  11760. b = op->src[1];
  11761. }
  11762. if (a->ne[3] != b->ne[3]) {
  11763. return false;
  11764. }
  11765. 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) ||
  11766. !(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
  11767. return false;
  11768. }
  11769. if (op->src[0]->type == GGML_TYPE_BF16 && op->src[1]->type == GGML_TYPE_F16) {
  11770. // We currently don't have a bf16 x f16 shader, or an fp16->bf16 copy shader.
  11771. // So don't support this combination for now.
  11772. return false;
  11773. }
  11774. return true;
  11775. }
  11776. case GGML_OP_FLASH_ATTN_EXT:
  11777. {
  11778. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11779. auto device = ggml_vk_get_device(ctx->device);
  11780. bool coopmat2 = device->coopmat2;
  11781. uint32_t HSK = op->src[1]->ne[0];
  11782. uint32_t HSV = op->src[2]->ne[0];
  11783. if ((HSK % 8) != 0 || (HSV % 8) != 0) {
  11784. return false;
  11785. }
  11786. if (op->src[4] && op->src[4]->type != GGML_TYPE_F32) {
  11787. return false;
  11788. }
  11789. if (op->src[0]->type != GGML_TYPE_F32) {
  11790. return false;
  11791. }
  11792. if (op->type != GGML_TYPE_F32) {
  11793. return false;
  11794. }
  11795. if (op->src[3] && op->src[3]->type != GGML_TYPE_F16) {
  11796. return false;
  11797. }
  11798. // It's straightforward to support different K/V dequant, but would
  11799. // significantly increase the number of pipelines
  11800. if (op->src[1]->type != op->src[2]->type) {
  11801. return false;
  11802. }
  11803. switch (op->src[1]->type) {
  11804. case GGML_TYPE_F16:
  11805. case GGML_TYPE_F32:
  11806. case GGML_TYPE_Q4_0:
  11807. case GGML_TYPE_Q8_0:
  11808. // supported in scalar and coopmat2 paths
  11809. break;
  11810. case GGML_TYPE_Q4_1:
  11811. case GGML_TYPE_Q5_0:
  11812. case GGML_TYPE_Q5_1:
  11813. // K dequants currently disabled because D dimension is rounded up to 256 and runs inefficiently
  11814. //case GGML_TYPE_Q2_K:
  11815. //case GGML_TYPE_Q3_K:
  11816. //case GGML_TYPE_Q4_K:
  11817. //case GGML_TYPE_Q5_K:
  11818. //case GGML_TYPE_Q6_K:
  11819. //case GGML_TYPE_IQ1_S:
  11820. //case GGML_TYPE_IQ1_M:
  11821. //case GGML_TYPE_IQ2_XXS:
  11822. //case GGML_TYPE_IQ2_XS:
  11823. //case GGML_TYPE_IQ2_S:
  11824. //case GGML_TYPE_IQ3_XXS:
  11825. //case GGML_TYPE_IQ3_S:
  11826. //case GGML_TYPE_IQ4_XS:
  11827. case GGML_TYPE_IQ4_NL:
  11828. // currently supported only in coopmat2 path
  11829. if (!coopmat2) {
  11830. return false;
  11831. }
  11832. break;
  11833. default:
  11834. return false;
  11835. }
  11836. if (!coopmat2 && !(device->subgroup_shuffle && device->subgroup_vote)) {
  11837. // scalar/coopmat1 FA uses subgroupShuffle/subgroupAll
  11838. return false;
  11839. }
  11840. return true;
  11841. }
  11842. case GGML_OP_GET_ROWS:
  11843. {
  11844. switch (op->src[0]->type) {
  11845. case GGML_TYPE_F32:
  11846. case GGML_TYPE_F16:
  11847. case GGML_TYPE_BF16:
  11848. case GGML_TYPE_Q4_0:
  11849. case GGML_TYPE_Q4_1:
  11850. case GGML_TYPE_Q5_0:
  11851. case GGML_TYPE_Q5_1:
  11852. case GGML_TYPE_Q8_0:
  11853. case GGML_TYPE_Q2_K:
  11854. case GGML_TYPE_Q3_K:
  11855. case GGML_TYPE_Q4_K:
  11856. case GGML_TYPE_Q5_K:
  11857. case GGML_TYPE_Q6_K:
  11858. case GGML_TYPE_IQ1_S:
  11859. case GGML_TYPE_IQ1_M:
  11860. case GGML_TYPE_IQ2_XXS:
  11861. case GGML_TYPE_IQ2_XS:
  11862. case GGML_TYPE_IQ2_S:
  11863. case GGML_TYPE_IQ3_XXS:
  11864. case GGML_TYPE_IQ3_S:
  11865. case GGML_TYPE_IQ4_XS:
  11866. case GGML_TYPE_IQ4_NL:
  11867. case GGML_TYPE_MXFP4:
  11868. return true;
  11869. default:
  11870. return false;
  11871. }
  11872. }
  11873. case GGML_OP_SET_ROWS:
  11874. {
  11875. switch (op->type) {
  11876. case GGML_TYPE_F32:
  11877. case GGML_TYPE_F16:
  11878. case GGML_TYPE_BF16:
  11879. case GGML_TYPE_Q4_0:
  11880. case GGML_TYPE_Q4_1:
  11881. case GGML_TYPE_Q5_0:
  11882. case GGML_TYPE_Q5_1:
  11883. case GGML_TYPE_Q8_0:
  11884. case GGML_TYPE_IQ4_NL:
  11885. return true;
  11886. default:
  11887. return false;
  11888. }
  11889. }
  11890. case GGML_OP_CONT:
  11891. case GGML_OP_CPY:
  11892. case GGML_OP_DUP:
  11893. {
  11894. ggml_type src0_type = op->src[0]->type;
  11895. ggml_type src1_type = op->src[1] != nullptr ? op->src[1]->type : src0_type;
  11896. if (src0_type == GGML_TYPE_F32) {
  11897. switch (src1_type) {
  11898. case GGML_TYPE_F32:
  11899. case GGML_TYPE_F16:
  11900. case GGML_TYPE_BF16:
  11901. case GGML_TYPE_Q4_0:
  11902. case GGML_TYPE_Q4_1:
  11903. case GGML_TYPE_Q5_0:
  11904. case GGML_TYPE_Q5_1:
  11905. case GGML_TYPE_Q8_0:
  11906. case GGML_TYPE_IQ4_NL:
  11907. return true;
  11908. default:
  11909. break;
  11910. }
  11911. }
  11912. if (src1_type == GGML_TYPE_F32) {
  11913. switch (src0_type) {
  11914. case GGML_TYPE_F16:
  11915. case GGML_TYPE_Q4_0:
  11916. case GGML_TYPE_Q4_1:
  11917. case GGML_TYPE_Q5_0:
  11918. case GGML_TYPE_Q5_1:
  11919. case GGML_TYPE_Q8_0:
  11920. case GGML_TYPE_IQ4_NL:
  11921. return true;
  11922. default:
  11923. break;
  11924. }
  11925. }
  11926. if (src0_type == GGML_TYPE_F16 && src1_type == GGML_TYPE_F16) {
  11927. return true;
  11928. }
  11929. if (
  11930. (src0_type == GGML_TYPE_F32 && src1_type == GGML_TYPE_I32) ||
  11931. (src0_type == GGML_TYPE_I32 && src1_type == GGML_TYPE_F32)
  11932. ) {
  11933. return true;
  11934. }
  11935. // We can handle copying from a type to the same type if it's
  11936. // either not quantized or is quantized and contiguous.
  11937. // We use f16 or f32 shaders to do the copy,
  11938. // so the type/block size must be a multiple of 4.
  11939. if (src0_type == src1_type &&
  11940. (!ggml_is_quantized(src0_type) || (ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op))) &&
  11941. (ggml_type_size(src0_type) % 2) == 0) {
  11942. return true;
  11943. }
  11944. return false;
  11945. }
  11946. case GGML_OP_REPEAT:
  11947. return ggml_type_size(op->type) == sizeof(float) && ggml_type_size(op->src[0]->type) == sizeof(float);
  11948. case GGML_OP_REPEAT_BACK:
  11949. return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32;
  11950. case GGML_OP_ROPE:
  11951. case GGML_OP_ROPE_BACK:
  11952. case GGML_OP_NONE:
  11953. case GGML_OP_RESHAPE:
  11954. case GGML_OP_VIEW:
  11955. case GGML_OP_PERMUTE:
  11956. case GGML_OP_TRANSPOSE:
  11957. case GGML_OP_RMS_NORM:
  11958. return true;
  11959. case GGML_OP_NORM:
  11960. case GGML_OP_GROUP_NORM:
  11961. case GGML_OP_L2_NORM:
  11962. return ggml_is_contiguous(op->src[0]);
  11963. case GGML_OP_ADD:
  11964. case GGML_OP_SUB:
  11965. case GGML_OP_MUL:
  11966. case GGML_OP_DIV:
  11967. return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  11968. (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) &&
  11969. (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
  11970. case GGML_OP_ADD_ID:
  11971. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 &&
  11972. op->type == GGML_TYPE_F32;
  11973. case GGML_OP_SILU_BACK:
  11974. case GGML_OP_RMS_NORM_BACK:
  11975. case GGML_OP_SQR:
  11976. case GGML_OP_SQRT:
  11977. case GGML_OP_SIN:
  11978. case GGML_OP_COS:
  11979. case GGML_OP_CLAMP:
  11980. case GGML_OP_LEAKY_RELU:
  11981. case GGML_OP_OPT_STEP_ADAMW:
  11982. case GGML_OP_OPT_STEP_SGD:
  11983. return op->src[0]->type == GGML_TYPE_F32;
  11984. case GGML_OP_LOG:
  11985. return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16;
  11986. case GGML_OP_ARGSORT:
  11987. {
  11988. if (!ggml_is_contiguous(op) || !ggml_is_contiguous(op->src[0])) {
  11989. return false;
  11990. }
  11991. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  11992. auto device = ggml_vk_get_device(ctx->device);
  11993. // pipeline_argsort_large_f32 requires vulkan memory model.
  11994. if (device->vulkan_memory_model) {
  11995. return true;
  11996. } else {
  11997. return op->ne[0] <= (1 << device->max_workgroup_size_log2);
  11998. }
  11999. }
  12000. case GGML_OP_UPSCALE:
  12001. case GGML_OP_ACC:
  12002. case GGML_OP_CONCAT:
  12003. case GGML_OP_ADD1:
  12004. case GGML_OP_ARANGE:
  12005. case GGML_OP_FILL:
  12006. case GGML_OP_SCALE:
  12007. case GGML_OP_PAD:
  12008. case GGML_OP_ROLL:
  12009. case GGML_OP_DIAG_MASK_INF:
  12010. case GGML_OP_SOFT_MAX:
  12011. case GGML_OP_SOFT_MAX_BACK:
  12012. return true;
  12013. case GGML_OP_SUM:
  12014. case GGML_OP_SUM_ROWS:
  12015. case GGML_OP_MEAN:
  12016. return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[0]);
  12017. case GGML_OP_ARGMAX:
  12018. case GGML_OP_COUNT_EQUAL:
  12019. case GGML_OP_IM2COL:
  12020. case GGML_OP_IM2COL_3D:
  12021. case GGML_OP_TIMESTEP_EMBEDDING:
  12022. case GGML_OP_CONV_2D_DW:
  12023. case GGML_OP_POOL_2D:
  12024. case GGML_OP_RWKV_WKV6:
  12025. case GGML_OP_RWKV_WKV7:
  12026. return true;
  12027. case GGML_OP_SSM_SCAN:
  12028. {
  12029. for (int i = 0; i < 6; i++) {
  12030. if (op->src[i] && ggml_is_quantized(op->src[i]->type)) {
  12031. return false;
  12032. }
  12033. }
  12034. if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) {
  12035. return false;
  12036. }
  12037. if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
  12038. return false;
  12039. }
  12040. const uint32_t d_state = op->src[0]->ne[0];
  12041. const uint32_t head_dim = op->src[0]->ne[1];
  12042. bool is_mamba2 = (op->src[3] && op->src[3]->nb[1] == sizeof(float));
  12043. if (!is_mamba2) {
  12044. return false;
  12045. }
  12046. if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) {
  12047. return false;
  12048. }
  12049. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12050. const vk_device& device = ggml_vk_get_device(ctx->device);
  12051. const uint32_t SPLIT_H = 16;
  12052. size_t stateC_size = SPLIT_H * d_state * sizeof(float);
  12053. if (stateC_size > device->properties.limits.maxComputeSharedMemorySize) {
  12054. return false;
  12055. }
  12056. return true;
  12057. }
  12058. case GGML_OP_SSM_CONV:
  12059. return true;
  12060. case GGML_OP_CONV_TRANSPOSE_1D:
  12061. return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32;
  12062. case GGML_OP_CONV_2D:
  12063. case GGML_OP_CONV_TRANSPOSE_2D:
  12064. {
  12065. // Op is disabled for Apple because it segfaults at pipeline create time on MoltenVK
  12066. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12067. const vk_device& device = ggml_vk_get_device(ctx->device);
  12068. if (op->op == GGML_OP_CONV_TRANSPOSE_2D &&
  12069. device->properties.limits.maxPushConstantsSize < sizeof(vk_op_conv_transpose_2d_push_constants)) {
  12070. return false;
  12071. }
  12072. // Channel-contiguous format is not supported yet.
  12073. return ((op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) &&
  12074. op->src[1]->type == GGML_TYPE_F32 &&
  12075. op->type == GGML_TYPE_F32 &&
  12076. ggml_is_contiguous(op->src[0]) &&
  12077. ggml_is_contiguous(op->src[1]) &&
  12078. ggml_is_contiguous(op));
  12079. }
  12080. default:
  12081. return false;
  12082. }
  12083. UNUSED(dev);
  12084. }
  12085. static bool ggml_backend_vk_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
  12086. if (buft->iface.get_name != ggml_backend_vk_buffer_type_name) {
  12087. return false;
  12088. }
  12089. ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
  12090. ggml_backend_vk_buffer_type_context * buft_ctx = (ggml_backend_vk_buffer_type_context *)buft->context;
  12091. return buft_ctx->device->idx == ctx->device;
  12092. }
  12093. static bool ggml_backend_vk_device_offload_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
  12094. const int min_batch_size = 32;
  12095. return (op->ne[1] >= min_batch_size && op->op != GGML_OP_GET_ROWS) ||
  12096. (op->ne[2] >= min_batch_size && op->op == GGML_OP_MUL_MAT_ID);
  12097. UNUSED(dev);
  12098. }
  12099. static const struct ggml_backend_device_i ggml_backend_vk_device_i = {
  12100. /* .get_name = */ ggml_backend_vk_device_get_name,
  12101. /* .get_description = */ ggml_backend_vk_device_get_description,
  12102. /* .get_memory = */ ggml_backend_vk_device_get_memory,
  12103. /* .get_type = */ ggml_backend_vk_device_get_type,
  12104. /* .get_props = */ ggml_backend_vk_device_get_props,
  12105. /* .init_backend = */ ggml_backend_vk_device_init,
  12106. /* .get_buffer_type = */ ggml_backend_vk_device_get_buffer_type,
  12107. /* .get_host_buffer_type = */ ggml_backend_vk_device_get_host_buffer_type,
  12108. /* .buffer_from_host_ptr = */ NULL,
  12109. /* .supports_op = */ ggml_backend_vk_device_supports_op,
  12110. /* .supports_buft = */ ggml_backend_vk_device_supports_buft,
  12111. /* .offload_op = */ ggml_backend_vk_device_offload_op,
  12112. /* .event_new = */ NULL,
  12113. /* .event_free = */ NULL,
  12114. /* .event_synchronize = */ NULL,
  12115. };
  12116. static const char * ggml_backend_vk_reg_get_name(ggml_backend_reg_t reg) {
  12117. UNUSED(reg);
  12118. return GGML_VK_NAME;
  12119. }
  12120. static size_t ggml_backend_vk_reg_get_device_count(ggml_backend_reg_t reg) {
  12121. UNUSED(reg);
  12122. return ggml_backend_vk_get_device_count();
  12123. }
  12124. static ggml_backend_dev_t ggml_backend_vk_reg_get_device(ggml_backend_reg_t reg, size_t device) {
  12125. static std::vector<ggml_backend_dev_t> devices;
  12126. static bool initialized = false;
  12127. {
  12128. static std::mutex mutex;
  12129. std::lock_guard<std::mutex> lock(mutex);
  12130. if (!initialized) {
  12131. for (int i = 0; i < ggml_backend_vk_get_device_count(); i++) {
  12132. ggml_backend_vk_device_context * ctx = new ggml_backend_vk_device_context;
  12133. char desc[256];
  12134. ggml_backend_vk_get_device_description(i, desc, sizeof(desc));
  12135. ctx->device = i;
  12136. ctx->name = GGML_VK_NAME + std::to_string(i);
  12137. ctx->description = desc;
  12138. ctx->is_integrated_gpu = ggml_backend_vk_get_device_type(i) == vk::PhysicalDeviceType::eIntegratedGpu;
  12139. ctx->pci_bus_id = ggml_backend_vk_get_device_pci_id(i);
  12140. devices.push_back(new ggml_backend_device {
  12141. /* .iface = */ ggml_backend_vk_device_i,
  12142. /* .reg = */ reg,
  12143. /* .context = */ ctx,
  12144. });
  12145. }
  12146. initialized = true;
  12147. }
  12148. }
  12149. GGML_ASSERT(device < devices.size());
  12150. return devices[device];
  12151. }
  12152. static const struct ggml_backend_reg_i ggml_backend_vk_reg_i = {
  12153. /* .get_name = */ ggml_backend_vk_reg_get_name,
  12154. /* .get_device_count = */ ggml_backend_vk_reg_get_device_count,
  12155. /* .get_device = */ ggml_backend_vk_reg_get_device,
  12156. /* .get_proc_address = */ NULL,
  12157. };
  12158. ggml_backend_reg_t ggml_backend_vk_reg() {
  12159. static ggml_backend_reg reg = {
  12160. /* .api_version = */ GGML_BACKEND_API_VERSION,
  12161. /* .iface = */ ggml_backend_vk_reg_i,
  12162. /* .context = */ nullptr,
  12163. };
  12164. try {
  12165. ggml_vk_instance_init();
  12166. return &reg;
  12167. } catch (const vk::SystemError& e) {
  12168. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: System error: " << e.what());
  12169. return nullptr;
  12170. } catch (const std::exception &e) {
  12171. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: " << e.what());
  12172. return nullptr;
  12173. } catch (...) {
  12174. VK_LOG_DEBUG("ggml_backend_vk_reg() -> Error: unknown exception during Vulkan init");
  12175. return nullptr;
  12176. }
  12177. }
  12178. // Extension availability
  12179. static bool ggml_vk_instance_validation_ext_available() {
  12180. #ifdef GGML_VULKAN_VALIDATE
  12181. // Check if validation layer provides the extension
  12182. const std::string layer_name = "VK_LAYER_KHRONOS_validation";
  12183. for (const auto& layer : vk::enumerateInstanceLayerProperties()) {
  12184. if (layer_name == layer.layerName.data()) {
  12185. for (const auto& ext : vk::enumerateInstanceExtensionProperties(layer_name)) {
  12186. if (strcmp("VK_EXT_validation_features", ext.extensionName.data()) == 0) {
  12187. return true;
  12188. }
  12189. }
  12190. }
  12191. }
  12192. std::cerr << "ggml_vulkan: WARNING: Validation layer or layer extension VK_EXT_validation_features not found." << std::endl;
  12193. #endif
  12194. return false;
  12195. }
  12196. static bool ggml_vk_instance_portability_enumeration_ext_available(const std::vector<vk::ExtensionProperties>& instance_extensions) {
  12197. #ifdef __APPLE__
  12198. // Check for portability enumeration extension for MoltenVK support
  12199. for (const auto& properties : instance_extensions) {
  12200. if (strcmp("VK_KHR_portability_enumeration", properties.extensionName) == 0) {
  12201. return true;
  12202. }
  12203. }
  12204. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_KHR_portability_enumeration not found." << std::endl;
  12205. #endif
  12206. return false;
  12207. UNUSED(instance_extensions);
  12208. }
  12209. // Extension availability
  12210. static bool ggml_vk_instance_debug_utils_ext_available(
  12211. const std::vector<vk::ExtensionProperties> & instance_extensions) {
  12212. // Check for portability enumeration extension for MoltenVK support
  12213. for (const auto & properties : instance_extensions) {
  12214. if (strcmp("VK_EXT_debug_utils", properties.extensionName) == 0) {
  12215. return true;
  12216. }
  12217. }
  12218. std::cerr << "ggml_vulkan: WARNING: Instance extension VK_EXT_debug_utils not found." << std::endl;
  12219. return false;
  12220. UNUSED(instance_extensions);
  12221. }
  12222. static bool ggml_vk_device_is_supported(const vk::PhysicalDevice & vkdev) {
  12223. VkPhysicalDeviceFeatures2 device_features2;
  12224. device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
  12225. VkPhysicalDeviceVulkan11Features vk11_features;
  12226. vk11_features.pNext = nullptr;
  12227. vk11_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
  12228. device_features2.pNext = &vk11_features;
  12229. vkGetPhysicalDeviceFeatures2(vkdev, &device_features2);
  12230. return vk11_features.storageBuffer16BitAccess;
  12231. }
  12232. static bool ggml_vk_khr_cooperative_matrix_support(const vk::PhysicalDeviceProperties& props, const vk::PhysicalDeviceDriverProperties& driver_props, vk_device_architecture arch) {
  12233. switch (props.vendorID) {
  12234. case VK_VENDOR_ID_INTEL:
  12235. // Only allowing Xe2 GPU at the moment since Xe2 GPU can gain significant performance boost,
  12236. // while some older hardware (ex. Arc A770) has performance regressions
  12237. return arch == vk_device_architecture::INTEL_XE2;
  12238. case VK_VENDOR_ID_AMD:
  12239. if (driver_props.driverID == vk::DriverId::eAmdProprietary || driver_props.driverID == vk::DriverId::eAmdOpenSource) {
  12240. // Workaround for AMD proprietary driver reporting support on all GPUs
  12241. return arch == vk_device_architecture::AMD_RDNA3;
  12242. }
  12243. return true;
  12244. default:
  12245. return true;
  12246. }
  12247. }
  12248. // checks
  12249. #ifdef GGML_VULKAN_CHECK_RESULTS
  12250. static void ggml_vk_print_graph_origin(const ggml_tensor * tensor, std::vector<const ggml_tensor *>& done, int level = 0) {
  12251. if (std::find(done.begin(), done.end(), tensor) != done.end() || level > 10) {
  12252. return;
  12253. }
  12254. for (int j = 0; j < level; j++) {
  12255. std::cerr << " ";
  12256. }
  12257. std::cerr << ggml_op_name(tensor->op) << " gpu=" << (tensor->extra != nullptr) << std::endl;
  12258. done.push_back(tensor);
  12259. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12260. if (tensor->src[i] != nullptr) {
  12261. ggml_vk_print_graph_origin(tensor->src[i], done, level + 1);
  12262. }
  12263. }
  12264. }
  12265. static void ggml_vk_print_tensor_area(const ggml_tensor * tensor, const void * data, int i0, int i1, int i2, int i3) {
  12266. if (tensor->type != GGML_TYPE_F32 && tensor->type != GGML_TYPE_F16 && tensor->type != GGML_TYPE_I32) {
  12267. return;
  12268. }
  12269. i0 = std::max(i0, 5);
  12270. i1 = std::max(i1, 5);
  12271. i2 = std::max(i2, 0);
  12272. i3 = std::max(i3, 0);
  12273. fprintf(stderr, " ");
  12274. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12275. fprintf(stderr, "%7d ", idx1);
  12276. }
  12277. fprintf(stderr, "\n");
  12278. for (int idx0 = i0 - 5; idx0 < i0 + 5; idx0++) {
  12279. fprintf(stderr, "%7d: ", idx0);
  12280. for (int idx1 = i1 - 5; idx1 < i1 + 5; idx1++) {
  12281. 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]) {
  12282. float val;
  12283. if (tensor->type == GGML_TYPE_F32) {
  12284. val = *(const float *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12285. } else if (tensor->type == GGML_TYPE_F16) {
  12286. 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]));
  12287. } else if (tensor->type == GGML_TYPE_I32) {
  12288. val = *(const int32_t *) ((const char *) data + i3*tensor->nb[3] + i2*tensor->nb[2] + idx1*tensor->nb[1] + idx0*tensor->nb[0]);
  12289. } else {
  12290. GGML_ABORT("fatal error");
  12291. }
  12292. fprintf(stderr, "% 7.2f ", val);
  12293. } else {
  12294. fprintf(stderr, " ");
  12295. }
  12296. }
  12297. fprintf(stderr, "\n");
  12298. }
  12299. }
  12300. static void ggml_vk_print_tensor(const ggml_tensor * tensor, const char * name) {
  12301. void * tensor_data = tensor->data;
  12302. const bool is_gpu = tensor->buffer != nullptr && ggml_backend_buffer_is_vk(tensor->buffer);
  12303. if (is_gpu) {
  12304. const size_t tensor_size = ggml_nbytes(tensor);
  12305. tensor_data = malloc(tensor_size);
  12306. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12307. vk_buffer buffer_gpu = buf_ctx->dev_buffer;
  12308. ggml_vk_buffer_read(buffer_gpu, vk_tensor_offset(tensor) + tensor->view_offs, tensor_data, tensor_size);
  12309. }
  12310. std::cerr << "TENSOR CHECK " << name << " (" << tensor->name << "): " << ggml_op_name(tensor->op) << std::endl;
  12311. 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;
  12312. if (tensor->src[0] != nullptr) {
  12313. 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;
  12314. }
  12315. if (tensor->src[1] != nullptr) {
  12316. 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;
  12317. }
  12318. std::cerr << std::endl << "Result:" << std::endl;
  12319. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  12320. std::cerr << std::endl;
  12321. std::vector<const ggml_tensor *> done;
  12322. ggml_vk_print_graph_origin(tensor, done);
  12323. if (is_gpu) {
  12324. free(tensor_data);
  12325. }
  12326. }
  12327. void * comp_result;
  12328. size_t comp_size;
  12329. size_t comp_nb[GGML_MAX_DIMS];
  12330. size_t check_counter = 0;
  12331. static void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12332. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  12333. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12334. return;
  12335. }
  12336. check_counter++;
  12337. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12338. return;
  12339. }
  12340. VK_LOG_DEBUG("ggml_vk_check_results_0(" << tensor->name << ")");
  12341. struct ggml_init_params iparams = {
  12342. /*.mem_size =*/ 2ul*1024ul*1024ul*1024ul,
  12343. /*.mem_buffer =*/ NULL,
  12344. /*.no_alloc =*/ false,
  12345. };
  12346. struct ggml_context * ggml_ctx = ggml_init(iparams);
  12347. std::array<struct ggml_tensor *, GGML_MAX_SRC> src_clone = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
  12348. const char * srci_name[GGML_MAX_SRC] = {"src0", "src1", "src2", "src3", "src4", "src5", "src6", "src7", "src8", "src9"};
  12349. std::map<ggml_tensor *, ggml_tensor *> cloned_tensors;
  12350. std::vector<void *> cloned_mallocs;
  12351. struct ggml_tensor * tensor_clone = nullptr;
  12352. for (int f = 0; f < ctx->num_additional_fused_ops + 1; ++f) {
  12353. tensor = cgraph->nodes[tensor_idx + f];
  12354. for (int i = 0; i < GGML_MAX_SRC; i++) {
  12355. ggml_tensor * srci = tensor->src[i];
  12356. if (srci == nullptr) {
  12357. continue;
  12358. }
  12359. // If a src tensor has been cloned, use that one
  12360. auto it = cloned_tensors.find(srci);
  12361. if (it != cloned_tensors.end()) {
  12362. src_clone[i] = it->second;
  12363. continue;
  12364. }
  12365. ggml_tensor * srci_clone = ggml_dup_tensor(ggml_ctx, srci);
  12366. size_t srci_size = ggml_nbytes(srci);
  12367. src_clone[i] = srci_clone;
  12368. void *src_buffer = malloc(srci_size);
  12369. cloned_mallocs.push_back(src_buffer);
  12370. srci_clone->data = src_buffer;
  12371. if (ggml_backend_buffer_is_host(srci->buffer)) {
  12372. memcpy(srci_clone->data, srci->data, srci_size);
  12373. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12374. } else if (ggml_backend_buffer_is_vk(srci->buffer)) {
  12375. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)srci->buffer->context;
  12376. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12377. uint64_t offset = vk_tensor_offset(srci) + srci->view_offs;
  12378. if (!ggml_is_contiguous(srci) && ggml_vk_dim01_contiguous(srci)) {
  12379. for (int i3 = 0; i3 < srci->ne[3]; i3++) {
  12380. for (int i2 = 0; i2 < srci->ne[2]; i2++) {
  12381. const int idx = i3*srci->ne[2] + i2;
  12382. 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]);
  12383. }
  12384. }
  12385. srci_clone->nb[0] = srci->nb[0];
  12386. srci_clone->nb[1] = srci->nb[1];
  12387. for (int i = 2; i < GGML_MAX_DIMS; i++) {
  12388. srci_clone->nb[i] = srci_clone->nb[i - 1]*srci_clone->ne[i - 1];
  12389. }
  12390. } else {
  12391. if (offset + srci_size >= buffer_gpu->size) {
  12392. srci_size = buffer_gpu->size - offset;
  12393. }
  12394. ggml_vk_buffer_read(buffer_gpu, offset, srci_clone->data, srci_size);
  12395. memcpy(srci_clone->nb, srci->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12396. }
  12397. } else {
  12398. GGML_ABORT("fatal error");
  12399. }
  12400. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12401. ggml_vk_print_tensor(srci, srci_name[i]);
  12402. }
  12403. }
  12404. if (tensor->op == GGML_OP_FLASH_ATTN_EXT) {
  12405. const float * params = (const float *)tensor->op_params;
  12406. 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]);
  12407. if (src_clone[4]) {
  12408. ggml_flash_attn_ext_add_sinks(tensor_clone, src_clone[4]);
  12409. }
  12410. } else if (tensor->op == GGML_OP_MUL_MAT) {
  12411. tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
  12412. } else if (tensor->op == GGML_OP_MUL_MAT_ID) {
  12413. tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12414. } else if (tensor->op == GGML_OP_SUB) {
  12415. tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
  12416. } else if (tensor->op == GGML_OP_MUL) {
  12417. tensor_clone = ggml_mul(ggml_ctx, src_clone[0], src_clone[1]);
  12418. } else if (tensor->op == GGML_OP_DIV) {
  12419. tensor_clone = ggml_div(ggml_ctx, src_clone[0], src_clone[1]);
  12420. } else if (tensor->op == GGML_OP_CONCAT) {
  12421. tensor_clone = ggml_concat(ggml_ctx, src_clone[0], src_clone[1], *(int *)tensor->op_params);
  12422. } else if (tensor->op == GGML_OP_UPSCALE) {
  12423. tensor_clone = ggml_interpolate(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3], (ggml_scale_mode) tensor->op_params[0]);
  12424. } else if (tensor->op == GGML_OP_SCALE) {
  12425. const float * params = (const float *)tensor->op_params;
  12426. tensor_clone = ggml_scale_bias(ggml_ctx, src_clone[0], params[0], params[1]);
  12427. } else if (tensor->op == GGML_OP_ADD1) {
  12428. tensor_clone = ggml_add1(ggml_ctx, src_clone[0], src_clone[1]);
  12429. } else if (tensor->op == GGML_OP_ARANGE) {
  12430. const float start = ggml_get_op_params_f32(tensor, 0);
  12431. const float stop = ggml_get_op_params_f32(tensor, 1);
  12432. const float step = ggml_get_op_params_f32(tensor, 2);
  12433. tensor_clone = ggml_arange(ggml_ctx, start, stop, step);
  12434. } else if (tensor->op == GGML_OP_FILL) {
  12435. const float value = ggml_get_op_params_f32(tensor, 0);
  12436. tensor_clone = ggml_fill(ggml_ctx, tensor_clone, value);
  12437. } else if (tensor->op == GGML_OP_SQR) {
  12438. tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]);
  12439. } else if (tensor->op == GGML_OP_SQRT) {
  12440. tensor_clone = ggml_sqrt(ggml_ctx, src_clone[0]);
  12441. } else if (tensor->op == GGML_OP_SIN) {
  12442. tensor_clone = ggml_sin(ggml_ctx, src_clone[0]);
  12443. } else if (tensor->op == GGML_OP_COS) {
  12444. tensor_clone = ggml_cos(ggml_ctx, src_clone[0]);
  12445. } else if (tensor->op == GGML_OP_LOG) {
  12446. tensor_clone = ggml_log(ggml_ctx, src_clone[0]);
  12447. } else if (tensor->op == GGML_OP_CLAMP) {
  12448. const float * params = (const float *)tensor->op_params;
  12449. tensor_clone = ggml_clamp(ggml_ctx, src_clone[0], params[0], params[1]);
  12450. } else if (tensor->op == GGML_OP_PAD) {
  12451. tensor_clone = ggml_pad_ext(ggml_ctx, src_clone[0], tensor->op_params[0], tensor->op_params[1], tensor->op_params[2], tensor->op_params[3],
  12452. tensor->op_params[4], tensor->op_params[5], tensor->op_params[6], tensor->op_params[7]);
  12453. } else if (tensor->op == GGML_OP_REPEAT) {
  12454. tensor_clone = ggml_repeat(ggml_ctx, src_clone[0], tensor);
  12455. } else if (tensor->op == GGML_OP_REPEAT_BACK) {
  12456. tensor_clone = ggml_repeat_back(ggml_ctx, src_clone[0], tensor);
  12457. } else if (tensor->op == GGML_OP_ADD) {
  12458. tensor_clone = ggml_add(ggml_ctx, src_clone[0], src_clone[1]);
  12459. } else if (tensor->op == GGML_OP_ACC) {
  12460. 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]);
  12461. } else if (tensor->op == GGML_OP_NORM) {
  12462. tensor_clone = ggml_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12463. } else if (tensor->op == GGML_OP_GROUP_NORM) {
  12464. const float * float_params = (const float *)tensor->op_params;
  12465. tensor_clone = ggml_group_norm(ggml_ctx, src_clone[0], tensor->op_params[0], float_params[1]);
  12466. } else if (tensor->op == GGML_OP_RMS_NORM) {
  12467. tensor_clone = ggml_rms_norm(ggml_ctx, src_clone[0], *(float *)tensor->op_params);
  12468. } else if (tensor->op == GGML_OP_RMS_NORM_BACK) {
  12469. const float eps = ((float *) tensor->op_params)[0];
  12470. tensor_clone = ggml_rms_norm_back(ggml_ctx, src_clone[0], src_clone[1], eps);
  12471. } else if (tensor->op == GGML_OP_SILU_BACK) {
  12472. tensor_clone = ggml_silu_back(ggml_ctx, src_clone[0], src_clone[1]);
  12473. } else if (tensor->op == GGML_OP_L2_NORM) {
  12474. const float eps = ((float *) tensor->op_params)[0];
  12475. tensor_clone = ggml_l2_norm(ggml_ctx, src_clone[0], eps);
  12476. } else if (tensor->op == GGML_OP_SOFT_MAX) {
  12477. if (tensor->src[1] != nullptr) {
  12478. const float * params = (const float *)tensor->op_params;
  12479. tensor_clone = ggml_soft_max_ext(ggml_ctx, src_clone[0], src_clone[1], params[0], params[1]);
  12480. } else {
  12481. tensor_clone = ggml_soft_max(ggml_ctx, src_clone[0]);
  12482. }
  12483. } else if (tensor->op == GGML_OP_SOFT_MAX_BACK) {
  12484. 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]);
  12485. } else if (tensor->op == GGML_OP_DIAG_MASK_INF) {
  12486. tensor_clone = ggml_diag_mask_inf(ggml_ctx, src_clone[0], tensor->op_params[0]);
  12487. } else if (tensor->op == GGML_OP_ROPE || tensor->op == GGML_OP_ROPE_BACK) {
  12488. const int n_dims = ((int32_t *) tensor->op_params)[1];
  12489. const int mode = ((int32_t *) tensor->op_params)[2];
  12490. //const int n_ctx_ggml = ((int32_t *) tensor->op_params)[3];
  12491. const int n_ctx_orig_ggml = ((int32_t *) tensor->op_params)[4];
  12492. const float freq_base = ((float *) tensor->op_params)[5];
  12493. const float freq_scale = ((float *) tensor->op_params)[6];
  12494. const float ext_factor = ((float *) tensor->op_params)[7];
  12495. const float attn_factor = ((float *) tensor->op_params)[8];
  12496. const float beta_fast = ((float *) tensor->op_params)[9];
  12497. const float beta_slow = ((float *) tensor->op_params)[10];
  12498. if (mode & GGML_ROPE_TYPE_MROPE) {
  12499. int32_t *sections = ((int32_t *) tensor->op_params) + 11;
  12500. if (tensor->op == GGML_OP_ROPE) {
  12501. 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);
  12502. } else {
  12503. 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);
  12504. }
  12505. } else {
  12506. if (tensor->op == GGML_OP_ROPE) {
  12507. 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);
  12508. } else {
  12509. 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);
  12510. }
  12511. }
  12512. } else if (tensor->op == GGML_OP_UNARY) {
  12513. switch (ggml_get_unary_op(tensor)) {
  12514. case GGML_UNARY_OP_EXP:
  12515. tensor_clone = ggml_exp(ggml_ctx, src_clone[0]);
  12516. break;
  12517. case GGML_UNARY_OP_SILU:
  12518. tensor_clone = ggml_silu(ggml_ctx, src_clone[0]);
  12519. break;
  12520. case GGML_UNARY_OP_GELU:
  12521. tensor_clone = ggml_gelu(ggml_ctx, src_clone[0]);
  12522. break;
  12523. case GGML_UNARY_OP_GELU_ERF:
  12524. tensor_clone = ggml_gelu_erf(ggml_ctx, src_clone[0]);
  12525. break;
  12526. case GGML_UNARY_OP_GELU_QUICK:
  12527. tensor_clone = ggml_gelu_quick(ggml_ctx, src_clone[0]);
  12528. break;
  12529. case GGML_UNARY_OP_RELU:
  12530. tensor_clone = ggml_relu(ggml_ctx, src_clone[0]);
  12531. break;
  12532. case GGML_UNARY_OP_NEG:
  12533. tensor_clone = ggml_neg(ggml_ctx, src_clone[0]);
  12534. break;
  12535. case GGML_UNARY_OP_TANH:
  12536. tensor_clone = ggml_tanh(ggml_ctx, src_clone[0]);
  12537. break;
  12538. case GGML_UNARY_OP_SIGMOID:
  12539. tensor_clone = ggml_sigmoid(ggml_ctx, src_clone[0]);
  12540. break;
  12541. case GGML_UNARY_OP_HARDSIGMOID:
  12542. tensor_clone = ggml_hardsigmoid(ggml_ctx, src_clone[0]);
  12543. break;
  12544. case GGML_UNARY_OP_HARDSWISH:
  12545. tensor_clone = ggml_hardswish(ggml_ctx, src_clone[0]);
  12546. break;
  12547. case GGML_UNARY_OP_ABS:
  12548. tensor_clone = ggml_abs(ggml_ctx, src_clone[0]);
  12549. break;
  12550. case GGML_UNARY_OP_SOFTPLUS:
  12551. tensor_clone = ggml_softplus(ggml_ctx, src_clone[0]);
  12552. break;
  12553. case GGML_UNARY_OP_STEP:
  12554. tensor_clone = ggml_step(ggml_ctx, src_clone[0]);
  12555. break;
  12556. case GGML_UNARY_OP_ROUND:
  12557. tensor_clone = ggml_round(ggml_ctx, src_clone[0]);
  12558. break;
  12559. case GGML_UNARY_OP_CEIL:
  12560. tensor_clone = ggml_ceil(ggml_ctx, src_clone[0]);
  12561. break;
  12562. case GGML_UNARY_OP_FLOOR:
  12563. tensor_clone = ggml_floor(ggml_ctx, src_clone[0]);
  12564. break;
  12565. case GGML_UNARY_OP_TRUNC:
  12566. tensor_clone = ggml_trunc(ggml_ctx, src_clone[0]);
  12567. break;
  12568. default:
  12569. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12570. GGML_ABORT("fatal error");
  12571. }
  12572. } else if (tensor->op == GGML_OP_GLU) {
  12573. if (src_clone[1] == nullptr) {
  12574. tensor_clone = ggml_glu(ggml_ctx, src_clone[0], (ggml_glu_op) tensor->op_params[0], tensor->op_params[1]);
  12575. } else {
  12576. tensor_clone = ggml_glu_split(ggml_ctx, src_clone[0], src_clone[1], (ggml_glu_op) tensor->op_params[0]);
  12577. }
  12578. ggml_set_op_params_i32(tensor_clone, 2, ggml_get_op_params_i32(tensor, 2));
  12579. ggml_set_op_params_i32(tensor_clone, 3, ggml_get_op_params_i32(tensor, 3));
  12580. } else if (tensor->op == GGML_OP_CPY || tensor->op == GGML_OP_DUP) {
  12581. if (tensor->src[1] == nullptr) {
  12582. tensor_clone = ggml_dup(ggml_ctx, src_clone[0]);
  12583. tensor_clone->type = tensor->type;
  12584. } else {
  12585. tensor_clone = ggml_cpy(ggml_ctx, src_clone[0], src_clone[1]);
  12586. }
  12587. } else if (tensor->op == GGML_OP_CONT) {
  12588. tensor_clone = ggml_cont_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12589. } else if (tensor->op == GGML_OP_RESHAPE) {
  12590. tensor_clone = ggml_reshape_4d(ggml_ctx, src_clone[0], tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]);
  12591. } else if (tensor->op == GGML_OP_VIEW) {
  12592. 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]);
  12593. } else if (tensor->op == GGML_OP_PERMUTE) {
  12594. int32_t * params = (int32_t *)tensor->op_params;
  12595. tensor_clone = ggml_permute(ggml_ctx, src_clone[0], params[0], params[1], params[2], params[3]);
  12596. } else if (tensor->op == GGML_OP_TRANSPOSE) {
  12597. tensor_clone = ggml_transpose(ggml_ctx, src_clone[0]);
  12598. } else if (tensor->op == GGML_OP_GET_ROWS) {
  12599. tensor_clone = ggml_get_rows(ggml_ctx, src_clone[0], src_clone[1]);
  12600. } else if (tensor->op == GGML_OP_ARGSORT) {
  12601. tensor_clone = ggml_argsort(ggml_ctx, src_clone[0], (ggml_sort_order) *(int *)tensor->op_params);
  12602. } else if (tensor->op == GGML_OP_SUM) {
  12603. tensor_clone = ggml_sum(ggml_ctx, src_clone[0]);
  12604. } else if (tensor->op == GGML_OP_SUM_ROWS) {
  12605. tensor_clone = ggml_sum_rows(ggml_ctx, src_clone[0]);
  12606. } else if (tensor->op == GGML_OP_MEAN) {
  12607. tensor_clone = ggml_mean(ggml_ctx, src_clone[0]);
  12608. } else if (tensor->op == GGML_OP_ARGMAX) {
  12609. tensor_clone = ggml_argmax(ggml_ctx, src_clone[0]);
  12610. } else if (tensor->op == GGML_OP_COUNT_EQUAL) {
  12611. tensor_clone = ggml_count_equal(ggml_ctx, src_clone[0], src_clone[1]);
  12612. } else if (tensor->op == GGML_OP_IM2COL) {
  12613. const int32_t s0 = tensor->op_params[0];
  12614. const int32_t s1 = tensor->op_params[1];
  12615. const int32_t p0 = tensor->op_params[2];
  12616. const int32_t p1 = tensor->op_params[3];
  12617. const int32_t d0 = tensor->op_params[4];
  12618. const int32_t d1 = tensor->op_params[5];
  12619. const bool is_2D = tensor->op_params[6] == 1;
  12620. tensor_clone = ggml_im2col(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1, is_2D, tensor->type);
  12621. } else if (tensor->op == GGML_OP_IM2COL_3D) {
  12622. const int32_t s0 = tensor->op_params[0];
  12623. const int32_t s1 = tensor->op_params[1];
  12624. const int32_t s2 = tensor->op_params[2];
  12625. const int32_t p0 = tensor->op_params[3];
  12626. const int32_t p1 = tensor->op_params[4];
  12627. const int32_t p2 = tensor->op_params[5];
  12628. const int32_t d0 = tensor->op_params[6];
  12629. const int32_t d1 = tensor->op_params[7];
  12630. const int32_t d2 = tensor->op_params[8];
  12631. const int32_t IC = tensor->op_params[9];
  12632. tensor_clone = ggml_im2col_3d(ggml_ctx, src_clone[0], src_clone[1], IC, s0, s1, s2, p0, p1, p2, d0, d1, d2, tensor->type);
  12633. } else if (tensor->op == GGML_OP_TIMESTEP_EMBEDDING) {
  12634. const int32_t dim = tensor->op_params[0];
  12635. const int32_t max_period = tensor->op_params[1];
  12636. tensor_clone = ggml_timestep_embedding(ggml_ctx, src_clone[0], dim, max_period);
  12637. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_1D){
  12638. const int32_t s0 = tensor->op_params[0];
  12639. const int32_t p0 = tensor->op_params[1];
  12640. const int32_t d0 = tensor->op_params[2];
  12641. tensor_clone = ggml_conv_transpose_1d(ggml_ctx, src_clone[0], src_clone[1], s0, p0, d0);
  12642. } else if (tensor->op == GGML_OP_POOL_2D) {
  12643. enum ggml_op_pool op = static_cast<ggml_op_pool>(tensor->op_params[0]);
  12644. const int32_t k0 = tensor->op_params[1];
  12645. const int32_t k1 = tensor->op_params[2];
  12646. const int32_t s0 = tensor->op_params[3];
  12647. const int32_t s1 = tensor->op_params[4];
  12648. const int32_t p0 = tensor->op_params[5];
  12649. const int32_t p1 = tensor->op_params[6];
  12650. tensor_clone = ggml_pool_2d(ggml_ctx, src_clone[0], op, k0, k1, s0, s1, p0, p1);
  12651. } else if (tensor->op == GGML_OP_CONV_2D) {
  12652. const int32_t s0 = tensor->op_params[0];
  12653. const int32_t s1 = tensor->op_params[1];
  12654. const int32_t p0 = tensor->op_params[2];
  12655. const int32_t p1 = tensor->op_params[3];
  12656. const int32_t d0 = tensor->op_params[4];
  12657. const int32_t d1 = tensor->op_params[5];
  12658. tensor_clone = ggml_conv_2d(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  12659. } else if (tensor->op == GGML_OP_CONV_2D_DW) {
  12660. const int32_t s0 = tensor->op_params[0];
  12661. const int32_t s1 = tensor->op_params[1];
  12662. const int32_t p0 = tensor->op_params[2];
  12663. const int32_t p1 = tensor->op_params[3];
  12664. const int32_t d0 = tensor->op_params[4];
  12665. const int32_t d1 = tensor->op_params[5];
  12666. tensor_clone = ggml_conv_2d_dw_direct(ggml_ctx, src_clone[0], src_clone[1], s0, s1, p0, p1, d0, d1);
  12667. } else if (tensor->op == GGML_OP_CONV_TRANSPOSE_2D) {
  12668. const int32_t s = tensor->op_params[0];
  12669. tensor_clone = ggml_conv_transpose_2d_p0(ggml_ctx, src_clone[0], src_clone[1], s);
  12670. } else if (tensor->op == GGML_OP_LEAKY_RELU) {
  12671. const float * op_params = (const float *)tensor->op_params;
  12672. tensor_clone = ggml_leaky_relu(ggml_ctx, src_clone[0], op_params[0], false);
  12673. } else if (tensor->op == GGML_OP_RWKV_WKV6) {
  12674. tensor_clone = ggml_rwkv_wkv6(ggml_ctx, src_clone[0], src_clone[1],
  12675. src_clone[2], src_clone[3], src_clone[4], src_clone[5]);
  12676. } else if (tensor->op == GGML_OP_RWKV_WKV7) {
  12677. tensor_clone = ggml_rwkv_wkv7(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3],
  12678. src_clone[4], src_clone[5], src_clone[6]);
  12679. } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) {
  12680. src_clone[0]->flags = tensor->src[0]->flags;
  12681. tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1],
  12682. src_clone[2], src_clone[3], src_clone[4]);
  12683. } else if (tensor->op == GGML_OP_OPT_STEP_SGD) {
  12684. src_clone[0]->flags = tensor->src[0]->flags;
  12685. tensor_clone = ggml_opt_step_sgd(ggml_ctx, src_clone[0], src_clone[1],
  12686. src_clone[2]);
  12687. } else if (tensor->op == GGML_OP_ADD_ID) {
  12688. tensor_clone = ggml_add_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
  12689. } else if (tensor->op == GGML_OP_SSM_SCAN) {
  12690. tensor_clone = ggml_ssm_scan(ggml_ctx, src_clone[0], src_clone[1], src_clone[2],
  12691. src_clone[3], src_clone[4], src_clone[5], src_clone[6]);
  12692. } else if (tensor->op == GGML_OP_SSM_CONV) {
  12693. tensor_clone = ggml_ssm_conv(ggml_ctx, src_clone[0], src_clone[1]);
  12694. } else if (tensor->op == GGML_OP_ROLL) {
  12695. const int32_t s0 = tensor->op_params[0];
  12696. const int32_t s1 = tensor->op_params[1];
  12697. const int32_t s2 = tensor->op_params[2];
  12698. const int32_t s3 = tensor->op_params[3];
  12699. tensor_clone = ggml_roll(ggml_ctx, src_clone[0], s0, s1, s2, s3);
  12700. }
  12701. else {
  12702. std::cerr << "Missing vk_check_results OP: " << ggml_op_name(tensor->op) << std::endl;
  12703. GGML_ABORT("fatal error");
  12704. }
  12705. cloned_tensors[tensor] = tensor_clone;
  12706. }
  12707. ggml_cgraph * cgraph_cpu = ggml_new_graph(ggml_ctx);
  12708. ggml_build_forward_expand(cgraph_cpu, tensor_clone);
  12709. ggml_graph_compute_with_ctx(ggml_ctx, cgraph_cpu, 8);
  12710. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12711. ggml_vk_print_tensor(tensor_clone, "tensor_clone");
  12712. }
  12713. comp_size = ggml_nbytes(tensor_clone);
  12714. comp_result = malloc(comp_size);
  12715. memcpy(comp_result, tensor_clone->data, comp_size);
  12716. memcpy(comp_nb, tensor_clone->nb, sizeof(size_t) * GGML_MAX_DIMS);
  12717. for (auto m : cloned_mallocs) {
  12718. free(m);
  12719. }
  12720. ggml_free(ggml_ctx);
  12721. VK_LOG_DEBUG("END ggml_vk_check_results_0(" << tensor->name << ")");
  12722. }
  12723. static void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, int tensor_idx) {
  12724. ggml_tensor * tensor = cgraph->nodes[tensor_idx + ctx->num_additional_fused_ops];
  12725. if (tensor->op == GGML_OP_TRANSPOSE || tensor->op == GGML_OP_SET_ROWS) {
  12726. return;
  12727. }
  12728. if (!(vk_output_tensor > 0 && vk_output_tensor == check_counter) && check_counter <= vk_skip_checks) {
  12729. return;
  12730. }
  12731. VK_LOG_DEBUG("ggml_vk_check_results_1(" << tensor->name << ")");
  12732. ggml_tensor * src0 = tensor->src[0];
  12733. ggml_tensor * src1 = tensor->src[1];
  12734. ggml_tensor * src2 = tensor->src[2];
  12735. ggml_tensor * src3 = tensor->src[3];
  12736. void * tensor_data = tensor->data;
  12737. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  12738. size_t tensor_size = ggml_nbytes(tensor);
  12739. tensor_data = malloc(tensor_size);
  12740. ggml_backend_vk_buffer_context * buf_ctx = (ggml_backend_vk_buffer_context *)tensor->buffer->context;
  12741. vk_buffer& buffer_gpu = buf_ctx->dev_buffer;
  12742. uint64_t offset = vk_tensor_offset(tensor) + tensor->view_offs;
  12743. if (offset + tensor_size >= buffer_gpu->size) {
  12744. tensor_size = buffer_gpu->size - offset;
  12745. }
  12746. ggml_vk_buffer_read(buffer_gpu, offset, tensor_data, tensor_size);
  12747. }
  12748. float first_error_result = -1.0f;
  12749. float first_error_correct = -1.0f;
  12750. std::array<int, 4> first_error = { -1, -1, -1, -1 };
  12751. double avg_err = 0.0;
  12752. size_t counter = 0;
  12753. for (int i3 = 0; i3 < tensor->ne[3]; i3++) {
  12754. for (int i2 = 0; i2 < tensor->ne[2]; i2++) {
  12755. for (int i1 = 0; i1 < tensor->ne[1]; i1++) {
  12756. for (int i0 = 0; i0 < tensor->ne[0]; i0++) {
  12757. const bool buffer_size_fit = i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0] < comp_size;
  12758. float correct = 0.0f;
  12759. float result = 0.0f;
  12760. if (buffer_size_fit) {
  12761. if (tensor->type == GGML_TYPE_F32) {
  12762. correct = *(float *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12763. result = *(float *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12764. } else if (tensor->type == GGML_TYPE_F16) {
  12765. 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]));
  12766. 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]));
  12767. } else if (tensor->type == GGML_TYPE_BF16) {
  12768. 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]));
  12769. 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]));
  12770. } else if (tensor->type == GGML_TYPE_I32) {
  12771. correct = *(int32_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12772. result = *(int32_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12773. } else if (tensor->type == GGML_TYPE_I64) {
  12774. correct = *(int64_t *) ((char *) comp_result + i3*comp_nb[3] + i2*comp_nb[2] + i1*comp_nb[1] + i0*comp_nb[0]);
  12775. result = *(int64_t *) ((char *) tensor_data + i3*tensor->nb[3] + i2*tensor->nb[2] + i1*tensor->nb[1] + i0*tensor->nb[0]);
  12776. } else {
  12777. std::cerr << "Results check not implemented for type " << ggml_type_name(tensor->type) << std::endl;
  12778. }
  12779. } else {
  12780. std::cerr << "Missing debug code for type " << ggml_type_name(tensor->type) << std::endl;
  12781. GGML_ABORT("fatal error");
  12782. }
  12783. if ((std::isnan(correct) != std::isnan(result)) || (std::isinf(correct) != std::isinf(result)) || !buffer_size_fit) {
  12784. 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;
  12785. 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;
  12786. if (src0 != nullptr) {
  12787. 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;
  12788. }
  12789. if (src1 != nullptr) {
  12790. 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;
  12791. }
  12792. if (src2 != nullptr) {
  12793. 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;
  12794. }
  12795. if (src3 != nullptr) {
  12796. 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;
  12797. }
  12798. 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;
  12799. std::cerr << std::endl << "Result:" << std::endl;
  12800. ggml_vk_print_tensor_area(tensor, tensor_data, i0, i1, i2, i3);
  12801. std::cerr << std::endl << "Correct:" << std::endl;
  12802. ggml_vk_print_tensor_area(tensor, comp_result, i0, i1, i2, i3);
  12803. std::cerr << std::endl;
  12804. std::vector<const ggml_tensor *> done;
  12805. ggml_vk_print_graph_origin(tensor, done);
  12806. GGML_ABORT("fatal error");
  12807. }
  12808. const double denom = std::fabs(correct) > 1.0f ? (std::fabs(correct) > 1e-8 ? std::fabs(correct) : 1e-8) : 1.0f;
  12809. if (first_error[0] == -1 && std::fabs(correct - result) / denom > 0.5) {
  12810. first_error[0] = i0;
  12811. first_error[1] = i1;
  12812. first_error[2] = i2;
  12813. first_error[3] = i3;
  12814. first_error_result = result;
  12815. first_error_correct = correct;
  12816. }
  12817. // Special case, value is infinite, avoid NaN result in avg_err
  12818. // NaN also appears in results, if both are nan error is 0
  12819. if (!std::isinf(correct) && !std::isinf(result) && !std::isnan(correct) && !std::isnan(result)) {
  12820. avg_err += std::fabs(correct - result) / denom;
  12821. }
  12822. counter++;
  12823. }
  12824. }
  12825. }
  12826. }
  12827. avg_err /= counter;
  12828. if (vk_output_tensor > 0 && vk_output_tensor == check_counter) {
  12829. std::cerr << "TENSOR CHECK: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  12830. 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;
  12831. if (src0 != nullptr) {
  12832. 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;
  12833. }
  12834. if (src1 != nullptr) {
  12835. 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;
  12836. }
  12837. if (src2 != nullptr) {
  12838. 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;
  12839. }
  12840. if (src3 != nullptr) {
  12841. 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;
  12842. }
  12843. 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;
  12844. std::cerr << std::endl << "Result:" << std::endl;
  12845. ggml_vk_print_tensor_area(tensor, tensor_data, 5, 5, 0, 0);
  12846. std::cerr << std::endl << "Correct:" << std::endl;
  12847. ggml_vk_print_tensor_area(tensor, comp_result, 5, 5, 0, 0);
  12848. std::cerr << std::endl;
  12849. std::vector<const ggml_tensor *> done;
  12850. ggml_vk_print_graph_origin(tensor, done);
  12851. }
  12852. if (avg_err > 0.5 || std::isnan(avg_err)) {
  12853. std::cerr << "ERROR: avg_err=" << avg_err << " in " << ggml_op_name(tensor->op) << " (check " << check_counter << ")" << std::endl;
  12854. 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;
  12855. if (src0 != nullptr) {
  12856. 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;
  12857. }
  12858. if (src1 != nullptr) {
  12859. 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;
  12860. }
  12861. if (src2 != nullptr) {
  12862. 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;
  12863. }
  12864. if (src3 != nullptr) {
  12865. 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;
  12866. }
  12867. 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;
  12868. std::cerr << std::endl << "Result:" << std::endl;
  12869. ggml_vk_print_tensor_area(tensor, tensor_data, first_error[0], first_error[1], first_error[2], first_error[3]);
  12870. std::cerr << std::endl << "Correct:" << std::endl;
  12871. ggml_vk_print_tensor_area(tensor, comp_result, first_error[0], first_error[1], first_error[2], first_error[3]);
  12872. std::cerr << std::endl;
  12873. std::vector<const ggml_tensor *> done;
  12874. ggml_vk_print_graph_origin(tensor, done);
  12875. GGML_ABORT("fatal error");
  12876. } else {
  12877. std::cerr << check_counter << " " << tensor->name << " op=" << ggml_op_name(tensor->op) << " avg_err=" << avg_err << std::endl;
  12878. }
  12879. free(comp_result);
  12880. comp_result = nullptr;
  12881. comp_size = 0;
  12882. if (ggml_backend_buffer_is_vk(tensor->buffer)) {
  12883. free(tensor_data);
  12884. }
  12885. VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
  12886. }
  12887. #endif
  12888. GGML_BACKEND_DL_IMPL(ggml_backend_vk_reg)